lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | 5fff822545acfd5f0e9b265730f15cfe0397bf04 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.popup;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.icons.AllIcons;
import com.intellij.ide.*;
import com.intellij.ide.actions.WindowAction;
import com.intellij.ide.ui.PopupLocationTracker;
import com.intellij.ide.ui.ScreenAreaConsumer;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.application.TransactionGuardImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorActivityManager;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.ui.popup.*;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.*;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.openapi.wm.impl.IdeGlassPaneImpl;
import com.intellij.ui.*;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.mac.touchbar.TouchBarsManager;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.ui.speedSearch.ListWithFilter;
import com.intellij.ui.speedSearch.SpeedSearch;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.WeakList;
import com.intellij.util.ui.*;
import com.intellij.util.ui.accessibility.AccessibleContextUtil;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Supplier;
import static java.awt.event.MouseEvent.*;
import static java.awt.event.WindowEvent.WINDOW_ACTIVATED;
import static java.awt.event.WindowEvent.WINDOW_GAINED_FOCUS;
public class AbstractPopup implements JBPopup, ScreenAreaConsumer {
public static final String SHOW_HINTS = "ShowHints";
// Popup size stored with DimensionService is null first time
// In this case you can put Dimension in content client properties to adjust size
// Zero or negative values (with/height or both) would be ignored (actual values would be obtained from preferred size)
public static final String FIRST_TIME_SIZE = "FirstTimeSize";
private static final Logger LOG = Logger.getInstance(AbstractPopup.class);
private PopupComponent myPopup;
private MyContentPanel myContent;
private JComponent myPreferredFocusedComponent;
private boolean myRequestFocus;
private boolean myFocusable;
private boolean myForcedHeavyweight;
private boolean myLocateWithinScreen;
private boolean myResizable;
private WindowResizeListener myResizeListener;
private WindowMoveListener myMoveListener;
private JPanel myHeaderPanel;
private CaptionPanel myCaption;
private JComponent myComponent;
private SpeedSearch mySpeedSearchFoundInRootComponent;
private String myDimensionServiceKey;
private Computable<Boolean> myCallBack;
private Project myProject;
private boolean myCancelOnClickOutside;
private final List<JBPopupListener> myListeners = new CopyOnWriteArrayList<>();
private boolean myUseDimServiceForXYLocation;
private MouseChecker myCancelOnMouseOutCallback;
private Canceller myMouseOutCanceller;
private boolean myCancelOnWindow;
private boolean myCancelOnWindowDeactivation = true;
private Dimension myForcedSize;
private Point myForcedLocation;
private boolean myCancelKeyEnabled;
private boolean myLocateByContent;
private Dimension myMinSize;
private List<Object> myUserData;
private boolean myShadowed;
private float myAlpha;
private float myLastAlpha;
private MaskProvider myMaskProvider;
private Window myWindow;
private boolean myInStack;
private MyWindowListener myWindowListener;
private boolean myModalContext;
private Component[] myFocusOwners;
private PopupBorder myPopupBorder;
private Dimension myRestoreWindowSize;
protected Component myOwner;
private Component myRequestorComponent;
private boolean myHeaderAlwaysFocusable;
private boolean myMovable;
private JComponent myHeaderComponent;
InputEvent myDisposeEvent;
private Runnable myFinalRunnable;
private Runnable myOkHandler;
private @Nullable BooleanFunction<? super KeyEvent> myKeyEventHandler;
protected boolean myOk;
private final List<Runnable> myResizeListeners = new ArrayList<>();
private static final WeakList<JBPopup> all = new WeakList<>();
private boolean mySpeedSearchAlwaysShown;
protected final SpeedSearch mySpeedSearch = new SpeedSearch() {
boolean searchFieldShown;
@Override
public void update() {
mySpeedSearchPatternField.getTextEditor().setBackground(UIUtil.getTextFieldBackground());
onSpeedSearchPatternChanged();
mySpeedSearchPatternField.setText(getFilter());
if (!mySpeedSearchAlwaysShown) {
if (isHoldingFilter() && !searchFieldShown) {
setHeaderComponent(mySpeedSearchPatternField);
searchFieldShown = true;
}
else if (!isHoldingFilter() && searchFieldShown) {
setHeaderComponent(null);
searchFieldShown = false;
}
}
}
@Override
public void noHits() {
mySpeedSearchPatternField.getTextEditor().setBackground(LightColors.RED);
}
};
protected SearchTextField mySpeedSearchPatternField;
private boolean myNativePopup;
private boolean myMayBeParent;
private JLabel myAdComponent;
private boolean myDisposed;
private boolean myNormalWindowLevel;
private UiActivity myActivityKey;
private Disposable myProjectDisposable;
private volatile State myState = State.NEW;
void setNormalWindowLevel(boolean normalWindowLevel) {
myNormalWindowLevel = normalWindowLevel;
}
private enum State {NEW, INIT, SHOWING, SHOWN, CANCEL, DISPOSE}
private void debugState(@NonNls @NotNull String message, State @NotNull ... states) {
if (LOG.isDebugEnabled()) {
LOG.debug(hashCode() + " - " + message);
if (!ApplicationManager.getApplication().isDispatchThread()) {
LOG.debug("unexpected thread");
}
for (State state : states) {
if (state == myState) {
return;
}
}
LOG.debug(new IllegalStateException("myState=" + myState));
}
}
protected AbstractPopup() { }
protected @NotNull AbstractPopup init(Project project,
@NotNull JComponent component,
@Nullable JComponent preferredFocusedComponent,
boolean requestFocus,
boolean focusable,
boolean movable,
String dimensionServiceKey,
boolean resizable,
@Nullable String caption,
@Nullable Computable<Boolean> callback,
boolean cancelOnClickOutside,
@NotNull Set<? extends JBPopupListener> listeners,
boolean useDimServiceForXYLocation,
ActiveComponent commandButton,
@Nullable IconButton cancelButton,
@Nullable MouseChecker cancelOnMouseOutCallback,
boolean cancelOnWindow,
@Nullable ActiveIcon titleIcon,
boolean cancelKeyEnabled,
boolean locateByContent,
boolean placeWithinScreenBounds,
@Nullable Dimension minSize,
float alpha,
@Nullable MaskProvider maskProvider,
boolean inStack,
boolean modalContext,
Component @NotNull [] focusOwners,
@Nullable String adText,
int adTextAlignment,
boolean headerAlwaysFocusable,
@NotNull List<? extends Pair<ActionListener, KeyStroke>> keyboardActions,
Component settingsButtons,
final @Nullable Processor<? super JBPopup> pinCallback,
boolean mayBeParent,
boolean showShadow,
boolean showBorder,
Color borderColor,
boolean cancelOnWindowDeactivation,
@Nullable BooleanFunction<? super KeyEvent> keyEventHandler) {
assert !requestFocus || focusable : "Incorrect argument combination: requestFocus=true focusable=false";
all.add(this);
myActivityKey = new UiActivity.Focus("Popup:" + this);
myProject = project;
myComponent = component;
mySpeedSearchFoundInRootComponent =
findInComponentHierarchy(component, it -> it instanceof ListWithFilter ? ((ListWithFilter)it).getSpeedSearch() : null);
myPopupBorder = showBorder ? borderColor != null ? PopupBorder.Factory.createColored(borderColor) :
PopupBorder.Factory.create(true, showShadow) :
PopupBorder.Factory.createEmpty();
myShadowed = showShadow;
myContent = createContentPanel(resizable, myPopupBorder, false);
myMayBeParent = mayBeParent;
myCancelOnWindowDeactivation = cancelOnWindowDeactivation;
myContent.add(component, BorderLayout.CENTER);
if (adText != null) {
setAdText(adText, adTextAlignment);
}
myCancelKeyEnabled = cancelKeyEnabled;
myLocateByContent = locateByContent;
myLocateWithinScreen = placeWithinScreenBounds;
myAlpha = alpha;
myMaskProvider = maskProvider;
myInStack = inStack;
myModalContext = modalContext;
myFocusOwners = focusOwners;
myHeaderAlwaysFocusable = headerAlwaysFocusable;
myMovable = movable;
ActiveIcon actualIcon = titleIcon == null ? new ActiveIcon(EmptyIcon.ICON_0) : titleIcon;
myHeaderPanel = new JPanel(new BorderLayout());
if (caption != null) {
if (!caption.isEmpty()) {
myCaption = new TitlePanel(actualIcon.getRegular(), actualIcon.getInactive());
((TitlePanel)myCaption).setText(caption);
}
else {
myCaption = new CaptionPanel();
}
if (pinCallback != null) {
Icon icon = ToolWindowManager.getInstance(myProject != null ? myProject : ProjectUtil.guessCurrentProject((JComponent)myOwner))
.getLocationIcon(ToolWindowId.FIND, AllIcons.General.Pin_tab);
myCaption.setButtonComponent(new InplaceButton(
new IconButton(IdeBundle.message("show.in.find.window.button.name"), icon),
e -> pinCallback.process(this)
), JBUI.Borders.empty(4));
}
else if (cancelButton != null) {
myCaption.setButtonComponent(new InplaceButton(cancelButton, e -> cancel()), JBUI.Borders.empty(4));
}
else if (commandButton != null) {
myCaption.setButtonComponent(commandButton, null);
}
}
else {
myCaption = new CaptionPanel();
myCaption.setBorder(null);
myCaption.setPreferredSize(JBUI.emptySize());
}
setWindowActive(myHeaderAlwaysFocusable);
myHeaderPanel.add(myCaption, BorderLayout.NORTH);
myContent.add(myHeaderPanel, BorderLayout.NORTH);
myForcedHeavyweight = true;
myResizable = resizable;
myPreferredFocusedComponent = preferredFocusedComponent;
myRequestFocus = requestFocus;
myFocusable = focusable;
myDimensionServiceKey = dimensionServiceKey;
myCallBack = callback;
myCancelOnClickOutside = cancelOnClickOutside;
myCancelOnMouseOutCallback = cancelOnMouseOutCallback;
myListeners.addAll(listeners);
myUseDimServiceForXYLocation = useDimServiceForXYLocation;
myCancelOnWindow = cancelOnWindow;
myMinSize = minSize;
for (Pair<ActionListener, KeyStroke> pair : keyboardActions) {
myContent.registerKeyboardAction(pair.getFirst(), pair.getSecond(), JComponent.WHEN_IN_FOCUSED_WINDOW);
}
if (settingsButtons != null) {
myCaption.addSettingsComponent(settingsButtons);
}
myKeyEventHandler = keyEventHandler;
debugState("popup initialized", State.NEW);
myState = State.INIT;
return this;
}
private void setWindowActive(boolean active) {
boolean value = myHeaderAlwaysFocusable || active;
if (myCaption != null) {
myCaption.setActive(value);
}
myPopupBorder.setActive(value);
myContent.repaint();
}
protected @NotNull MyContentPanel createContentPanel(final boolean resizable, @NotNull PopupBorder border, boolean isToDrawMacCorner) {
return new MyContentPanel(border);
}
public void setShowHints(boolean show) {
final Window ancestor = getContentWindow(myComponent);
if (ancestor instanceof RootPaneContainer) {
final JRootPane rootPane = ((RootPaneContainer)ancestor).getRootPane();
if (rootPane != null) {
rootPane.putClientProperty(SHOW_HINTS, show);
}
}
}
public String getDimensionServiceKey() {
return myDimensionServiceKey;
}
public void setDimensionServiceKey(final @Nullable String dimensionServiceKey) {
myDimensionServiceKey = dimensionServiceKey;
}
public void setAdText(@NotNull @NlsContexts.PopupAdvertisement String s) {
setAdText(s, SwingConstants.LEFT);
}
public @NotNull PopupBorder getPopupBorder() {
return myPopupBorder;
}
@Override
public void setAdText(final @NotNull String s, int alignment) {
if (myAdComponent == null) {
myAdComponent = HintUtil.createAdComponent(s, JBUI.CurrentTheme.Advertiser.border(), alignment);
JPanel wrapper = new JPanel(new BorderLayout());
wrapper.setOpaque(false);
wrapper.add(myAdComponent, BorderLayout.CENTER);
myContent.add(wrapper, BorderLayout.SOUTH);
pack(false, true);
}
else {
myAdComponent.setText(s);
myAdComponent.setHorizontalAlignment(alignment);
}
}
public static @NotNull Point getCenterOf(@NotNull Component aContainer, @NotNull JComponent content) {
return getCenterOf(aContainer, content.getPreferredSize());
}
private static @NotNull Point getCenterOf(@NotNull Component aContainer, @NotNull Dimension contentSize) {
final JComponent component = getTargetComponent(aContainer);
Rectangle visibleBounds = component != null
? component.getVisibleRect()
: new Rectangle(aContainer.getSize());
Point containerScreenPoint = visibleBounds.getLocation();
SwingUtilities.convertPointToScreen(containerScreenPoint, aContainer);
visibleBounds.setLocation(containerScreenPoint);
return UIUtil.getCenterPoint(visibleBounds, contentSize);
}
@Override
public void showCenteredInCurrentWindow(@NotNull Project project) {
if (UiInterceptors.tryIntercept(this)) return;
Window window = null;
Component focusedComponent = getWndManager().getFocusedComponent(project);
if (focusedComponent != null) {
Component parent = UIUtil.findUltimateParent(focusedComponent);
if (parent instanceof Window) {
window = (Window)parent;
}
}
if (window == null) {
window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
}
if (window != null && window.isShowing()) {
showInCenterOf(window);
}
}
@Override
public void showInCenterOf(@NotNull Component aComponent) {
HelpTooltip.setMasterPopup(aComponent, this);
Point popupPoint = getCenterOf(aComponent, getPreferredContentSize());
show(aComponent, popupPoint.x, popupPoint.y, false);
}
@Override
public void showUnderneathOf(@NotNull Component aComponent) {
show(new RelativePoint(aComponent, new Point(JBUIScale.scale(2), aComponent.getHeight())));
}
@Override
public void show(@NotNull RelativePoint aPoint) {
if (UiInterceptors.tryIntercept(this)) return;
HelpTooltip.setMasterPopup(aPoint.getOriginalComponent(), this);
Point screenPoint = aPoint.getScreenPoint();
show(aPoint.getComponent(), screenPoint.x, screenPoint.y, false);
}
@Override
public void showInScreenCoordinates(@NotNull Component owner, @NotNull Point point) {
show(owner, point.x, point.y, false);
}
@Override
public @NotNull Point getBestPositionFor(@NotNull DataContext dataContext) {
final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
if (editor != null && editor.getComponent().isShowing()) {
return getBestPositionFor(editor).getScreenPoint();
}
return relativePointByQuickSearch(dataContext).getScreenPoint();
}
@Override
public void showInBestPositionFor(@NotNull DataContext dataContext) {
final Editor editor = CommonDataKeys.EDITOR_EVEN_IF_INACTIVE.getData(dataContext);
if (editor != null && editor.getComponent().isShowing()) {
showInBestPositionFor(editor);
}
else {
show(relativePointByQuickSearch(dataContext));
}
}
@Override
public void showInFocusCenter() {
final Component focused = getWndManager().getFocusedComponent(myProject);
if (focused != null) {
showInCenterOf(focused);
}
else {
final WindowManager manager = WindowManager.getInstance();
final JFrame frame = myProject != null ? manager.getFrame(myProject) : manager.findVisibleFrame();
showInCenterOf(frame.getRootPane());
}
}
private @NotNull RelativePoint relativePointByQuickSearch(@NotNull DataContext dataContext) {
Rectangle dominantArea = PlatformDataKeys.DOMINANT_HINT_AREA_RECTANGLE.getData(dataContext);
if (dominantArea != null) {
final Component focusedComponent = getWndManager().getFocusedComponent(myProject);
if (focusedComponent != null) {
Window window = SwingUtilities.windowForComponent(focusedComponent);
JLayeredPane layeredPane;
if (window instanceof JFrame) {
layeredPane = ((JFrame)window).getLayeredPane();
}
else if (window instanceof JDialog) {
layeredPane = ((JDialog)window).getLayeredPane();
}
else if (window instanceof JWindow) {
layeredPane = ((JWindow)window).getLayeredPane();
}
else {
throw new IllegalStateException("cannot find parent window: project=" + myProject + "; window=" + window);
}
return relativePointWithDominantRectangle(layeredPane, dominantArea);
}
}
RelativePoint location;
Component contextComponent = dataContext.getData(PlatformDataKeys.CONTEXT_COMPONENT);
if (contextComponent == myComponent) {
location = new RelativePoint(myComponent, new Point());
}
else {
location = JBPopupFactory.getInstance().guessBestPopupLocation(dataContext);
}
if (myLocateWithinScreen) {
Point screenPoint = location.getScreenPoint();
Rectangle rectangle = new Rectangle(screenPoint, getSizeForPositioning());
Rectangle screen = ScreenUtil.getScreenRectangle(screenPoint);
ScreenUtil.moveToFit(rectangle, screen, null);
location = new RelativePoint(rectangle.getLocation()).getPointOn(location.getComponent());
}
return location;
}
private Dimension getSizeForPositioning() {
Dimension size = getSize();
if (size == null) {
size = getStoredSize();
}
if (size == null) {
size = myContent.getPreferredSize();
}
return size;
}
@Override
public void showInBestPositionFor(@NotNull Editor editor) {
// Intercept before the following assert; otherwise assertion may fail
if (UiInterceptors.tryIntercept(this)) return;
assert EditorActivityManager.getInstance().isVisible(editor) : "Editor must be showing on the screen";
// Set the accessible parent so that screen readers don't announce
// a window context change -- the tooltip is "logically" hosted
// inside the component (e.g. editor) it appears on top of.
AccessibleContextUtil.setParent((Component)myComponent, editor.getContentComponent());
show(getBestPositionFor(editor));
}
private @NotNull RelativePoint getBestPositionFor(@NotNull Editor editor) {
DataContext context = ((EditorEx)editor).getDataContext();
Rectangle dominantArea = PlatformDataKeys.DOMINANT_HINT_AREA_RECTANGLE.getData(context);
if (dominantArea != null && !myRequestFocus) {
final JLayeredPane layeredPane = editor.getContentComponent().getRootPane().getLayeredPane();
return relativePointWithDominantRectangle(layeredPane, dominantArea);
}
else {
return guessBestPopupLocation(editor);
}
}
private @NotNull RelativePoint guessBestPopupLocation(@NotNull Editor editor) {
RelativePoint preferredLocation = JBPopupFactory.getInstance().guessBestPopupLocation(editor);
Dimension targetSize = getSizeForPositioning();
Point preferredPoint = preferredLocation.getScreenPoint();
Point result = getLocationAboveEditorLineIfPopupIsClippedAtTheBottom(preferredPoint, targetSize, editor);
if (myLocateWithinScreen) {
Rectangle rectangle = new Rectangle(result, targetSize);
Rectangle screen = ScreenUtil.getScreenRectangle(preferredPoint);
ScreenUtil.moveToFit(rectangle, screen, null);
result = rectangle.getLocation();
}
return toRelativePoint(result, preferredLocation.getComponent());
}
private static @NotNull RelativePoint toRelativePoint(@NotNull Point screenPoint, @Nullable Component component) {
if (component == null) {
return RelativePoint.fromScreen(screenPoint);
}
SwingUtilities.convertPointFromScreen(screenPoint, component);
return new RelativePoint(component, screenPoint);
}
private static @NotNull Point getLocationAboveEditorLineIfPopupIsClippedAtTheBottom(@NotNull Point originalLocation,
@NotNull Dimension popupSize,
@NotNull Editor editor) {
Rectangle preferredBounds = new Rectangle(originalLocation, popupSize);
Rectangle adjustedBounds = new Rectangle(preferredBounds);
ScreenUtil.moveRectangleToFitTheScreen(adjustedBounds);
if (preferredBounds.y - adjustedBounds.y <= 0) {
return originalLocation;
}
int adjustedY = preferredBounds.y - editor.getLineHeight() - popupSize.height;
if (adjustedY < 0) {
return originalLocation;
}
return new Point(preferredBounds.x, adjustedY);
}
/**
* @see #addListener
* @deprecated use public API instead
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.1")
protected void addPopupListener(@NotNull JBPopupListener listener) {
myListeners.add(listener);
}
private @NotNull RelativePoint relativePointWithDominantRectangle(@NotNull JLayeredPane layeredPane, @NotNull Rectangle bounds) {
Dimension size = getSizeForPositioning();
List<Supplier<Point>> optionsToTry = Arrays.asList(() -> new Point(bounds.x + bounds.width, bounds.y),
() -> new Point(bounds.x - size.width, bounds.y));
for (Supplier<Point> option : optionsToTry) {
Point location = option.get();
SwingUtilities.convertPointToScreen(location, layeredPane);
Point adjustedLocation = fitToScreenAdjustingVertically(location, size);
if (adjustedLocation != null) return new RelativePoint(adjustedLocation).getPointOn(layeredPane);
}
setDimensionServiceKey(null); // going to cut width
Point rightTopCorner = new Point(bounds.x + bounds.width, bounds.y);
final Point rightTopCornerScreen = (Point)rightTopCorner.clone();
SwingUtilities.convertPointToScreen(rightTopCornerScreen, layeredPane);
Rectangle screen = ScreenUtil.getScreenRectangle(rightTopCornerScreen.x, rightTopCornerScreen.y);
final int spaceOnTheLeft = bounds.x;
final int spaceOnTheRight = screen.x + screen.width - rightTopCornerScreen.x;
if (spaceOnTheLeft > spaceOnTheRight) {
myComponent.setPreferredSize(new Dimension(spaceOnTheLeft, Math.max(size.height, JBUIScale.scale(200))));
return new RelativePoint(layeredPane, new Point(0, bounds.y));
}
else {
myComponent.setPreferredSize(new Dimension(spaceOnTheRight, Math.max(size.height, JBUIScale.scale(200))));
return new RelativePoint(layeredPane, rightTopCorner);
}
}
// positions are relative to screen
private static @Nullable Point fitToScreenAdjustingVertically(@NotNull Point position, @NotNull Dimension size) {
Rectangle screenRectangle = ScreenUtil.getScreenRectangle(position);
Rectangle rectangle = new Rectangle(position, size);
if (rectangle.height > screenRectangle.height ||
rectangle.x < screenRectangle.x ||
rectangle.x + rectangle.width > screenRectangle.x + screenRectangle.width) {
return null;
}
ScreenUtil.moveToFit(rectangle, screenRectangle, null);
return rectangle.getLocation();
}
private @NotNull Dimension getPreferredContentSize() {
if (myForcedSize != null) {
return myForcedSize;
}
Dimension size = getStoredSize();
if (size != null) return size;
return myComponent.getPreferredSize();
}
@Override
public final void closeOk(@Nullable InputEvent e) {
setOk(true);
myFinalRunnable = FunctionUtil.composeRunnables(myOkHandler, myFinalRunnable);
cancel(e);
}
@Override
public final void cancel() {
InputEvent inputEvent = null;
AWTEvent event = IdeEventQueue.getInstance().getTrueCurrentEvent();
if (event instanceof InputEvent && myPopup != null) {
InputEvent ie = (InputEvent)event;
Window window = myPopup.getWindow();
if (window != null && UIUtil.isDescendingFrom(ie.getComponent(), window)) {
inputEvent = ie;
}
}
cancel(inputEvent);
}
@Override
public void setRequestFocus(boolean requestFocus) {
myRequestFocus = requestFocus;
}
@Override
public void cancel(InputEvent e) {
if (myState == State.CANCEL || myState == State.DISPOSE) {
return;
}
debugState("cancel popup", State.SHOWN);
myState = State.CANCEL;
if (isDisposed()) return;
if (myPopup != null) {
if (!canClose()) {
debugState("cannot cancel popup", State.CANCEL);
myState = State.SHOWN;
return;
}
storeDimensionSize();
if (myUseDimServiceForXYLocation) {
final JRootPane root = myComponent.getRootPane();
if (root != null) {
Point location = getLocationOnScreen(root.getParent());
if (location != null) {
storeLocation(fixLocateByContent(location, true));
}
}
}
if (e instanceof MouseEvent) {
IdeEventQueue.getInstance().blockNextEvents((MouseEvent)e);
}
myPopup.hide(false);
if (ApplicationManager.getApplication() != null) {
StackingPopupDispatcher.getInstance().onPopupHidden(this);
}
disposePopup();
}
myListeners.forEach(listener -> listener.onClosed(new LightweightWindowEvent(this, myOk)));
Disposer.dispose(this, false);
if (myProjectDisposable != null) {
Disposer.dispose(myProjectDisposable);
}
}
private void disposePopup() {
all.remove(this);
if (myPopup != null) {
resetWindow();
myPopup.hide(true);
}
myPopup = null;
}
@Override
public boolean canClose() {
return myCallBack == null || myCallBack.compute().booleanValue();
}
@Override
public boolean isVisible() {
if (myPopup == null) return false;
Window window = myPopup.getWindow();
if (window != null && window.isShowing()) return true;
if (LOG.isDebugEnabled()) LOG.debug("window hidden, popup's state: " + myState);
return false;
}
@Override
public void show(final @NotNull Component owner) {
show(owner, -1, -1, true);
}
public void show(@NotNull Component owner, int aScreenX, int aScreenY, final boolean considerForcedXY) {
if (UiInterceptors.tryIntercept(this)) return;
if (ApplicationManager.getApplication() != null && ApplicationManager.getApplication().isHeadlessEnvironment()) return;
if (isDisposed()) {
throw new IllegalStateException("Popup was already disposed. Recreate a new instance to show again");
}
ApplicationManager.getApplication().assertIsDispatchThread();
assert myState == State.INIT : "Popup was already shown. Recreate a new instance to show again.";
debugState("show popup", State.INIT);
myState = State.SHOWING;
installProjectDisposer();
addActivity();
final boolean shouldShow = beforeShow();
if (!shouldShow) {
removeActivity();
debugState("rejected to show popup", State.SHOWING);
myState = State.INIT;
return;
}
prepareToShow();
installWindowHook(this);
Dimension sizeToSet = getStoredSize();
if (myForcedSize != null) {
sizeToSet = myForcedSize;
}
Rectangle screen = ScreenUtil.getScreenRectangle(aScreenX, aScreenY);
if (myLocateWithinScreen) {
Dimension preferredSize = myContent.getPreferredSize();
Object o = myContent.getClientProperty(FIRST_TIME_SIZE);
if (sizeToSet == null && o instanceof Dimension) {
int w = ((Dimension)o).width;
int h = ((Dimension)o).height;
if (w > 0) preferredSize.width = w;
if (h > 0) preferredSize.height = h;
sizeToSet = preferredSize;
}
Dimension size = sizeToSet != null ? sizeToSet : preferredSize;
if (size.width > screen.width) {
size.width = screen.width;
sizeToSet = size;
}
if (size.height > screen.height) {
size.height = screen.height;
sizeToSet = size;
}
}
if (sizeToSet != null) {
JBInsets.addTo(sizeToSet, myContent.getInsets());
sizeToSet.width = Math.max(sizeToSet.width, myContent.getMinimumSize().width);
sizeToSet.height = Math.max(sizeToSet.height, myContent.getMinimumSize().height);
myContent.setSize(sizeToSet);
myContent.setPreferredSize(sizeToSet);
}
Point xy = new Point(aScreenX, aScreenY);
boolean adjustXY = true;
if (myUseDimServiceForXYLocation) {
Point storedLocation = getStoredLocation();
if (storedLocation != null) {
xy = storedLocation;
adjustXY = false;
}
}
if (adjustXY) {
final Insets insets = myContent.getInsets();
if (insets != null) {
xy.x -= insets.left;
xy.y -= insets.top;
}
}
if (considerForcedXY && myForcedLocation != null) {
xy = myForcedLocation;
}
fixLocateByContent(xy, false);
Rectangle targetBounds = new Rectangle(xy, myContent.getPreferredSize());
if (targetBounds.width > screen.width || targetBounds.height > screen.height) {
StringBuilder sb = new StringBuilder("popup preferred size is bigger than screen: ");
sb.append(targetBounds.width).append("x").append(targetBounds.height);
IJSwingUtilities.appendComponentClassNames(sb, myContent);
LOG.warn(sb.toString());
}
Rectangle original = new Rectangle(targetBounds);
if (myLocateWithinScreen) {
ScreenUtil.moveToFit(targetBounds, screen, null);
}
if (myMouseOutCanceller != null) {
myMouseOutCanceller.myEverEntered = targetBounds.equals(original);
}
myOwner = getFrameOrDialog(owner); // use correct popup owner for non-modal dialogs too
if (myOwner == null) {
myOwner = owner;
}
myRequestorComponent = owner;
boolean forcedDialog = myMayBeParent || SystemInfo.isMac && !(myOwner instanceof IdeFrame) && myOwner.isShowing();
PopupComponent.Factory factory = getFactory(myForcedHeavyweight || myResizable, forcedDialog);
myNativePopup = factory.isNativePopup();
Component popupOwner = myOwner;
if (popupOwner instanceof RootPaneContainer && !(popupOwner instanceof IdeFrame && !Registry.is("popup.fix.ide.frame.owner"))) {
// JDK uses cached heavyweight popup for a window ancestor
RootPaneContainer root = (RootPaneContainer)popupOwner;
popupOwner = root.getRootPane();
LOG.debug("popup owner fixed for JDK cache");
}
if (LOG.isDebugEnabled()) {
LOG.debug("expected preferred size: " + myContent.getPreferredSize());
}
myPopup = factory.getPopup(popupOwner, myContent, targetBounds.x, targetBounds.y, this);
if (LOG.isDebugEnabled()) {
LOG.debug(" actual preferred size: " + myContent.getPreferredSize());
}
if (targetBounds.width != myContent.getWidth() || targetBounds.height != myContent.getHeight()) {
// JDK uses cached heavyweight popup that is not initialized properly
LOG.debug("the expected size is not equal to the actual size");
Window popup = myPopup.getWindow();
if (popup != null) {
popup.setSize(targetBounds.width, targetBounds.height);
if (myContent.getParent().getComponentCount() != 1) {
LOG.debug("unexpected count of components in heavy-weight popup");
}
}
else {
LOG.debug("cannot fix size for non-heavy-weight popup");
}
}
if (myResizable) {
final JRootPane root = myContent.getRootPane();
final IdeGlassPaneImpl glass = new IdeGlassPaneImpl(root);
root.setGlassPane(glass);
int i = Registry.intValue("ide.popup.resizable.border.sensitivity", 4);
WindowResizeListener resizeListener = new WindowResizeListener(
myComponent,
myMovable ? JBUI.insets(i) : JBUI.insets(0, 0, i, i),
null) {
private Cursor myCursor;
@Override
protected void setCursor(Component content, Cursor cursor) {
if (myCursor != cursor || myCursor != Cursor.getDefaultCursor()) {
glass.setCursor(cursor, this);
myCursor = cursor;
if (content instanceof JComponent) {
IdeGlassPaneImpl.savePreProcessedCursor((JComponent)content, content.getCursor());
}
super.setCursor(content, cursor);
}
}
@Override
protected void notifyResized() {
myResizeListeners.forEach(Runnable::run);
}
};
glass.addMousePreprocessor(resizeListener, this);
glass.addMouseMotionPreprocessor(resizeListener, this);
myResizeListener = resizeListener;
}
if (myCaption != null && myMovable) {
final WindowMoveListener moveListener = new WindowMoveListener(myCaption) {
@Override
public void mousePressed(final MouseEvent e) {
if (e.isConsumed()) return;
if (UIUtil.isCloseClick(e) && myCaption.isWithinPanel(e)) {
cancel();
}
else {
super.mousePressed(e);
}
}
};
myCaption.addMouseListener(moveListener);
myCaption.addMouseMotionListener(moveListener);
final MyContentPanel saved = myContent;
Disposer.register(this, () -> {
ListenerUtil.removeMouseListener(saved, moveListener);
ListenerUtil.removeMouseMotionListener(saved, moveListener);
});
myMoveListener = moveListener;
}
myListeners.forEach(listener -> listener.beforeShown(new LightweightWindowEvent(this)));
myPopup.setRequestFocus(myRequestFocus);
final Window window = getContentWindow(myContent);
if (window instanceof IdeFrame) {
LOG.warn("Lightweight popup is shown using AbstractPopup class. But this class is not supposed to work with lightweight popups.");
}
window.setFocusableWindowState(myRequestFocus);
window.setFocusable(myRequestFocus);
// Swing popup default always on top state is set in true
window.setAlwaysOnTop(false);
if (myFocusable) {
FocusTraversalPolicy focusTraversalPolicy = new FocusTraversalPolicy() {
@Override
public Component getComponentAfter(Container aContainer, Component aComponent) {
return getComponent();
}
private Component getComponent() {
return myPreferredFocusedComponent == null ? myComponent : myPreferredFocusedComponent;
}
@Override
public Component getComponentBefore(Container aContainer, Component aComponent) {
return getComponent();
}
@Override
public Component getFirstComponent(Container aContainer) {
return getComponent();
}
@Override
public Component getLastComponent(Container aContainer) {
return getComponent();
}
@Override
public Component getDefaultComponent(Container aContainer) {
return getComponent();
}
};
window.setFocusTraversalPolicy(focusTraversalPolicy);
Disposer.register(this, () -> window.setFocusTraversalPolicy(null));
}
window.setAutoRequestFocus(myRequestFocus);
final String data = getUserData(String.class);
final boolean popupIsSimpleWindow = "TRUE".equals(getContent().getClientProperty("BookmarkPopup"));
myContent.getRootPane().putClientProperty("SIMPLE_WINDOW", "SIMPLE_WINDOW".equals(data) || popupIsSimpleWindow);
myWindow = window;
if (myNormalWindowLevel) {
myWindow.setType(Window.Type.NORMAL);
}
setMinimumSize(myMinSize);
final Disposable tb = TouchBarsManager.showPopupBar(this, myContent);
if (tb != null)
Disposer.register(this, tb);
myPopup.show();
Rectangle bounds = window.getBounds();
PopupLocationTracker.register(this);
if (bounds.width > screen.width || bounds.height > screen.height) {
ScreenUtil.fitToScreen(bounds);
window.setBounds(bounds);
}
WindowAction.setEnabledFor(myPopup.getWindow(), myResizable);
myWindowListener = new MyWindowListener();
window.addWindowListener(myWindowListener);
if (myWindow != null) {
// dialog wrapper-based popups do this internally through peer,
// for other popups like jdialog-based we should exclude them manually, but
// we still have to be able to use IdeFrame as parent
if (!myMayBeParent && !(myWindow instanceof Frame)) {
WindowManager.getInstance().doNotSuggestAsParent(myWindow);
}
}
final Runnable afterShow = () -> {
if (isDisposed()) {
LOG.debug("popup is disposed after showing");
removeActivity();
return;
}
if ((myPreferredFocusedComponent instanceof AbstractButton || myPreferredFocusedComponent instanceof JTextField) && myFocusable) {
IJSwingUtilities.moveMousePointerOn(myPreferredFocusedComponent);
}
removeActivity();
afterShow();
};
if (myRequestFocus) {
if (myPreferredFocusedComponent != null) {
myPreferredFocusedComponent.requestFocus();
}
else {
_requestFocus();
}
window.setAutoRequestFocus(myRequestFocus);
SwingUtilities.invokeLater(afterShow);
}
else {
//noinspection SSBasedInspection
SwingUtilities.invokeLater(() -> {
if (isDisposed()) {
removeActivity();
return;
}
afterShow.run();
});
}
debugState("popup shown", State.SHOWING);
myState = State.SHOWN;
afterShowSync();
}
public void focusPreferredComponent() {
_requestFocus();
}
private void installProjectDisposer() {
final Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (c != null) {
final DataContext context = DataManager.getInstance().getDataContext(c);
final Project project = CommonDataKeys.PROJECT.getData(context);
if (project != null) {
myProjectDisposable = () -> {
if (!isDisposed()) {
Disposer.dispose(this);
}
};
Disposer.register(project, myProjectDisposable);
}
}
}
//Sometimes just after popup was shown the WINDOW_ACTIVATED cancels it
private static void installWindowHook(final @NotNull AbstractPopup popup) {
if (popup.myCancelOnWindow) {
popup.myCancelOnWindow = false;
new Alarm(popup).addRequest(() -> popup.myCancelOnWindow = true, 100);
}
}
private void addActivity() {
UiActivityMonitor.getInstance().addActivity(myActivityKey);
}
private void removeActivity() {
UiActivityMonitor.getInstance().removeActivity(myActivityKey);
}
private void prepareToShow() {
final MouseAdapter mouseAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Rectangle bounds = getBoundsOnScreen(myContent);
if (bounds != null) {
bounds.x -= 2;
bounds.y -= 2;
bounds.width += 4;
bounds.height += 4;
}
if (bounds == null || !bounds.contains(e.getLocationOnScreen())) {
cancel();
}
}
};
myContent.addMouseListener(mouseAdapter);
Disposer.register(this, () -> myContent.removeMouseListener(mouseAdapter));
myContent.addKeyListener(mySpeedSearch);
if (myCancelOnMouseOutCallback != null || myCancelOnWindow) {
myMouseOutCanceller = new Canceller();
Toolkit.getDefaultToolkit().addAWTEventListener(myMouseOutCanceller,
MOUSE_EVENT_MASK | WINDOW_ACTIVATED | WINDOW_GAINED_FOCUS | MOUSE_MOTION_EVENT_MASK);
}
ChildFocusWatcher focusWatcher = new ChildFocusWatcher(myContent) {
@Override
protected void onFocusGained(final FocusEvent event) {
setWindowActive(true);
}
@Override
protected void onFocusLost(final FocusEvent event) {
setWindowActive(false);
}
};
Disposer.register(this, focusWatcher);
mySpeedSearchPatternField = new SearchTextField(false) {
@Override
protected void onFieldCleared() {
mySpeedSearch.reset();
}
};
mySpeedSearchPatternField.getTextEditor().setFocusable(mySpeedSearchAlwaysShown);
if (mySpeedSearchAlwaysShown) {
setHeaderComponent(mySpeedSearchPatternField);
mySpeedSearchPatternField.setBorder(JBUI.Borders.customLine(JBUI.CurrentTheme.BigPopup.searchFieldBorderColor(), 1, 0, 1, 0));
mySpeedSearchPatternField.getTextEditor().setBorder(JBUI.Borders.empty());
}
if (SystemInfo.isMac) {
RelativeFont.TINY.install(mySpeedSearchPatternField);
}
}
private void updateMaskAndAlpha(Window window) {
if (window == null) return;
if (!window.isDisplayable() || !window.isShowing()) return;
final WindowManagerEx wndManager = getWndManager();
if (wndManager == null) return;
if (!wndManager.isAlphaModeEnabled(window)) return;
if (myAlpha != myLastAlpha) {
wndManager.setAlphaModeRatio(window, myAlpha);
myLastAlpha = myAlpha;
}
if (myMaskProvider != null) {
final Dimension size = window.getSize();
Shape mask = myMaskProvider.getMask(size);
wndManager.setWindowMask(window, mask);
}
WindowManagerEx.WindowShadowMode mode =
myShadowed ? WindowManagerEx.WindowShadowMode.NORMAL : WindowManagerEx.WindowShadowMode.DISABLED;
WindowManagerEx.getInstanceEx().setWindowShadow(window, mode);
}
private static WindowManagerEx getWndManager() {
return ApplicationManager.getApplication() != null ? WindowManagerEx.getInstanceEx() : null;
}
@Override
public boolean isDisposed() {
return myContent == null;
}
protected boolean beforeShow() {
if (ApplicationManager.getApplication() == null) return true;
StackingPopupDispatcher.getInstance().onPopupShown(this, myInStack);
return true;
}
protected void afterShow() {
}
protected void afterShowSync() {
}
protected final boolean requestFocus() {
if (!myFocusable) return false;
getFocusManager().doWhenFocusSettlesDown(() -> _requestFocus());
return true;
}
private void _requestFocus() {
if (!myFocusable) return;
JComponent toFocus = ObjectUtils.chooseNotNull(myPreferredFocusedComponent,
mySpeedSearchAlwaysShown ? mySpeedSearchPatternField : null);
if (toFocus != null) {
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> {
if (!myDisposed) {
IdeFocusManager.getGlobalInstance().requestFocus(toFocus, true);
}
});
}
}
private IdeFocusManager getFocusManager() {
if (myProject != null) {
return IdeFocusManager.getInstance(myProject);
}
if (myOwner != null) {
return IdeFocusManager.findInstanceByComponent(myOwner);
}
return IdeFocusManager.findInstance();
}
private static JComponent getTargetComponent(Component aComponent) {
if (aComponent instanceof JComponent) {
return (JComponent)aComponent;
}
if (aComponent instanceof RootPaneContainer) {
return ((RootPaneContainer)aComponent).getRootPane();
}
LOG.error("Cannot find target for:" + aComponent);
return null;
}
private PopupComponent.@NotNull Factory getFactory(boolean forceHeavyweight, boolean forceDialog) {
if (Registry.is("allow.dialog.based.popups")) {
boolean noFocus = !myFocusable || !myRequestFocus;
boolean cannotBeDialog = noFocus; // && SystemInfo.isXWindow
if (!cannotBeDialog && (isPersistent() || forceDialog)) {
return new PopupComponent.Factory.Dialog();
}
}
if (forceHeavyweight) {
return new PopupComponent.Factory.AwtHeavyweight();
}
return new PopupComponent.Factory.AwtDefault();
}
@Override
public @NotNull JComponent getContent() {
return myContent;
}
public void setLocation(@NotNull RelativePoint p) {
if (isBusy()) return;
setLocation(p, myPopup);
}
private static void setLocation(@NotNull RelativePoint p, @Nullable PopupComponent popup) {
if (popup == null) return;
final Window wnd = popup.getWindow();
assert wnd != null;
wnd.setLocation(p.getScreenPoint());
}
@Override
public void pack(boolean width, boolean height) {
if (!isVisible() || !width && !height || isBusy()) return;
Dimension size = getSize();
Dimension prefSize = myContent.computePreferredSize();
Point location = !myLocateWithinScreen ? null : getLocationOnScreen();
Rectangle screen = location == null ? null : ScreenUtil.getScreenRectangle(location);
if (width) {
size.width = prefSize.width;
if (screen != null) {
int delta = screen.width + screen.x - location.x;
if (size.width > delta) {
size.width = delta;
if (!SystemInfo.isMac || Registry.is("mac.scroll.horizontal.gap")) {
// we shrank horizontally - need to increase height to fit the horizontal scrollbar
JScrollPane scrollPane = ScrollUtil.findScrollPane(myContent);
if (scrollPane != null && scrollPane.getHorizontalScrollBarPolicy() != ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) {
JScrollBar scrollBar = scrollPane.getHorizontalScrollBar();
if (scrollBar != null) {
prefSize.height += scrollBar.getPreferredSize().height;
}
}
}
}
}
}
if (height) {
size.height = prefSize.height;
if (screen != null) {
int delta = screen.height + screen.y - location.y;
if (size.height > delta) {
size.height = delta;
}
}
}
size.height += getAdComponentHeight();
final Window window = getContentWindow(myContent);
if (window != null) {
window.setSize(size);
}
}
public JComponent getComponent() {
return myComponent;
}
public Project getProject() {
return myProject;
}
@Override
public void dispose() {
if (myState == State.SHOWN) {
LOG.debug("shown popup must be cancelled");
cancel();
}
if (myState == State.DISPOSE) {
return;
}
debugState("dispose popup", State.INIT, State.CANCEL);
myState = State.DISPOSE;
if (myDisposed) {
return;
}
myDisposed = true;
if (LOG.isDebugEnabled()) {
LOG.debug("start disposing " + myContent);
}
Disposer.dispose(this, false);
ApplicationManager.getApplication().assertIsDispatchThread();
if (myPopup != null) {
cancel(myDisposeEvent);
}
if (myContent != null) {
Container parent = myContent.getParent();
if (parent != null) parent.remove(myContent);
myContent.removeAll();
myContent.removeKeyListener(mySpeedSearch);
}
myContent = null;
myPreferredFocusedComponent = null;
myComponent = null;
mySpeedSearchFoundInRootComponent = null;
myCallBack = null;
myListeners.clear();
if (myMouseOutCanceller != null) {
final Toolkit toolkit = Toolkit.getDefaultToolkit();
// it may happen, but have no idea how
// http://www.jetbrains.net/jira/browse/IDEADEV-21265
if (toolkit != null) {
toolkit.removeAWTEventListener(myMouseOutCanceller);
}
}
myMouseOutCanceller = null;
if (myFinalRunnable != null) {
final ActionCallback typeAheadDone = new ActionCallback();
IdeFocusManager.getInstance(myProject).typeAheadUntil(typeAheadDone, "Abstract Popup Disposal");
ModalityState modalityState = ModalityState.current();
Runnable finalRunnable = myFinalRunnable;
getFocusManager().doWhenFocusSettlesDown(() -> {
if (ModalityState.current().equals(modalityState)) {
typeAheadDone.setDone();
((TransactionGuardImpl)TransactionGuard.getInstance()).performUserActivity(finalRunnable);
} else {
typeAheadDone.setRejected();
LOG.debug("Final runnable of popup is skipped");
}
// Otherwise the UI has changed unexpectedly and the action is likely not applicable.
// And we don't want finalRunnable to perform potentially destructive actions
// in the context of a suddenly appeared modal dialog.
});
myFinalRunnable = null;
}
if (LOG.isDebugEnabled()) {
LOG.debug("stop disposing content");
}
}
private void resetWindow() {
if (myWindow != null && getWndManager() != null) {
getWndManager().resetWindow(myWindow);
if (myWindowListener != null) {
myWindow.removeWindowListener(myWindowListener);
}
if (myWindow instanceof RootPaneContainer) {
RootPaneContainer container = (RootPaneContainer)myWindow;
JRootPane root = container.getRootPane();
root.putClientProperty(KEY, null);
if (root.getGlassPane() instanceof IdeGlassPaneImpl) {
// replace installed glass pane with the default one: JRootPane.createGlassPane()
JPanel glass = new JPanel();
glass.setName(root.getName() + ".glassPane");
glass.setVisible(false);
glass.setOpaque(false);
root.setGlassPane(glass);
}
}
myWindow = null;
myWindowListener = null;
}
}
public void storeDimensionSize() {
if (myDimensionServiceKey != null) {
Dimension size = myContent.getSize();
JBInsets.removeFrom(size, myContent.getInsets());
getWindowStateService(myProject).putSize(myDimensionServiceKey, size);
}
}
private void storeLocation(final Point xy) {
if (myDimensionServiceKey != null) {
getWindowStateService(myProject).putLocation(myDimensionServiceKey, xy);
}
}
public static class MyContentPanel extends JPanel implements DataProvider {
private @Nullable DataProvider myDataProvider;
/**
* @deprecated use {@link MyContentPanel#MyContentPanel(PopupBorder)}
*/
@Deprecated
public MyContentPanel(final boolean resizable, final PopupBorder border, boolean drawMacCorner) {
this(border);
DeprecatedMethodException.report("Use com.intellij.ui.popup.AbstractPopup.MyContentPanel.MyContentPanel(com.intellij.ui.PopupBorder) instead");
}
public MyContentPanel(@NotNull PopupBorder border) {
super(new BorderLayout());
putClientProperty(UIUtil.TEXT_COPY_ROOT, Boolean.TRUE);
setBorder(border);
}
public Dimension computePreferredSize() {
if (isPreferredSizeSet()) {
Dimension setSize = getPreferredSize();
setPreferredSize(null);
Dimension result = getPreferredSize();
setPreferredSize(setSize);
return result;
}
return getPreferredSize();
}
@Override
public @Nullable Object getData(@NotNull @NonNls String dataId) {
return myDataProvider != null ? myDataProvider.getData(dataId) : null;
}
public void setDataProvider(@Nullable DataProvider dataProvider) {
myDataProvider = dataProvider;
}
}
boolean isCancelOnClickOutside() {
return myCancelOnClickOutside;
}
boolean isCancelOnWindowDeactivation() {
return myCancelOnWindowDeactivation;
}
private class Canceller implements AWTEventListener {
private boolean myEverEntered;
@Override
public void eventDispatched(final AWTEvent event) {
switch (event.getID()) {
case WINDOW_ACTIVATED:
case WINDOW_GAINED_FOCUS:
if (myCancelOnWindow && myPopup != null && isCancelNeeded((WindowEvent)event, myPopup.getWindow())) {
cancel();
}
break;
case MOUSE_ENTERED:
if (withinPopup(event)) {
myEverEntered = true;
}
break;
case MOUSE_MOVED:
case MOUSE_PRESSED:
if (myCancelOnMouseOutCallback != null && myEverEntered && !withinPopup(event)) {
if (myCancelOnMouseOutCallback.check((MouseEvent)event)) {
cancel();
}
}
break;
}
}
private boolean withinPopup(@NotNull AWTEvent event) {
final MouseEvent mouse = (MouseEvent)event;
Rectangle bounds = getBoundsOnScreen(myContent);
return bounds != null && bounds.contains(mouse.getLocationOnScreen());
}
}
@Override
public void setLocation(@NotNull Point screenPoint) {
if (myPopup == null) {
myForcedLocation = screenPoint;
}
else if (!isBusy()) {
final Insets insets = myContent.getInsets();
if (insets != null && (insets.top != 0 || insets.left != 0)) {
screenPoint = new Point(screenPoint.x - insets.left, screenPoint.y - insets.top);
}
moveTo(myContent, screenPoint, myLocateByContent ? myHeaderPanel.getPreferredSize() : null);
}
}
private static void moveTo(@NotNull JComponent content, @NotNull Point screenPoint, @Nullable Dimension headerCorrectionSize) {
final Window wnd = getContentWindow(content);
if (wnd != null) {
wnd.setCursor(Cursor.getDefaultCursor());
if (headerCorrectionSize != null) {
screenPoint.y -= headerCorrectionSize.height;
}
wnd.setLocation(screenPoint);
}
}
private static Window getContentWindow(@NotNull Component content) {
Window window = SwingUtilities.getWindowAncestor(content);
if (window == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("no window ancestor for " + content);
}
}
return window;
}
@Override
public @NotNull Point getLocationOnScreen() {
Window window = getContentWindow(myContent);
Point screenPoint = window == null ? new Point() : window.getLocation();
fixLocateByContent(screenPoint, false);
Insets insets = myContent.getInsets();
if (insets != null) {
screenPoint.x += insets.left;
screenPoint.y += insets.top;
}
return screenPoint;
}
@Override
public void setSize(final @NotNull Dimension size) {
if (isBusy()) return;
Dimension toSet = new Dimension(size);
toSet.height += getAdComponentHeight();
if (myPopup == null) {
myForcedSize = toSet;
}
else {
updateMaskAndAlpha(setSize(myContent, toSet));
}
}
private int getAdComponentHeight() {
return myAdComponent != null ? myAdComponent.getPreferredSize().height + JBUIScale.scale(1) : 0;
}
@Override
public Dimension getSize() {
if (myPopup != null) {
final Window popupWindow = getContentWindow(myContent);
if (popupWindow != null) {
Dimension size = popupWindow.getSize();
size.height -= getAdComponentHeight();
return size;
}
}
return myForcedSize;
}
@Override
public void moveToFitScreen() {
if (myPopup == null || isBusy()) return;
final Window popupWindow = getContentWindow(myContent);
if (popupWindow == null) return;
Rectangle bounds = popupWindow.getBounds();
ScreenUtil.moveRectangleToFitTheScreen(bounds);
// calling #setLocation or #setSize makes the window move for a bit because of tricky computations
// our aim here is to just move the window as-is to make it fit the screen
// no tricks are included here
popupWindow.setBounds(bounds);
updateMaskAndAlpha(popupWindow);
}
public static Window setSize(@NotNull JComponent content, @NotNull Dimension size) {
final Window popupWindow = getContentWindow(content);
if (popupWindow == null) return null;
JBInsets.addTo(size, content.getInsets());
content.setPreferredSize(size);
popupWindow.pack();
return popupWindow;
}
@Override
public void setCaption(@NotNull @NlsContexts.PopupTitle String title) {
if (myCaption instanceof TitlePanel) {
((TitlePanel)myCaption).setText(title);
}
}
protected void setSpeedSearchAlwaysShown() {
assert myState == State.INIT;
mySpeedSearchAlwaysShown = true;
}
private class MyWindowListener extends WindowAdapter {
@Override
public void windowOpened(WindowEvent e) {
updateMaskAndAlpha(myWindow);
}
@Override
public void windowClosing(final WindowEvent e) {
resetWindow();
cancel();
}
}
@Override
public boolean isPersistent() {
return !myCancelOnClickOutside && !myCancelOnWindow;
}
@Override
public boolean isNativePopup() {
return myNativePopup;
}
@Override
public void setUiVisible(final boolean visible) {
if (myPopup != null) {
if (visible) {
myPopup.show();
final Window window = getPopupWindow();
if (window != null && myRestoreWindowSize != null) {
window.setSize(myRestoreWindowSize);
myRestoreWindowSize = null;
}
}
else {
final Window window = getPopupWindow();
if (window != null) {
myRestoreWindowSize = window.getSize();
window.setVisible(false);
}
}
}
}
public Window getPopupWindow() {
return myPopup != null ? myPopup.getWindow() : null;
}
@Override
public void setUserData(@NotNull List<Object> userData) {
myUserData = userData;
}
@Override
public <T> T getUserData(final @NotNull Class<T> userDataClass) {
if (myUserData != null) {
for (Object o : myUserData) {
if (userDataClass.isInstance(o)) {
@SuppressWarnings("unchecked") T t = (T)o;
return t;
}
}
}
return null;
}
@Override
public boolean isModalContext() {
return myModalContext;
}
@Override
public boolean isFocused() {
if (myComponent != null && isFocused(new Component[]{SwingUtilities.getWindowAncestor(myComponent)})) {
return true;
}
return isFocused(myFocusOwners);
}
private static boolean isFocused(Component @NotNull [] components) {
Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (owner == null) return false;
Window wnd = ComponentUtil.getWindow(owner);
for (Component each : components) {
if (each != null && SwingUtilities.isDescendingFrom(owner, each)) {
Window eachWindow = ComponentUtil.getWindow(each);
if (eachWindow == wnd) {
return true;
}
}
}
return false;
}
@Override
public boolean isCancelKeyEnabled() {
return myCancelKeyEnabled;
}
public @NotNull CaptionPanel getTitle() {
return myCaption;
}
protected void setHeaderComponent(JComponent c) {
boolean doRevalidate = false;
if (myHeaderComponent != null) {
myHeaderPanel.remove(myHeaderComponent);
myHeaderComponent = null;
doRevalidate = true;
}
if (c != null) {
myHeaderPanel.add(c, BorderLayout.CENTER);
myHeaderComponent = c;
if (isVisible()) {
final Dimension size = myContent.getSize();
if (size.height < c.getPreferredSize().height * 2) {
size.height += c.getPreferredSize().height;
setSize(size);
}
}
doRevalidate = true;
}
if (doRevalidate) myContent.revalidate();
}
public void setWarning(@NotNull String text) {
JBLabel label = new JBLabel(text, UIUtil.getBalloonWarningIcon(), SwingConstants.CENTER);
label.setOpaque(true);
Color color = HintUtil.getInformationColor();
label.setBackground(color);
label.setBorder(BorderFactory.createLineBorder(color, 3));
myHeaderPanel.add(label, BorderLayout.SOUTH);
}
@Override
public void addListener(@NotNull JBPopupListener listener) {
myListeners.add(0, listener); // last added first notified
}
@Override
public void removeListener(@NotNull JBPopupListener listener) {
myListeners.remove(listener);
}
protected void onSpeedSearchPatternChanged() {
}
@Override
public Component getOwner() {
return myRequestorComponent;
}
@Override
public void setMinimumSize(Dimension size) {
//todo: consider changing only the caption panel minimum size
Dimension sizeFromHeader = myHeaderPanel.getPreferredSize();
if (sizeFromHeader == null) {
sizeFromHeader = myHeaderPanel.getMinimumSize();
}
if (sizeFromHeader == null) {
int minimumSize = myWindow.getGraphics().getFontMetrics(myHeaderPanel.getFont()).getHeight();
sizeFromHeader = new Dimension(minimumSize, minimumSize);
}
if (size == null) {
myMinSize = sizeFromHeader;
} else {
final int width = Math.max(size.width, sizeFromHeader.width);
final int height = Math.max(size.height, sizeFromHeader.height);
myMinSize = new Dimension(width, height);
}
if (myWindow != null) {
Rectangle screenRectangle = ScreenUtil.getScreenRectangle(myWindow.getLocation());
int width = Math.min(screenRectangle.width, myMinSize.width);
int height = Math.min(screenRectangle.height, myMinSize.height);
myWindow.setMinimumSize(new Dimension(width, height));
}
}
public void setOkHandler(Runnable okHandler) {
myOkHandler = okHandler;
}
@Override
public void setFinalRunnable(Runnable finalRunnable) {
myFinalRunnable = finalRunnable;
}
public void setOk(boolean ok) {
myOk = ok;
}
@Override
public void setDataProvider(@NotNull DataProvider dataProvider) {
if (myContent != null) {
myContent.setDataProvider(dataProvider);
}
}
@Override
public boolean dispatchKeyEvent(@NotNull KeyEvent e) {
BooleanFunction<? super KeyEvent> handler = myKeyEventHandler;
if (handler != null && handler.fun(e)) {
return true;
}
if (isCloseRequest(e) && myCancelKeyEnabled && !mySpeedSearch.isHoldingFilter()) {
if (mySpeedSearchFoundInRootComponent != null && mySpeedSearchFoundInRootComponent.isHoldingFilter()) {
mySpeedSearchFoundInRootComponent.reset();
}
else {
cancel(e);
}
return true;
}
return false;
}
public @NotNull Dimension getHeaderPreferredSize() {
return myHeaderPanel.getPreferredSize();
}
public @NotNull Dimension getFooterPreferredSize() {
return myAdComponent == null ? new Dimension(0,0) : myAdComponent.getPreferredSize();
}
public static boolean isCloseRequest(KeyEvent e) {
return e != null && e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_ESCAPE && e.getModifiers() == 0;
}
private @NotNull Point fixLocateByContent(@NotNull Point location, boolean save) {
Dimension size = !myLocateByContent ? null : myHeaderPanel.getPreferredSize();
if (size != null) location.y -= save ? -size.height : size.height;
return location;
}
protected boolean isBusy() {
return myResizeListener != null && myResizeListener.isBusy() || myMoveListener != null && myMoveListener.isBusy();
}
/**
* Returns the first frame (or dialog) ancestor of the component.
* Note that this method returns the component itself if it is a frame (or dialog).
*
* @param component the component used to find corresponding frame (or dialog)
* @return the first frame (or dialog) ancestor of the component; or {@code null}
* if the component is not a frame (or dialog) and is not contained inside a frame (or dialog)
*
* @see UIUtil#getWindow
*/
private static Component getFrameOrDialog(Component component) {
while (component != null) {
if (component instanceof Window) return component;
component = component.getParent();
}
return null;
}
private static @Nullable Point getLocationOnScreen(@Nullable Component component) {
return component == null || !component.isShowing() ? null : component.getLocationOnScreen();
}
private static @Nullable Rectangle getBoundsOnScreen(@Nullable Component component) {
Point point = getLocationOnScreen(component);
return point == null ? null : new Rectangle(point, component.getSize());
}
public static @NotNull List<JBPopup> getChildPopups(final @NotNull Component component) {
return ContainerUtil.filter(all.toStrongList(), popup -> {
Component owner = popup.getOwner();
while (owner != null) {
if (owner.equals(component)) {
return true;
}
owner = owner.getParent();
}
return false;
});
}
@Override
public boolean canShow() {
return myState == State.INIT;
}
@Override
public @NotNull Rectangle getConsumedScreenBounds() {
return myWindow.getBounds();
}
@Override
public Window getUnderlyingWindow() {
return myWindow.getOwner();
}
/**
* Passed listener will be notified if popup is resized by user (using mouse)
*/
public void addResizeListener(@NotNull Runnable runnable, @NotNull Disposable parentDisposable) {
myResizeListeners.add(runnable);
Disposer.register(parentDisposable, () -> myResizeListeners.remove(runnable));
}
/**
* @param event a {@code WindowEvent} for the activated or focused window
* @param popup a window that corresponds to the current popup
* @return {@code false} if a focus moved to a popup window or its child window in the whole hierarchy
*/
private static boolean isCancelNeeded(@NotNull WindowEvent event, @Nullable Window popup) {
Window window = event.getWindow(); // the activated or focused window
while (window != null) {
if (popup == window) return false; // do not close a popup, which child is activated or focused
window = window.getOwner(); // consider a window owner as activated or focused
}
return true;
}
private @Nullable Point getStoredLocation() {
if (myDimensionServiceKey == null) return null;
return getWindowStateService(myProject).getLocation(myDimensionServiceKey);
}
private @Nullable Dimension getStoredSize() {
if (myDimensionServiceKey == null) return null;
return getWindowStateService(myProject).getSize(myDimensionServiceKey);
}
private static @NotNull WindowStateService getWindowStateService(@Nullable Project project) {
return project == null ? WindowStateService.getInstance() : WindowStateService.getInstance(project);
}
private static <T> T findInComponentHierarchy(@NotNull Component component, Function<@NotNull Component, @Nullable T> mapper) {
T found = mapper.fun(component);
if (found != null) {
return found;
}
if (component instanceof JComponent) {
for (Component child : ((JComponent)component).getComponents()) {
found = findInComponentHierarchy(child, mapper);
if (found != null) {
return found;
}
}
}
return null;
}
}
| platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.popup;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.icons.AllIcons;
import com.intellij.ide.*;
import com.intellij.ide.actions.WindowAction;
import com.intellij.ide.ui.PopupLocationTracker;
import com.intellij.ide.ui.ScreenAreaConsumer;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.application.TransactionGuardImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.ui.popup.*;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.*;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.openapi.wm.impl.IdeGlassPaneImpl;
import com.intellij.ui.*;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.mac.touchbar.TouchBarsManager;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.ui.speedSearch.ListWithFilter;
import com.intellij.ui.speedSearch.SpeedSearch;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.WeakList;
import com.intellij.util.ui.*;
import com.intellij.util.ui.accessibility.AccessibleContextUtil;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Supplier;
import static java.awt.event.MouseEvent.*;
import static java.awt.event.WindowEvent.WINDOW_ACTIVATED;
import static java.awt.event.WindowEvent.WINDOW_GAINED_FOCUS;
public class AbstractPopup implements JBPopup, ScreenAreaConsumer {
public static final String SHOW_HINTS = "ShowHints";
// Popup size stored with DimensionService is null first time
// In this case you can put Dimension in content client properties to adjust size
// Zero or negative values (with/height or both) would be ignored (actual values would be obtained from preferred size)
public static final String FIRST_TIME_SIZE = "FirstTimeSize";
private static final Logger LOG = Logger.getInstance(AbstractPopup.class);
private PopupComponent myPopup;
private MyContentPanel myContent;
private JComponent myPreferredFocusedComponent;
private boolean myRequestFocus;
private boolean myFocusable;
private boolean myForcedHeavyweight;
private boolean myLocateWithinScreen;
private boolean myResizable;
private WindowResizeListener myResizeListener;
private WindowMoveListener myMoveListener;
private JPanel myHeaderPanel;
private CaptionPanel myCaption;
private JComponent myComponent;
private SpeedSearch mySpeedSearchFoundInRootComponent;
private String myDimensionServiceKey;
private Computable<Boolean> myCallBack;
private Project myProject;
private boolean myCancelOnClickOutside;
private final List<JBPopupListener> myListeners = new CopyOnWriteArrayList<>();
private boolean myUseDimServiceForXYLocation;
private MouseChecker myCancelOnMouseOutCallback;
private Canceller myMouseOutCanceller;
private boolean myCancelOnWindow;
private boolean myCancelOnWindowDeactivation = true;
private Dimension myForcedSize;
private Point myForcedLocation;
private boolean myCancelKeyEnabled;
private boolean myLocateByContent;
private Dimension myMinSize;
private List<Object> myUserData;
private boolean myShadowed;
private float myAlpha;
private float myLastAlpha;
private MaskProvider myMaskProvider;
private Window myWindow;
private boolean myInStack;
private MyWindowListener myWindowListener;
private boolean myModalContext;
private Component[] myFocusOwners;
private PopupBorder myPopupBorder;
private Dimension myRestoreWindowSize;
protected Component myOwner;
private Component myRequestorComponent;
private boolean myHeaderAlwaysFocusable;
private boolean myMovable;
private JComponent myHeaderComponent;
InputEvent myDisposeEvent;
private Runnable myFinalRunnable;
private Runnable myOkHandler;
private @Nullable BooleanFunction<? super KeyEvent> myKeyEventHandler;
protected boolean myOk;
private final List<Runnable> myResizeListeners = new ArrayList<>();
private static final WeakList<JBPopup> all = new WeakList<>();
private boolean mySpeedSearchAlwaysShown;
protected final SpeedSearch mySpeedSearch = new SpeedSearch() {
boolean searchFieldShown;
@Override
public void update() {
mySpeedSearchPatternField.getTextEditor().setBackground(UIUtil.getTextFieldBackground());
onSpeedSearchPatternChanged();
mySpeedSearchPatternField.setText(getFilter());
if (!mySpeedSearchAlwaysShown) {
if (isHoldingFilter() && !searchFieldShown) {
setHeaderComponent(mySpeedSearchPatternField);
searchFieldShown = true;
}
else if (!isHoldingFilter() && searchFieldShown) {
setHeaderComponent(null);
searchFieldShown = false;
}
}
}
@Override
public void noHits() {
mySpeedSearchPatternField.getTextEditor().setBackground(LightColors.RED);
}
};
protected SearchTextField mySpeedSearchPatternField;
private boolean myNativePopup;
private boolean myMayBeParent;
private JLabel myAdComponent;
private boolean myDisposed;
private boolean myNormalWindowLevel;
private UiActivity myActivityKey;
private Disposable myProjectDisposable;
private volatile State myState = State.NEW;
void setNormalWindowLevel(boolean normalWindowLevel) {
myNormalWindowLevel = normalWindowLevel;
}
private enum State {NEW, INIT, SHOWING, SHOWN, CANCEL, DISPOSE}
private void debugState(@NonNls @NotNull String message, State @NotNull ... states) {
if (LOG.isDebugEnabled()) {
LOG.debug(hashCode() + " - " + message);
if (!ApplicationManager.getApplication().isDispatchThread()) {
LOG.debug("unexpected thread");
}
for (State state : states) {
if (state == myState) {
return;
}
}
LOG.debug(new IllegalStateException("myState=" + myState));
}
}
protected AbstractPopup() { }
protected @NotNull AbstractPopup init(Project project,
@NotNull JComponent component,
@Nullable JComponent preferredFocusedComponent,
boolean requestFocus,
boolean focusable,
boolean movable,
String dimensionServiceKey,
boolean resizable,
@Nullable String caption,
@Nullable Computable<Boolean> callback,
boolean cancelOnClickOutside,
@NotNull Set<? extends JBPopupListener> listeners,
boolean useDimServiceForXYLocation,
ActiveComponent commandButton,
@Nullable IconButton cancelButton,
@Nullable MouseChecker cancelOnMouseOutCallback,
boolean cancelOnWindow,
@Nullable ActiveIcon titleIcon,
boolean cancelKeyEnabled,
boolean locateByContent,
boolean placeWithinScreenBounds,
@Nullable Dimension minSize,
float alpha,
@Nullable MaskProvider maskProvider,
boolean inStack,
boolean modalContext,
Component @NotNull [] focusOwners,
@Nullable String adText,
int adTextAlignment,
boolean headerAlwaysFocusable,
@NotNull List<? extends Pair<ActionListener, KeyStroke>> keyboardActions,
Component settingsButtons,
final @Nullable Processor<? super JBPopup> pinCallback,
boolean mayBeParent,
boolean showShadow,
boolean showBorder,
Color borderColor,
boolean cancelOnWindowDeactivation,
@Nullable BooleanFunction<? super KeyEvent> keyEventHandler) {
assert !requestFocus || focusable : "Incorrect argument combination: requestFocus=true focusable=false";
all.add(this);
myActivityKey = new UiActivity.Focus("Popup:" + this);
myProject = project;
myComponent = component;
mySpeedSearchFoundInRootComponent =
findInComponentHierarchy(component, it -> it instanceof ListWithFilter ? ((ListWithFilter)it).getSpeedSearch() : null);
myPopupBorder = showBorder ? borderColor != null ? PopupBorder.Factory.createColored(borderColor) :
PopupBorder.Factory.create(true, showShadow) :
PopupBorder.Factory.createEmpty();
myShadowed = showShadow;
myContent = createContentPanel(resizable, myPopupBorder, false);
myMayBeParent = mayBeParent;
myCancelOnWindowDeactivation = cancelOnWindowDeactivation;
myContent.add(component, BorderLayout.CENTER);
if (adText != null) {
setAdText(adText, adTextAlignment);
}
myCancelKeyEnabled = cancelKeyEnabled;
myLocateByContent = locateByContent;
myLocateWithinScreen = placeWithinScreenBounds;
myAlpha = alpha;
myMaskProvider = maskProvider;
myInStack = inStack;
myModalContext = modalContext;
myFocusOwners = focusOwners;
myHeaderAlwaysFocusable = headerAlwaysFocusable;
myMovable = movable;
ActiveIcon actualIcon = titleIcon == null ? new ActiveIcon(EmptyIcon.ICON_0) : titleIcon;
myHeaderPanel = new JPanel(new BorderLayout());
if (caption != null) {
if (!caption.isEmpty()) {
myCaption = new TitlePanel(actualIcon.getRegular(), actualIcon.getInactive());
((TitlePanel)myCaption).setText(caption);
}
else {
myCaption = new CaptionPanel();
}
if (pinCallback != null) {
Icon icon = ToolWindowManager.getInstance(myProject != null ? myProject : ProjectUtil.guessCurrentProject((JComponent)myOwner))
.getLocationIcon(ToolWindowId.FIND, AllIcons.General.Pin_tab);
myCaption.setButtonComponent(new InplaceButton(
new IconButton(IdeBundle.message("show.in.find.window.button.name"), icon),
e -> pinCallback.process(this)
), JBUI.Borders.empty(4));
}
else if (cancelButton != null) {
myCaption.setButtonComponent(new InplaceButton(cancelButton, e -> cancel()), JBUI.Borders.empty(4));
}
else if (commandButton != null) {
myCaption.setButtonComponent(commandButton, null);
}
}
else {
myCaption = new CaptionPanel();
myCaption.setBorder(null);
myCaption.setPreferredSize(JBUI.emptySize());
}
setWindowActive(myHeaderAlwaysFocusable);
myHeaderPanel.add(myCaption, BorderLayout.NORTH);
myContent.add(myHeaderPanel, BorderLayout.NORTH);
myForcedHeavyweight = true;
myResizable = resizable;
myPreferredFocusedComponent = preferredFocusedComponent;
myRequestFocus = requestFocus;
myFocusable = focusable;
myDimensionServiceKey = dimensionServiceKey;
myCallBack = callback;
myCancelOnClickOutside = cancelOnClickOutside;
myCancelOnMouseOutCallback = cancelOnMouseOutCallback;
myListeners.addAll(listeners);
myUseDimServiceForXYLocation = useDimServiceForXYLocation;
myCancelOnWindow = cancelOnWindow;
myMinSize = minSize;
for (Pair<ActionListener, KeyStroke> pair : keyboardActions) {
myContent.registerKeyboardAction(pair.getFirst(), pair.getSecond(), JComponent.WHEN_IN_FOCUSED_WINDOW);
}
if (settingsButtons != null) {
myCaption.addSettingsComponent(settingsButtons);
}
myKeyEventHandler = keyEventHandler;
debugState("popup initialized", State.NEW);
myState = State.INIT;
return this;
}
private void setWindowActive(boolean active) {
boolean value = myHeaderAlwaysFocusable || active;
if (myCaption != null) {
myCaption.setActive(value);
}
myPopupBorder.setActive(value);
myContent.repaint();
}
protected @NotNull MyContentPanel createContentPanel(final boolean resizable, @NotNull PopupBorder border, boolean isToDrawMacCorner) {
return new MyContentPanel(border);
}
public void setShowHints(boolean show) {
final Window ancestor = getContentWindow(myComponent);
if (ancestor instanceof RootPaneContainer) {
final JRootPane rootPane = ((RootPaneContainer)ancestor).getRootPane();
if (rootPane != null) {
rootPane.putClientProperty(SHOW_HINTS, show);
}
}
}
public String getDimensionServiceKey() {
return myDimensionServiceKey;
}
public void setDimensionServiceKey(final @Nullable String dimensionServiceKey) {
myDimensionServiceKey = dimensionServiceKey;
}
public void setAdText(@NotNull @NlsContexts.PopupAdvertisement String s) {
setAdText(s, SwingConstants.LEFT);
}
public @NotNull PopupBorder getPopupBorder() {
return myPopupBorder;
}
@Override
public void setAdText(final @NotNull String s, int alignment) {
if (myAdComponent == null) {
myAdComponent = HintUtil.createAdComponent(s, JBUI.CurrentTheme.Advertiser.border(), alignment);
JPanel wrapper = new JPanel(new BorderLayout());
wrapper.setOpaque(false);
wrapper.add(myAdComponent, BorderLayout.CENTER);
myContent.add(wrapper, BorderLayout.SOUTH);
pack(false, true);
}
else {
myAdComponent.setText(s);
myAdComponent.setHorizontalAlignment(alignment);
}
}
public static @NotNull Point getCenterOf(@NotNull Component aContainer, @NotNull JComponent content) {
return getCenterOf(aContainer, content.getPreferredSize());
}
private static @NotNull Point getCenterOf(@NotNull Component aContainer, @NotNull Dimension contentSize) {
final JComponent component = getTargetComponent(aContainer);
Rectangle visibleBounds = component != null
? component.getVisibleRect()
: new Rectangle(aContainer.getSize());
Point containerScreenPoint = visibleBounds.getLocation();
SwingUtilities.convertPointToScreen(containerScreenPoint, aContainer);
visibleBounds.setLocation(containerScreenPoint);
return UIUtil.getCenterPoint(visibleBounds, contentSize);
}
@Override
public void showCenteredInCurrentWindow(@NotNull Project project) {
if (UiInterceptors.tryIntercept(this)) return;
Window window = null;
Component focusedComponent = getWndManager().getFocusedComponent(project);
if (focusedComponent != null) {
Component parent = UIUtil.findUltimateParent(focusedComponent);
if (parent instanceof Window) {
window = (Window)parent;
}
}
if (window == null) {
window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
}
if (window != null && window.isShowing()) {
showInCenterOf(window);
}
}
@Override
public void showInCenterOf(@NotNull Component aComponent) {
HelpTooltip.setMasterPopup(aComponent, this);
Point popupPoint = getCenterOf(aComponent, getPreferredContentSize());
show(aComponent, popupPoint.x, popupPoint.y, false);
}
@Override
public void showUnderneathOf(@NotNull Component aComponent) {
show(new RelativePoint(aComponent, new Point(JBUIScale.scale(2), aComponent.getHeight())));
}
@Override
public void show(@NotNull RelativePoint aPoint) {
if (UiInterceptors.tryIntercept(this)) return;
HelpTooltip.setMasterPopup(aPoint.getOriginalComponent(), this);
Point screenPoint = aPoint.getScreenPoint();
show(aPoint.getComponent(), screenPoint.x, screenPoint.y, false);
}
@Override
public void showInScreenCoordinates(@NotNull Component owner, @NotNull Point point) {
show(owner, point.x, point.y, false);
}
@Override
public @NotNull Point getBestPositionFor(@NotNull DataContext dataContext) {
final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
if (editor != null && editor.getComponent().isShowing()) {
return getBestPositionFor(editor).getScreenPoint();
}
return relativePointByQuickSearch(dataContext).getScreenPoint();
}
@Override
public void showInBestPositionFor(@NotNull DataContext dataContext) {
final Editor editor = CommonDataKeys.EDITOR_EVEN_IF_INACTIVE.getData(dataContext);
if (editor != null && editor.getComponent().isShowing()) {
showInBestPositionFor(editor);
}
else {
show(relativePointByQuickSearch(dataContext));
}
}
@Override
public void showInFocusCenter() {
final Component focused = getWndManager().getFocusedComponent(myProject);
if (focused != null) {
showInCenterOf(focused);
}
else {
final WindowManager manager = WindowManager.getInstance();
final JFrame frame = myProject != null ? manager.getFrame(myProject) : manager.findVisibleFrame();
showInCenterOf(frame.getRootPane());
}
}
private @NotNull RelativePoint relativePointByQuickSearch(@NotNull DataContext dataContext) {
Rectangle dominantArea = PlatformDataKeys.DOMINANT_HINT_AREA_RECTANGLE.getData(dataContext);
if (dominantArea != null) {
final Component focusedComponent = getWndManager().getFocusedComponent(myProject);
if (focusedComponent != null) {
Window window = SwingUtilities.windowForComponent(focusedComponent);
JLayeredPane layeredPane;
if (window instanceof JFrame) {
layeredPane = ((JFrame)window).getLayeredPane();
}
else if (window instanceof JDialog) {
layeredPane = ((JDialog)window).getLayeredPane();
}
else if (window instanceof JWindow) {
layeredPane = ((JWindow)window).getLayeredPane();
}
else {
throw new IllegalStateException("cannot find parent window: project=" + myProject + "; window=" + window);
}
return relativePointWithDominantRectangle(layeredPane, dominantArea);
}
}
RelativePoint location;
Component contextComponent = dataContext.getData(PlatformDataKeys.CONTEXT_COMPONENT);
if (contextComponent == myComponent) {
location = new RelativePoint(myComponent, new Point());
}
else {
location = JBPopupFactory.getInstance().guessBestPopupLocation(dataContext);
}
if (myLocateWithinScreen) {
Point screenPoint = location.getScreenPoint();
Rectangle rectangle = new Rectangle(screenPoint, getSizeForPositioning());
Rectangle screen = ScreenUtil.getScreenRectangle(screenPoint);
ScreenUtil.moveToFit(rectangle, screen, null);
location = new RelativePoint(rectangle.getLocation()).getPointOn(location.getComponent());
}
return location;
}
private Dimension getSizeForPositioning() {
Dimension size = getSize();
if (size == null) {
size = getStoredSize();
}
if (size == null) {
size = myContent.getPreferredSize();
}
return size;
}
@Override
public void showInBestPositionFor(@NotNull Editor editor) {
// Intercept before the following assert; otherwise assertion may fail
if (UiInterceptors.tryIntercept(this)) return;
assert editor.getComponent().isShowing() : "Editor must be showing on the screen";
// Set the accessible parent so that screen readers don't announce
// a window context change -- the tooltip is "logically" hosted
// inside the component (e.g. editor) it appears on top of.
AccessibleContextUtil.setParent((Component)myComponent, editor.getContentComponent());
show(getBestPositionFor(editor));
}
private @NotNull RelativePoint getBestPositionFor(@NotNull Editor editor) {
DataContext context = ((EditorEx)editor).getDataContext();
Rectangle dominantArea = PlatformDataKeys.DOMINANT_HINT_AREA_RECTANGLE.getData(context);
if (dominantArea != null && !myRequestFocus) {
final JLayeredPane layeredPane = editor.getContentComponent().getRootPane().getLayeredPane();
return relativePointWithDominantRectangle(layeredPane, dominantArea);
}
else {
return guessBestPopupLocation(editor);
}
}
private @NotNull RelativePoint guessBestPopupLocation(@NotNull Editor editor) {
RelativePoint preferredLocation = JBPopupFactory.getInstance().guessBestPopupLocation(editor);
Dimension targetSize = getSizeForPositioning();
Point preferredPoint = preferredLocation.getScreenPoint();
Point result = getLocationAboveEditorLineIfPopupIsClippedAtTheBottom(preferredPoint, targetSize, editor);
if (myLocateWithinScreen) {
Rectangle rectangle = new Rectangle(result, targetSize);
Rectangle screen = ScreenUtil.getScreenRectangle(preferredPoint);
ScreenUtil.moveToFit(rectangle, screen, null);
result = rectangle.getLocation();
}
return toRelativePoint(result, preferredLocation.getComponent());
}
private static @NotNull RelativePoint toRelativePoint(@NotNull Point screenPoint, @Nullable Component component) {
if (component == null) {
return RelativePoint.fromScreen(screenPoint);
}
SwingUtilities.convertPointFromScreen(screenPoint, component);
return new RelativePoint(component, screenPoint);
}
private static @NotNull Point getLocationAboveEditorLineIfPopupIsClippedAtTheBottom(@NotNull Point originalLocation,
@NotNull Dimension popupSize,
@NotNull Editor editor) {
Rectangle preferredBounds = new Rectangle(originalLocation, popupSize);
Rectangle adjustedBounds = new Rectangle(preferredBounds);
ScreenUtil.moveRectangleToFitTheScreen(adjustedBounds);
if (preferredBounds.y - adjustedBounds.y <= 0) {
return originalLocation;
}
int adjustedY = preferredBounds.y - editor.getLineHeight() - popupSize.height;
if (adjustedY < 0) {
return originalLocation;
}
return new Point(preferredBounds.x, adjustedY);
}
/**
* @see #addListener
* @deprecated use public API instead
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.1")
protected void addPopupListener(@NotNull JBPopupListener listener) {
myListeners.add(listener);
}
private @NotNull RelativePoint relativePointWithDominantRectangle(@NotNull JLayeredPane layeredPane, @NotNull Rectangle bounds) {
Dimension size = getSizeForPositioning();
List<Supplier<Point>> optionsToTry = Arrays.asList(() -> new Point(bounds.x + bounds.width, bounds.y),
() -> new Point(bounds.x - size.width, bounds.y));
for (Supplier<Point> option : optionsToTry) {
Point location = option.get();
SwingUtilities.convertPointToScreen(location, layeredPane);
Point adjustedLocation = fitToScreenAdjustingVertically(location, size);
if (adjustedLocation != null) return new RelativePoint(adjustedLocation).getPointOn(layeredPane);
}
setDimensionServiceKey(null); // going to cut width
Point rightTopCorner = new Point(bounds.x + bounds.width, bounds.y);
final Point rightTopCornerScreen = (Point)rightTopCorner.clone();
SwingUtilities.convertPointToScreen(rightTopCornerScreen, layeredPane);
Rectangle screen = ScreenUtil.getScreenRectangle(rightTopCornerScreen.x, rightTopCornerScreen.y);
final int spaceOnTheLeft = bounds.x;
final int spaceOnTheRight = screen.x + screen.width - rightTopCornerScreen.x;
if (spaceOnTheLeft > spaceOnTheRight) {
myComponent.setPreferredSize(new Dimension(spaceOnTheLeft, Math.max(size.height, JBUIScale.scale(200))));
return new RelativePoint(layeredPane, new Point(0, bounds.y));
}
else {
myComponent.setPreferredSize(new Dimension(spaceOnTheRight, Math.max(size.height, JBUIScale.scale(200))));
return new RelativePoint(layeredPane, rightTopCorner);
}
}
// positions are relative to screen
private static @Nullable Point fitToScreenAdjustingVertically(@NotNull Point position, @NotNull Dimension size) {
Rectangle screenRectangle = ScreenUtil.getScreenRectangle(position);
Rectangle rectangle = new Rectangle(position, size);
if (rectangle.height > screenRectangle.height ||
rectangle.x < screenRectangle.x ||
rectangle.x + rectangle.width > screenRectangle.x + screenRectangle.width) {
return null;
}
ScreenUtil.moveToFit(rectangle, screenRectangle, null);
return rectangle.getLocation();
}
private @NotNull Dimension getPreferredContentSize() {
if (myForcedSize != null) {
return myForcedSize;
}
Dimension size = getStoredSize();
if (size != null) return size;
return myComponent.getPreferredSize();
}
@Override
public final void closeOk(@Nullable InputEvent e) {
setOk(true);
myFinalRunnable = FunctionUtil.composeRunnables(myOkHandler, myFinalRunnable);
cancel(e);
}
@Override
public final void cancel() {
InputEvent inputEvent = null;
AWTEvent event = IdeEventQueue.getInstance().getTrueCurrentEvent();
if (event instanceof InputEvent && myPopup != null) {
InputEvent ie = (InputEvent)event;
Window window = myPopup.getWindow();
if (window != null && UIUtil.isDescendingFrom(ie.getComponent(), window)) {
inputEvent = ie;
}
}
cancel(inputEvent);
}
@Override
public void setRequestFocus(boolean requestFocus) {
myRequestFocus = requestFocus;
}
@Override
public void cancel(InputEvent e) {
if (myState == State.CANCEL || myState == State.DISPOSE) {
return;
}
debugState("cancel popup", State.SHOWN);
myState = State.CANCEL;
if (isDisposed()) return;
if (myPopup != null) {
if (!canClose()) {
debugState("cannot cancel popup", State.CANCEL);
myState = State.SHOWN;
return;
}
storeDimensionSize();
if (myUseDimServiceForXYLocation) {
final JRootPane root = myComponent.getRootPane();
if (root != null) {
Point location = getLocationOnScreen(root.getParent());
if (location != null) {
storeLocation(fixLocateByContent(location, true));
}
}
}
if (e instanceof MouseEvent) {
IdeEventQueue.getInstance().blockNextEvents((MouseEvent)e);
}
myPopup.hide(false);
if (ApplicationManager.getApplication() != null) {
StackingPopupDispatcher.getInstance().onPopupHidden(this);
}
disposePopup();
}
myListeners.forEach(listener -> listener.onClosed(new LightweightWindowEvent(this, myOk)));
Disposer.dispose(this, false);
if (myProjectDisposable != null) {
Disposer.dispose(myProjectDisposable);
}
}
private void disposePopup() {
all.remove(this);
if (myPopup != null) {
resetWindow();
myPopup.hide(true);
}
myPopup = null;
}
@Override
public boolean canClose() {
return myCallBack == null || myCallBack.compute().booleanValue();
}
@Override
public boolean isVisible() {
if (myPopup == null) return false;
Window window = myPopup.getWindow();
if (window != null && window.isShowing()) return true;
if (LOG.isDebugEnabled()) LOG.debug("window hidden, popup's state: " + myState);
return false;
}
@Override
public void show(final @NotNull Component owner) {
show(owner, -1, -1, true);
}
public void show(@NotNull Component owner, int aScreenX, int aScreenY, final boolean considerForcedXY) {
if (UiInterceptors.tryIntercept(this)) return;
if (ApplicationManager.getApplication() != null && ApplicationManager.getApplication().isHeadlessEnvironment()) return;
if (isDisposed()) {
throw new IllegalStateException("Popup was already disposed. Recreate a new instance to show again");
}
ApplicationManager.getApplication().assertIsDispatchThread();
assert myState == State.INIT : "Popup was already shown. Recreate a new instance to show again.";
debugState("show popup", State.INIT);
myState = State.SHOWING;
installProjectDisposer();
addActivity();
final boolean shouldShow = beforeShow();
if (!shouldShow) {
removeActivity();
debugState("rejected to show popup", State.SHOWING);
myState = State.INIT;
return;
}
prepareToShow();
installWindowHook(this);
Dimension sizeToSet = getStoredSize();
if (myForcedSize != null) {
sizeToSet = myForcedSize;
}
Rectangle screen = ScreenUtil.getScreenRectangle(aScreenX, aScreenY);
if (myLocateWithinScreen) {
Dimension preferredSize = myContent.getPreferredSize();
Object o = myContent.getClientProperty(FIRST_TIME_SIZE);
if (sizeToSet == null && o instanceof Dimension) {
int w = ((Dimension)o).width;
int h = ((Dimension)o).height;
if (w > 0) preferredSize.width = w;
if (h > 0) preferredSize.height = h;
sizeToSet = preferredSize;
}
Dimension size = sizeToSet != null ? sizeToSet : preferredSize;
if (size.width > screen.width) {
size.width = screen.width;
sizeToSet = size;
}
if (size.height > screen.height) {
size.height = screen.height;
sizeToSet = size;
}
}
if (sizeToSet != null) {
JBInsets.addTo(sizeToSet, myContent.getInsets());
sizeToSet.width = Math.max(sizeToSet.width, myContent.getMinimumSize().width);
sizeToSet.height = Math.max(sizeToSet.height, myContent.getMinimumSize().height);
myContent.setSize(sizeToSet);
myContent.setPreferredSize(sizeToSet);
}
Point xy = new Point(aScreenX, aScreenY);
boolean adjustXY = true;
if (myUseDimServiceForXYLocation) {
Point storedLocation = getStoredLocation();
if (storedLocation != null) {
xy = storedLocation;
adjustXY = false;
}
}
if (adjustXY) {
final Insets insets = myContent.getInsets();
if (insets != null) {
xy.x -= insets.left;
xy.y -= insets.top;
}
}
if (considerForcedXY && myForcedLocation != null) {
xy = myForcedLocation;
}
fixLocateByContent(xy, false);
Rectangle targetBounds = new Rectangle(xy, myContent.getPreferredSize());
if (targetBounds.width > screen.width || targetBounds.height > screen.height) {
StringBuilder sb = new StringBuilder("popup preferred size is bigger than screen: ");
sb.append(targetBounds.width).append("x").append(targetBounds.height);
IJSwingUtilities.appendComponentClassNames(sb, myContent);
LOG.warn(sb.toString());
}
Rectangle original = new Rectangle(targetBounds);
if (myLocateWithinScreen) {
ScreenUtil.moveToFit(targetBounds, screen, null);
}
if (myMouseOutCanceller != null) {
myMouseOutCanceller.myEverEntered = targetBounds.equals(original);
}
myOwner = getFrameOrDialog(owner); // use correct popup owner for non-modal dialogs too
if (myOwner == null) {
myOwner = owner;
}
myRequestorComponent = owner;
boolean forcedDialog = myMayBeParent || SystemInfo.isMac && !(myOwner instanceof IdeFrame) && myOwner.isShowing();
PopupComponent.Factory factory = getFactory(myForcedHeavyweight || myResizable, forcedDialog);
myNativePopup = factory.isNativePopup();
Component popupOwner = myOwner;
if (popupOwner instanceof RootPaneContainer && !(popupOwner instanceof IdeFrame && !Registry.is("popup.fix.ide.frame.owner"))) {
// JDK uses cached heavyweight popup for a window ancestor
RootPaneContainer root = (RootPaneContainer)popupOwner;
popupOwner = root.getRootPane();
LOG.debug("popup owner fixed for JDK cache");
}
if (LOG.isDebugEnabled()) {
LOG.debug("expected preferred size: " + myContent.getPreferredSize());
}
myPopup = factory.getPopup(popupOwner, myContent, targetBounds.x, targetBounds.y, this);
if (LOG.isDebugEnabled()) {
LOG.debug(" actual preferred size: " + myContent.getPreferredSize());
}
if (targetBounds.width != myContent.getWidth() || targetBounds.height != myContent.getHeight()) {
// JDK uses cached heavyweight popup that is not initialized properly
LOG.debug("the expected size is not equal to the actual size");
Window popup = myPopup.getWindow();
if (popup != null) {
popup.setSize(targetBounds.width, targetBounds.height);
if (myContent.getParent().getComponentCount() != 1) {
LOG.debug("unexpected count of components in heavy-weight popup");
}
}
else {
LOG.debug("cannot fix size for non-heavy-weight popup");
}
}
if (myResizable) {
final JRootPane root = myContent.getRootPane();
final IdeGlassPaneImpl glass = new IdeGlassPaneImpl(root);
root.setGlassPane(glass);
int i = Registry.intValue("ide.popup.resizable.border.sensitivity", 4);
WindowResizeListener resizeListener = new WindowResizeListener(
myComponent,
myMovable ? JBUI.insets(i) : JBUI.insets(0, 0, i, i),
null) {
private Cursor myCursor;
@Override
protected void setCursor(Component content, Cursor cursor) {
if (myCursor != cursor || myCursor != Cursor.getDefaultCursor()) {
glass.setCursor(cursor, this);
myCursor = cursor;
if (content instanceof JComponent) {
IdeGlassPaneImpl.savePreProcessedCursor((JComponent)content, content.getCursor());
}
super.setCursor(content, cursor);
}
}
@Override
protected void notifyResized() {
myResizeListeners.forEach(Runnable::run);
}
};
glass.addMousePreprocessor(resizeListener, this);
glass.addMouseMotionPreprocessor(resizeListener, this);
myResizeListener = resizeListener;
}
if (myCaption != null && myMovable) {
final WindowMoveListener moveListener = new WindowMoveListener(myCaption) {
@Override
public void mousePressed(final MouseEvent e) {
if (e.isConsumed()) return;
if (UIUtil.isCloseClick(e) && myCaption.isWithinPanel(e)) {
cancel();
}
else {
super.mousePressed(e);
}
}
};
myCaption.addMouseListener(moveListener);
myCaption.addMouseMotionListener(moveListener);
final MyContentPanel saved = myContent;
Disposer.register(this, () -> {
ListenerUtil.removeMouseListener(saved, moveListener);
ListenerUtil.removeMouseMotionListener(saved, moveListener);
});
myMoveListener = moveListener;
}
myListeners.forEach(listener -> listener.beforeShown(new LightweightWindowEvent(this)));
myPopup.setRequestFocus(myRequestFocus);
final Window window = getContentWindow(myContent);
if (window instanceof IdeFrame) {
LOG.warn("Lightweight popup is shown using AbstractPopup class. But this class is not supposed to work with lightweight popups.");
}
window.setFocusableWindowState(myRequestFocus);
window.setFocusable(myRequestFocus);
// Swing popup default always on top state is set in true
window.setAlwaysOnTop(false);
if (myFocusable) {
FocusTraversalPolicy focusTraversalPolicy = new FocusTraversalPolicy() {
@Override
public Component getComponentAfter(Container aContainer, Component aComponent) {
return getComponent();
}
private Component getComponent() {
return myPreferredFocusedComponent == null ? myComponent : myPreferredFocusedComponent;
}
@Override
public Component getComponentBefore(Container aContainer, Component aComponent) {
return getComponent();
}
@Override
public Component getFirstComponent(Container aContainer) {
return getComponent();
}
@Override
public Component getLastComponent(Container aContainer) {
return getComponent();
}
@Override
public Component getDefaultComponent(Container aContainer) {
return getComponent();
}
};
window.setFocusTraversalPolicy(focusTraversalPolicy);
Disposer.register(this, () -> window.setFocusTraversalPolicy(null));
}
window.setAutoRequestFocus(myRequestFocus);
final String data = getUserData(String.class);
final boolean popupIsSimpleWindow = "TRUE".equals(getContent().getClientProperty("BookmarkPopup"));
myContent.getRootPane().putClientProperty("SIMPLE_WINDOW", "SIMPLE_WINDOW".equals(data) || popupIsSimpleWindow);
myWindow = window;
if (myNormalWindowLevel) {
myWindow.setType(Window.Type.NORMAL);
}
setMinimumSize(myMinSize);
final Disposable tb = TouchBarsManager.showPopupBar(this, myContent);
if (tb != null)
Disposer.register(this, tb);
myPopup.show();
Rectangle bounds = window.getBounds();
PopupLocationTracker.register(this);
if (bounds.width > screen.width || bounds.height > screen.height) {
ScreenUtil.fitToScreen(bounds);
window.setBounds(bounds);
}
WindowAction.setEnabledFor(myPopup.getWindow(), myResizable);
myWindowListener = new MyWindowListener();
window.addWindowListener(myWindowListener);
if (myWindow != null) {
// dialog wrapper-based popups do this internally through peer,
// for other popups like jdialog-based we should exclude them manually, but
// we still have to be able to use IdeFrame as parent
if (!myMayBeParent && !(myWindow instanceof Frame)) {
WindowManager.getInstance().doNotSuggestAsParent(myWindow);
}
}
final Runnable afterShow = () -> {
if (isDisposed()) {
LOG.debug("popup is disposed after showing");
removeActivity();
return;
}
if ((myPreferredFocusedComponent instanceof AbstractButton || myPreferredFocusedComponent instanceof JTextField) && myFocusable) {
IJSwingUtilities.moveMousePointerOn(myPreferredFocusedComponent);
}
removeActivity();
afterShow();
};
if (myRequestFocus) {
if (myPreferredFocusedComponent != null) {
myPreferredFocusedComponent.requestFocus();
}
else {
_requestFocus();
}
window.setAutoRequestFocus(myRequestFocus);
SwingUtilities.invokeLater(afterShow);
}
else {
//noinspection SSBasedInspection
SwingUtilities.invokeLater(() -> {
if (isDisposed()) {
removeActivity();
return;
}
afterShow.run();
});
}
debugState("popup shown", State.SHOWING);
myState = State.SHOWN;
afterShowSync();
}
public void focusPreferredComponent() {
_requestFocus();
}
private void installProjectDisposer() {
final Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (c != null) {
final DataContext context = DataManager.getInstance().getDataContext(c);
final Project project = CommonDataKeys.PROJECT.getData(context);
if (project != null) {
myProjectDisposable = () -> {
if (!isDisposed()) {
Disposer.dispose(this);
}
};
Disposer.register(project, myProjectDisposable);
}
}
}
//Sometimes just after popup was shown the WINDOW_ACTIVATED cancels it
private static void installWindowHook(final @NotNull AbstractPopup popup) {
if (popup.myCancelOnWindow) {
popup.myCancelOnWindow = false;
new Alarm(popup).addRequest(() -> popup.myCancelOnWindow = true, 100);
}
}
private void addActivity() {
UiActivityMonitor.getInstance().addActivity(myActivityKey);
}
private void removeActivity() {
UiActivityMonitor.getInstance().removeActivity(myActivityKey);
}
private void prepareToShow() {
final MouseAdapter mouseAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Rectangle bounds = getBoundsOnScreen(myContent);
if (bounds != null) {
bounds.x -= 2;
bounds.y -= 2;
bounds.width += 4;
bounds.height += 4;
}
if (bounds == null || !bounds.contains(e.getLocationOnScreen())) {
cancel();
}
}
};
myContent.addMouseListener(mouseAdapter);
Disposer.register(this, () -> myContent.removeMouseListener(mouseAdapter));
myContent.addKeyListener(mySpeedSearch);
if (myCancelOnMouseOutCallback != null || myCancelOnWindow) {
myMouseOutCanceller = new Canceller();
Toolkit.getDefaultToolkit().addAWTEventListener(myMouseOutCanceller,
MOUSE_EVENT_MASK | WINDOW_ACTIVATED | WINDOW_GAINED_FOCUS | MOUSE_MOTION_EVENT_MASK);
}
ChildFocusWatcher focusWatcher = new ChildFocusWatcher(myContent) {
@Override
protected void onFocusGained(final FocusEvent event) {
setWindowActive(true);
}
@Override
protected void onFocusLost(final FocusEvent event) {
setWindowActive(false);
}
};
Disposer.register(this, focusWatcher);
mySpeedSearchPatternField = new SearchTextField(false) {
@Override
protected void onFieldCleared() {
mySpeedSearch.reset();
}
};
mySpeedSearchPatternField.getTextEditor().setFocusable(mySpeedSearchAlwaysShown);
if (mySpeedSearchAlwaysShown) {
setHeaderComponent(mySpeedSearchPatternField);
mySpeedSearchPatternField.setBorder(JBUI.Borders.customLine(JBUI.CurrentTheme.BigPopup.searchFieldBorderColor(), 1, 0, 1, 0));
mySpeedSearchPatternField.getTextEditor().setBorder(JBUI.Borders.empty());
}
if (SystemInfo.isMac) {
RelativeFont.TINY.install(mySpeedSearchPatternField);
}
}
private void updateMaskAndAlpha(Window window) {
if (window == null) return;
if (!window.isDisplayable() || !window.isShowing()) return;
final WindowManagerEx wndManager = getWndManager();
if (wndManager == null) return;
if (!wndManager.isAlphaModeEnabled(window)) return;
if (myAlpha != myLastAlpha) {
wndManager.setAlphaModeRatio(window, myAlpha);
myLastAlpha = myAlpha;
}
if (myMaskProvider != null) {
final Dimension size = window.getSize();
Shape mask = myMaskProvider.getMask(size);
wndManager.setWindowMask(window, mask);
}
WindowManagerEx.WindowShadowMode mode =
myShadowed ? WindowManagerEx.WindowShadowMode.NORMAL : WindowManagerEx.WindowShadowMode.DISABLED;
WindowManagerEx.getInstanceEx().setWindowShadow(window, mode);
}
private static WindowManagerEx getWndManager() {
return ApplicationManager.getApplication() != null ? WindowManagerEx.getInstanceEx() : null;
}
@Override
public boolean isDisposed() {
return myContent == null;
}
protected boolean beforeShow() {
if (ApplicationManager.getApplication() == null) return true;
StackingPopupDispatcher.getInstance().onPopupShown(this, myInStack);
return true;
}
protected void afterShow() {
}
protected void afterShowSync() {
}
protected final boolean requestFocus() {
if (!myFocusable) return false;
getFocusManager().doWhenFocusSettlesDown(() -> _requestFocus());
return true;
}
private void _requestFocus() {
if (!myFocusable) return;
JComponent toFocus = ObjectUtils.chooseNotNull(myPreferredFocusedComponent,
mySpeedSearchAlwaysShown ? mySpeedSearchPatternField : null);
if (toFocus != null) {
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> {
if (!myDisposed) {
IdeFocusManager.getGlobalInstance().requestFocus(toFocus, true);
}
});
}
}
private IdeFocusManager getFocusManager() {
if (myProject != null) {
return IdeFocusManager.getInstance(myProject);
}
if (myOwner != null) {
return IdeFocusManager.findInstanceByComponent(myOwner);
}
return IdeFocusManager.findInstance();
}
private static JComponent getTargetComponent(Component aComponent) {
if (aComponent instanceof JComponent) {
return (JComponent)aComponent;
}
if (aComponent instanceof RootPaneContainer) {
return ((RootPaneContainer)aComponent).getRootPane();
}
LOG.error("Cannot find target for:" + aComponent);
return null;
}
private PopupComponent.@NotNull Factory getFactory(boolean forceHeavyweight, boolean forceDialog) {
if (Registry.is("allow.dialog.based.popups")) {
boolean noFocus = !myFocusable || !myRequestFocus;
boolean cannotBeDialog = noFocus; // && SystemInfo.isXWindow
if (!cannotBeDialog && (isPersistent() || forceDialog)) {
return new PopupComponent.Factory.Dialog();
}
}
if (forceHeavyweight) {
return new PopupComponent.Factory.AwtHeavyweight();
}
return new PopupComponent.Factory.AwtDefault();
}
@Override
public @NotNull JComponent getContent() {
return myContent;
}
public void setLocation(@NotNull RelativePoint p) {
if (isBusy()) return;
setLocation(p, myPopup);
}
private static void setLocation(@NotNull RelativePoint p, @Nullable PopupComponent popup) {
if (popup == null) return;
final Window wnd = popup.getWindow();
assert wnd != null;
wnd.setLocation(p.getScreenPoint());
}
@Override
public void pack(boolean width, boolean height) {
if (!isVisible() || !width && !height || isBusy()) return;
Dimension size = getSize();
Dimension prefSize = myContent.computePreferredSize();
Point location = !myLocateWithinScreen ? null : getLocationOnScreen();
Rectangle screen = location == null ? null : ScreenUtil.getScreenRectangle(location);
if (width) {
size.width = prefSize.width;
if (screen != null) {
int delta = screen.width + screen.x - location.x;
if (size.width > delta) {
size.width = delta;
if (!SystemInfo.isMac || Registry.is("mac.scroll.horizontal.gap")) {
// we shrank horizontally - need to increase height to fit the horizontal scrollbar
JScrollPane scrollPane = ScrollUtil.findScrollPane(myContent);
if (scrollPane != null && scrollPane.getHorizontalScrollBarPolicy() != ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) {
JScrollBar scrollBar = scrollPane.getHorizontalScrollBar();
if (scrollBar != null) {
prefSize.height += scrollBar.getPreferredSize().height;
}
}
}
}
}
}
if (height) {
size.height = prefSize.height;
if (screen != null) {
int delta = screen.height + screen.y - location.y;
if (size.height > delta) {
size.height = delta;
}
}
}
size.height += getAdComponentHeight();
final Window window = getContentWindow(myContent);
if (window != null) {
window.setSize(size);
}
}
public JComponent getComponent() {
return myComponent;
}
public Project getProject() {
return myProject;
}
@Override
public void dispose() {
if (myState == State.SHOWN) {
LOG.debug("shown popup must be cancelled");
cancel();
}
if (myState == State.DISPOSE) {
return;
}
debugState("dispose popup", State.INIT, State.CANCEL);
myState = State.DISPOSE;
if (myDisposed) {
return;
}
myDisposed = true;
if (LOG.isDebugEnabled()) {
LOG.debug("start disposing " + myContent);
}
Disposer.dispose(this, false);
ApplicationManager.getApplication().assertIsDispatchThread();
if (myPopup != null) {
cancel(myDisposeEvent);
}
if (myContent != null) {
Container parent = myContent.getParent();
if (parent != null) parent.remove(myContent);
myContent.removeAll();
myContent.removeKeyListener(mySpeedSearch);
}
myContent = null;
myPreferredFocusedComponent = null;
myComponent = null;
mySpeedSearchFoundInRootComponent = null;
myCallBack = null;
myListeners.clear();
if (myMouseOutCanceller != null) {
final Toolkit toolkit = Toolkit.getDefaultToolkit();
// it may happen, but have no idea how
// http://www.jetbrains.net/jira/browse/IDEADEV-21265
if (toolkit != null) {
toolkit.removeAWTEventListener(myMouseOutCanceller);
}
}
myMouseOutCanceller = null;
if (myFinalRunnable != null) {
final ActionCallback typeAheadDone = new ActionCallback();
IdeFocusManager.getInstance(myProject).typeAheadUntil(typeAheadDone, "Abstract Popup Disposal");
ModalityState modalityState = ModalityState.current();
Runnable finalRunnable = myFinalRunnable;
getFocusManager().doWhenFocusSettlesDown(() -> {
if (ModalityState.current().equals(modalityState)) {
typeAheadDone.setDone();
((TransactionGuardImpl)TransactionGuard.getInstance()).performUserActivity(finalRunnable);
} else {
typeAheadDone.setRejected();
LOG.debug("Final runnable of popup is skipped");
}
// Otherwise the UI has changed unexpectedly and the action is likely not applicable.
// And we don't want finalRunnable to perform potentially destructive actions
// in the context of a suddenly appeared modal dialog.
});
myFinalRunnable = null;
}
if (LOG.isDebugEnabled()) {
LOG.debug("stop disposing content");
}
}
private void resetWindow() {
if (myWindow != null && getWndManager() != null) {
getWndManager().resetWindow(myWindow);
if (myWindowListener != null) {
myWindow.removeWindowListener(myWindowListener);
}
if (myWindow instanceof RootPaneContainer) {
RootPaneContainer container = (RootPaneContainer)myWindow;
JRootPane root = container.getRootPane();
root.putClientProperty(KEY, null);
if (root.getGlassPane() instanceof IdeGlassPaneImpl) {
// replace installed glass pane with the default one: JRootPane.createGlassPane()
JPanel glass = new JPanel();
glass.setName(root.getName() + ".glassPane");
glass.setVisible(false);
glass.setOpaque(false);
root.setGlassPane(glass);
}
}
myWindow = null;
myWindowListener = null;
}
}
public void storeDimensionSize() {
if (myDimensionServiceKey != null) {
Dimension size = myContent.getSize();
JBInsets.removeFrom(size, myContent.getInsets());
getWindowStateService(myProject).putSize(myDimensionServiceKey, size);
}
}
private void storeLocation(final Point xy) {
if (myDimensionServiceKey != null) {
getWindowStateService(myProject).putLocation(myDimensionServiceKey, xy);
}
}
public static class MyContentPanel extends JPanel implements DataProvider {
private @Nullable DataProvider myDataProvider;
/**
* @deprecated use {@link MyContentPanel#MyContentPanel(PopupBorder)}
*/
@Deprecated
public MyContentPanel(final boolean resizable, final PopupBorder border, boolean drawMacCorner) {
this(border);
DeprecatedMethodException.report("Use com.intellij.ui.popup.AbstractPopup.MyContentPanel.MyContentPanel(com.intellij.ui.PopupBorder) instead");
}
public MyContentPanel(@NotNull PopupBorder border) {
super(new BorderLayout());
putClientProperty(UIUtil.TEXT_COPY_ROOT, Boolean.TRUE);
setBorder(border);
}
public Dimension computePreferredSize() {
if (isPreferredSizeSet()) {
Dimension setSize = getPreferredSize();
setPreferredSize(null);
Dimension result = getPreferredSize();
setPreferredSize(setSize);
return result;
}
return getPreferredSize();
}
@Override
public @Nullable Object getData(@NotNull @NonNls String dataId) {
return myDataProvider != null ? myDataProvider.getData(dataId) : null;
}
public void setDataProvider(@Nullable DataProvider dataProvider) {
myDataProvider = dataProvider;
}
}
boolean isCancelOnClickOutside() {
return myCancelOnClickOutside;
}
boolean isCancelOnWindowDeactivation() {
return myCancelOnWindowDeactivation;
}
private class Canceller implements AWTEventListener {
private boolean myEverEntered;
@Override
public void eventDispatched(final AWTEvent event) {
switch (event.getID()) {
case WINDOW_ACTIVATED:
case WINDOW_GAINED_FOCUS:
if (myCancelOnWindow && myPopup != null && isCancelNeeded((WindowEvent)event, myPopup.getWindow())) {
cancel();
}
break;
case MOUSE_ENTERED:
if (withinPopup(event)) {
myEverEntered = true;
}
break;
case MOUSE_MOVED:
case MOUSE_PRESSED:
if (myCancelOnMouseOutCallback != null && myEverEntered && !withinPopup(event)) {
if (myCancelOnMouseOutCallback.check((MouseEvent)event)) {
cancel();
}
}
break;
}
}
private boolean withinPopup(@NotNull AWTEvent event) {
final MouseEvent mouse = (MouseEvent)event;
Rectangle bounds = getBoundsOnScreen(myContent);
return bounds != null && bounds.contains(mouse.getLocationOnScreen());
}
}
@Override
public void setLocation(@NotNull Point screenPoint) {
if (myPopup == null) {
myForcedLocation = screenPoint;
}
else if (!isBusy()) {
final Insets insets = myContent.getInsets();
if (insets != null && (insets.top != 0 || insets.left != 0)) {
screenPoint = new Point(screenPoint.x - insets.left, screenPoint.y - insets.top);
}
moveTo(myContent, screenPoint, myLocateByContent ? myHeaderPanel.getPreferredSize() : null);
}
}
private static void moveTo(@NotNull JComponent content, @NotNull Point screenPoint, @Nullable Dimension headerCorrectionSize) {
final Window wnd = getContentWindow(content);
if (wnd != null) {
wnd.setCursor(Cursor.getDefaultCursor());
if (headerCorrectionSize != null) {
screenPoint.y -= headerCorrectionSize.height;
}
wnd.setLocation(screenPoint);
}
}
private static Window getContentWindow(@NotNull Component content) {
Window window = SwingUtilities.getWindowAncestor(content);
if (window == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("no window ancestor for " + content);
}
}
return window;
}
@Override
public @NotNull Point getLocationOnScreen() {
Window window = getContentWindow(myContent);
Point screenPoint = window == null ? new Point() : window.getLocation();
fixLocateByContent(screenPoint, false);
Insets insets = myContent.getInsets();
if (insets != null) {
screenPoint.x += insets.left;
screenPoint.y += insets.top;
}
return screenPoint;
}
@Override
public void setSize(final @NotNull Dimension size) {
if (isBusy()) return;
Dimension toSet = new Dimension(size);
toSet.height += getAdComponentHeight();
if (myPopup == null) {
myForcedSize = toSet;
}
else {
updateMaskAndAlpha(setSize(myContent, toSet));
}
}
private int getAdComponentHeight() {
return myAdComponent != null ? myAdComponent.getPreferredSize().height + JBUIScale.scale(1) : 0;
}
@Override
public Dimension getSize() {
if (myPopup != null) {
final Window popupWindow = getContentWindow(myContent);
if (popupWindow != null) {
Dimension size = popupWindow.getSize();
size.height -= getAdComponentHeight();
return size;
}
}
return myForcedSize;
}
@Override
public void moveToFitScreen() {
if (myPopup == null || isBusy()) return;
final Window popupWindow = getContentWindow(myContent);
if (popupWindow == null) return;
Rectangle bounds = popupWindow.getBounds();
ScreenUtil.moveRectangleToFitTheScreen(bounds);
// calling #setLocation or #setSize makes the window move for a bit because of tricky computations
// our aim here is to just move the window as-is to make it fit the screen
// no tricks are included here
popupWindow.setBounds(bounds);
updateMaskAndAlpha(popupWindow);
}
public static Window setSize(@NotNull JComponent content, @NotNull Dimension size) {
final Window popupWindow = getContentWindow(content);
if (popupWindow == null) return null;
JBInsets.addTo(size, content.getInsets());
content.setPreferredSize(size);
popupWindow.pack();
return popupWindow;
}
@Override
public void setCaption(@NotNull @NlsContexts.PopupTitle String title) {
if (myCaption instanceof TitlePanel) {
((TitlePanel)myCaption).setText(title);
}
}
protected void setSpeedSearchAlwaysShown() {
assert myState == State.INIT;
mySpeedSearchAlwaysShown = true;
}
private class MyWindowListener extends WindowAdapter {
@Override
public void windowOpened(WindowEvent e) {
updateMaskAndAlpha(myWindow);
}
@Override
public void windowClosing(final WindowEvent e) {
resetWindow();
cancel();
}
}
@Override
public boolean isPersistent() {
return !myCancelOnClickOutside && !myCancelOnWindow;
}
@Override
public boolean isNativePopup() {
return myNativePopup;
}
@Override
public void setUiVisible(final boolean visible) {
if (myPopup != null) {
if (visible) {
myPopup.show();
final Window window = getPopupWindow();
if (window != null && myRestoreWindowSize != null) {
window.setSize(myRestoreWindowSize);
myRestoreWindowSize = null;
}
}
else {
final Window window = getPopupWindow();
if (window != null) {
myRestoreWindowSize = window.getSize();
window.setVisible(false);
}
}
}
}
public Window getPopupWindow() {
return myPopup != null ? myPopup.getWindow() : null;
}
@Override
public void setUserData(@NotNull List<Object> userData) {
myUserData = userData;
}
@Override
public <T> T getUserData(final @NotNull Class<T> userDataClass) {
if (myUserData != null) {
for (Object o : myUserData) {
if (userDataClass.isInstance(o)) {
@SuppressWarnings("unchecked") T t = (T)o;
return t;
}
}
}
return null;
}
@Override
public boolean isModalContext() {
return myModalContext;
}
@Override
public boolean isFocused() {
if (myComponent != null && isFocused(new Component[]{SwingUtilities.getWindowAncestor(myComponent)})) {
return true;
}
return isFocused(myFocusOwners);
}
private static boolean isFocused(Component @NotNull [] components) {
Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (owner == null) return false;
Window wnd = ComponentUtil.getWindow(owner);
for (Component each : components) {
if (each != null && SwingUtilities.isDescendingFrom(owner, each)) {
Window eachWindow = ComponentUtil.getWindow(each);
if (eachWindow == wnd) {
return true;
}
}
}
return false;
}
@Override
public boolean isCancelKeyEnabled() {
return myCancelKeyEnabled;
}
public @NotNull CaptionPanel getTitle() {
return myCaption;
}
protected void setHeaderComponent(JComponent c) {
boolean doRevalidate = false;
if (myHeaderComponent != null) {
myHeaderPanel.remove(myHeaderComponent);
myHeaderComponent = null;
doRevalidate = true;
}
if (c != null) {
myHeaderPanel.add(c, BorderLayout.CENTER);
myHeaderComponent = c;
if (isVisible()) {
final Dimension size = myContent.getSize();
if (size.height < c.getPreferredSize().height * 2) {
size.height += c.getPreferredSize().height;
setSize(size);
}
}
doRevalidate = true;
}
if (doRevalidate) myContent.revalidate();
}
public void setWarning(@NotNull String text) {
JBLabel label = new JBLabel(text, UIUtil.getBalloonWarningIcon(), SwingConstants.CENTER);
label.setOpaque(true);
Color color = HintUtil.getInformationColor();
label.setBackground(color);
label.setBorder(BorderFactory.createLineBorder(color, 3));
myHeaderPanel.add(label, BorderLayout.SOUTH);
}
@Override
public void addListener(@NotNull JBPopupListener listener) {
myListeners.add(0, listener); // last added first notified
}
@Override
public void removeListener(@NotNull JBPopupListener listener) {
myListeners.remove(listener);
}
protected void onSpeedSearchPatternChanged() {
}
@Override
public Component getOwner() {
return myRequestorComponent;
}
@Override
public void setMinimumSize(Dimension size) {
//todo: consider changing only the caption panel minimum size
Dimension sizeFromHeader = myHeaderPanel.getPreferredSize();
if (sizeFromHeader == null) {
sizeFromHeader = myHeaderPanel.getMinimumSize();
}
if (sizeFromHeader == null) {
int minimumSize = myWindow.getGraphics().getFontMetrics(myHeaderPanel.getFont()).getHeight();
sizeFromHeader = new Dimension(minimumSize, minimumSize);
}
if (size == null) {
myMinSize = sizeFromHeader;
} else {
final int width = Math.max(size.width, sizeFromHeader.width);
final int height = Math.max(size.height, sizeFromHeader.height);
myMinSize = new Dimension(width, height);
}
if (myWindow != null) {
Rectangle screenRectangle = ScreenUtil.getScreenRectangle(myWindow.getLocation());
int width = Math.min(screenRectangle.width, myMinSize.width);
int height = Math.min(screenRectangle.height, myMinSize.height);
myWindow.setMinimumSize(new Dimension(width, height));
}
}
public void setOkHandler(Runnable okHandler) {
myOkHandler = okHandler;
}
@Override
public void setFinalRunnable(Runnable finalRunnable) {
myFinalRunnable = finalRunnable;
}
public void setOk(boolean ok) {
myOk = ok;
}
@Override
public void setDataProvider(@NotNull DataProvider dataProvider) {
if (myContent != null) {
myContent.setDataProvider(dataProvider);
}
}
@Override
public boolean dispatchKeyEvent(@NotNull KeyEvent e) {
BooleanFunction<? super KeyEvent> handler = myKeyEventHandler;
if (handler != null && handler.fun(e)) {
return true;
}
if (isCloseRequest(e) && myCancelKeyEnabled && !mySpeedSearch.isHoldingFilter()) {
if (mySpeedSearchFoundInRootComponent != null && mySpeedSearchFoundInRootComponent.isHoldingFilter()) {
mySpeedSearchFoundInRootComponent.reset();
}
else {
cancel(e);
}
return true;
}
return false;
}
public @NotNull Dimension getHeaderPreferredSize() {
return myHeaderPanel.getPreferredSize();
}
public @NotNull Dimension getFooterPreferredSize() {
return myAdComponent == null ? new Dimension(0,0) : myAdComponent.getPreferredSize();
}
public static boolean isCloseRequest(KeyEvent e) {
return e != null && e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_ESCAPE && e.getModifiers() == 0;
}
private @NotNull Point fixLocateByContent(@NotNull Point location, boolean save) {
Dimension size = !myLocateByContent ? null : myHeaderPanel.getPreferredSize();
if (size != null) location.y -= save ? -size.height : size.height;
return location;
}
protected boolean isBusy() {
return myResizeListener != null && myResizeListener.isBusy() || myMoveListener != null && myMoveListener.isBusy();
}
/**
* Returns the first frame (or dialog) ancestor of the component.
* Note that this method returns the component itself if it is a frame (or dialog).
*
* @param component the component used to find corresponding frame (or dialog)
* @return the first frame (or dialog) ancestor of the component; or {@code null}
* if the component is not a frame (or dialog) and is not contained inside a frame (or dialog)
*
* @see UIUtil#getWindow
*/
private static Component getFrameOrDialog(Component component) {
while (component != null) {
if (component instanceof Window) return component;
component = component.getParent();
}
return null;
}
private static @Nullable Point getLocationOnScreen(@Nullable Component component) {
return component == null || !component.isShowing() ? null : component.getLocationOnScreen();
}
private static @Nullable Rectangle getBoundsOnScreen(@Nullable Component component) {
Point point = getLocationOnScreen(component);
return point == null ? null : new Rectangle(point, component.getSize());
}
public static @NotNull List<JBPopup> getChildPopups(final @NotNull Component component) {
return ContainerUtil.filter(all.toStrongList(), popup -> {
Component owner = popup.getOwner();
while (owner != null) {
if (owner.equals(component)) {
return true;
}
owner = owner.getParent();
}
return false;
});
}
@Override
public boolean canShow() {
return myState == State.INIT;
}
@Override
public @NotNull Rectangle getConsumedScreenBounds() {
return myWindow.getBounds();
}
@Override
public Window getUnderlyingWindow() {
return myWindow.getOwner();
}
/**
* Passed listener will be notified if popup is resized by user (using mouse)
*/
public void addResizeListener(@NotNull Runnable runnable, @NotNull Disposable parentDisposable) {
myResizeListeners.add(runnable);
Disposer.register(parentDisposable, () -> myResizeListeners.remove(runnable));
}
/**
* @param event a {@code WindowEvent} for the activated or focused window
* @param popup a window that corresponds to the current popup
* @return {@code false} if a focus moved to a popup window or its child window in the whole hierarchy
*/
private static boolean isCancelNeeded(@NotNull WindowEvent event, @Nullable Window popup) {
Window window = event.getWindow(); // the activated or focused window
while (window != null) {
if (popup == window) return false; // do not close a popup, which child is activated or focused
window = window.getOwner(); // consider a window owner as activated or focused
}
return true;
}
private @Nullable Point getStoredLocation() {
if (myDimensionServiceKey == null) return null;
return getWindowStateService(myProject).getLocation(myDimensionServiceKey);
}
private @Nullable Dimension getStoredSize() {
if (myDimensionServiceKey == null) return null;
return getWindowStateService(myProject).getSize(myDimensionServiceKey);
}
private static @NotNull WindowStateService getWindowStateService(@Nullable Project project) {
return project == null ? WindowStateService.getInstance() : WindowStateService.getInstance(project);
}
private static <T> T findInComponentHierarchy(@NotNull Component component, Function<@NotNull Component, @Nullable T> mapper) {
T found = mapper.fun(component);
if (found != null) {
return found;
}
if (component instanceof JComponent) {
for (Component child : ((JComponent)component).getComponents()) {
found = findInComponentHierarchy(child, mapper);
if (found != null) {
return found;
}
}
}
return null;
}
}
| IDEA-CR-64106 Fix `GotoDeclarationTestGenerated#testImportAliasMultiDeclarations` in Kotlin plugin
This commit is part 2 of "Introduce EditorActivityManager which abstracts away visibility/focus from actual swing components"
GitOrigin-RevId: 83feca77241bbc4fe1776b6c79787ff2ced1373f | platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java | IDEA-CR-64106 Fix `GotoDeclarationTestGenerated#testImportAliasMultiDeclarations` in Kotlin plugin |
|
Java | apache-2.0 | 6df4cb1cf48bffacdecac08331b86e8ef883fbe0 | 0 | HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.mob;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.PrivateCellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.Tag;
import org.apache.hadoop.hbase.TagType;
import org.apache.hadoop.hbase.TagUtil;
import org.apache.hadoop.hbase.backup.HFileArchiver;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
import org.apache.hadoop.hbase.client.MobCompactPartitionPolicy;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.RegionInfoBuilder;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.io.HFileLink;
import org.apache.hadoop.hbase.io.compress.Compression;
import org.apache.hadoop.hbase.io.crypto.Encryption;
import org.apache.hadoop.hbase.io.hfile.CacheConfig;
import org.apache.hadoop.hbase.io.hfile.HFile;
import org.apache.hadoop.hbase.io.hfile.HFileContext;
import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
import org.apache.hadoop.hbase.master.locking.LockManager;
import org.apache.hadoop.hbase.mob.compactions.MobCompactor;
import org.apache.hadoop.hbase.mob.compactions.PartitionedMobCompactionRequest.CompactionPartitionId;
import org.apache.hadoop.hbase.mob.compactions.PartitionedMobCompactor;
import org.apache.hadoop.hbase.regionserver.BloomType;
import org.apache.hadoop.hbase.regionserver.HStoreFile;
import org.apache.hadoop.hbase.regionserver.StoreFileWriter;
import org.apache.hadoop.hbase.regionserver.StoreUtils;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.ChecksumType;
import org.apache.hadoop.hbase.util.CommonFSUtils;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.ReflectionUtils;
import org.apache.hadoop.hbase.util.Threads;
import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.yetus.audience.InterfaceAudience;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The mob utilities
*/
@InterfaceAudience.Private
public final class MobUtils {
private static final Logger LOG = LoggerFactory.getLogger(MobUtils.class);
private final static long WEEKLY_THRESHOLD_MULTIPLIER = 7;
private final static long MONTHLY_THRESHOLD_MULTIPLIER = 4 * WEEKLY_THRESHOLD_MULTIPLIER;
private static final ThreadLocal<SimpleDateFormat> LOCAL_FORMAT =
new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyyMMdd");
}
};
private static final byte[] REF_DELETE_MARKER_TAG_BYTES;
static {
List<Tag> tags = new ArrayList<>();
tags.add(MobConstants.MOB_REF_TAG);
REF_DELETE_MARKER_TAG_BYTES = TagUtil.fromList(tags);
}
/**
* Private constructor to keep this class from being instantiated.
*/
private MobUtils() {
}
/**
* Formats a date to a string.
* @param date The date.
* @return The string format of the date, it's yyyymmdd.
*/
public static String formatDate(Date date) {
return LOCAL_FORMAT.get().format(date);
}
/**
* Parses the string to a date.
* @param dateString The string format of a date, it's yyyymmdd.
* @return A date.
*/
public static Date parseDate(String dateString) throws ParseException {
return LOCAL_FORMAT.get().parse(dateString);
}
/**
* Get the first day of the input date's month
* @param calendar Calendar object
* @param date The date to find out its first day of that month
* @return The first day in the month
*/
public static Date getFirstDayOfMonth(final Calendar calendar, final Date date) {
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date firstDayInMonth = calendar.getTime();
return firstDayInMonth;
}
/**
* Get the first day of the input date's week
* @param calendar Calendar object
* @param date The date to find out its first day of that week
* @return The first day in the week
*/
public static Date getFirstDayOfWeek(final Calendar calendar, final Date date) {
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
Date firstDayInWeek = calendar.getTime();
return firstDayInWeek;
}
/**
* Whether the current cell is a mob reference cell.
* @param cell The current cell.
* @return True if the cell has a mob reference tag, false if it doesn't.
*/
public static boolean isMobReferenceCell(Cell cell) {
if (cell.getTagsLength() > 0) {
Optional<Tag> tag = PrivateCellUtil.getTag(cell, TagType.MOB_REFERENCE_TAG_TYPE);
if (tag.isPresent()) {
return true;
}
}
return false;
}
/**
* Gets the table name tag.
* @param cell The current cell.
* @return The table name tag.
*/
public static Tag getTableNameTag(Cell cell) {
if (cell.getTagsLength() > 0) {
Optional<Tag> tag = PrivateCellUtil.getTag(cell, TagType.MOB_TABLE_NAME_TAG_TYPE);
if (tag.isPresent()) {
return tag.get();
}
}
return null;
}
/**
* Whether the tag list has a mob reference tag.
* @param tags The tag list.
* @return True if the list has a mob reference tag, false if it doesn't.
*/
public static boolean hasMobReferenceTag(List<Tag> tags) {
if (!tags.isEmpty()) {
for (Tag tag : tags) {
if (tag.getType() == TagType.MOB_REFERENCE_TAG_TYPE) {
return true;
}
}
}
return false;
}
/**
* Indicates whether it's a raw scan.
* The information is set in the attribute "hbase.mob.scan.raw" of scan.
* For a mob cell, in a normal scan the scanners retrieves the mob cell from the mob file.
* In a raw scan, the scanner directly returns cell in HBase without retrieve the one in
* the mob file.
* @param scan The current scan.
* @return True if it's a raw scan.
*/
public static boolean isRawMobScan(Scan scan) {
byte[] raw = scan.getAttribute(MobConstants.MOB_SCAN_RAW);
try {
return raw != null && Bytes.toBoolean(raw);
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Indicates whether it's a reference only scan.
* The information is set in the attribute "hbase.mob.scan.ref.only" of scan.
* If it's a ref only scan, only the cells with ref tag are returned.
* @param scan The current scan.
* @return True if it's a ref only scan.
*/
public static boolean isRefOnlyScan(Scan scan) {
byte[] refOnly = scan.getAttribute(MobConstants.MOB_SCAN_REF_ONLY);
try {
return refOnly != null && Bytes.toBoolean(refOnly);
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Indicates whether the scan contains the information of caching blocks.
* The information is set in the attribute "hbase.mob.cache.blocks" of scan.
* @param scan The current scan.
* @return True when the Scan attribute specifies to cache the MOB blocks.
*/
public static boolean isCacheMobBlocks(Scan scan) {
byte[] cache = scan.getAttribute(MobConstants.MOB_CACHE_BLOCKS);
try {
return cache != null && Bytes.toBoolean(cache);
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Sets the attribute of caching blocks in the scan.
*
* @param scan
* The current scan.
* @param cacheBlocks
* True, set the attribute of caching blocks into the scan, the scanner with this scan
* caches blocks.
* False, the scanner doesn't cache blocks for this scan.
*/
public static void setCacheMobBlocks(Scan scan, boolean cacheBlocks) {
scan.setAttribute(MobConstants.MOB_CACHE_BLOCKS, Bytes.toBytes(cacheBlocks));
}
/**
* Cleans the expired mob files.
* Cleans the files whose creation date is older than (current - columnFamily.ttl), and
* the minVersions of that column family is 0.
* @param fs The current file system.
* @param conf The current configuration.
* @param tableName The current table name.
* @param columnDescriptor The descriptor of the current column family.
* @param cacheConfig The cacheConfig that disables the block cache.
* @param current The current time.
*/
public static void cleanExpiredMobFiles(FileSystem fs, Configuration conf, TableName tableName,
ColumnFamilyDescriptor columnDescriptor, CacheConfig cacheConfig, long current)
throws IOException {
long timeToLive = columnDescriptor.getTimeToLive();
if (Integer.MAX_VALUE == timeToLive) {
// no need to clean, because the TTL is not set.
return;
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(current - timeToLive * 1000);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date expireDate = calendar.getTime();
LOG.info("MOB HFiles older than " + expireDate.toGMTString() + " will be deleted!");
FileStatus[] stats = null;
Path mobTableDir = CommonFSUtils.getTableDir(getMobHome(conf), tableName);
Path path = getMobFamilyPath(conf, tableName, columnDescriptor.getNameAsString());
try {
stats = fs.listStatus(path);
} catch (FileNotFoundException e) {
LOG.warn("Failed to find the mob file " + path, e);
}
if (null == stats) {
// no file found
return;
}
List<HStoreFile> filesToClean = new ArrayList<>();
int deletedFileCount = 0;
for (FileStatus file : stats) {
String fileName = file.getPath().getName();
try {
if (HFileLink.isHFileLink(file.getPath())) {
HFileLink hfileLink = HFileLink.buildFromHFileLinkPattern(conf, file.getPath());
fileName = hfileLink.getOriginPath().getName();
}
Date fileDate = parseDate(MobFileName.getDateFromName(fileName));
if (LOG.isDebugEnabled()) {
LOG.debug("Checking file " + fileName);
}
if (fileDate.getTime() < expireDate.getTime()) {
if (LOG.isDebugEnabled()) {
LOG.debug(fileName + " is an expired file");
}
filesToClean
.add(new HStoreFile(fs, file.getPath(), conf, cacheConfig, BloomType.NONE, true));
}
} catch (Exception e) {
LOG.error("Cannot parse the fileName " + fileName, e);
}
}
if (!filesToClean.isEmpty()) {
try {
removeMobFiles(conf, fs, tableName, mobTableDir, columnDescriptor.getName(),
filesToClean);
deletedFileCount = filesToClean.size();
} catch (IOException e) {
LOG.error("Failed to delete the mob files " + filesToClean, e);
}
}
LOG.info(deletedFileCount + " expired mob files are deleted");
}
/**
* Gets the root dir of the mob files.
* It's {HBASE_DIR}/mobdir.
* @param conf The current configuration.
* @return the root dir of the mob file.
*/
public static Path getMobHome(Configuration conf) {
Path hbaseDir = new Path(conf.get(HConstants.HBASE_DIR));
return getMobHome(hbaseDir);
}
/**
* Gets the root dir of the mob files under the qualified HBase root dir.
* It's {rootDir}/mobdir.
* @param rootDir The qualified path of HBase root directory.
* @return The root dir of the mob file.
*/
public static Path getMobHome(Path rootDir) {
return new Path(rootDir, MobConstants.MOB_DIR_NAME);
}
/**
* Gets the qualified root dir of the mob files.
* @param conf The current configuration.
* @return The qualified root dir.
*/
public static Path getQualifiedMobRootDir(Configuration conf) throws IOException {
Path hbaseDir = new Path(conf.get(HConstants.HBASE_DIR));
Path mobRootDir = new Path(hbaseDir, MobConstants.MOB_DIR_NAME);
FileSystem fs = mobRootDir.getFileSystem(conf);
return mobRootDir.makeQualified(fs.getUri(), fs.getWorkingDirectory());
}
/**
* Gets the table dir of the mob files under the qualified HBase root dir.
* It's {rootDir}/mobdir/data/${namespace}/${tableName}
* @param rootDir The qualified path of HBase root directory.
* @param tableName The name of table.
* @return The table dir of the mob file.
*/
public static Path getMobTableDir(Path rootDir, TableName tableName) {
return CommonFSUtils.getTableDir(getMobHome(rootDir), tableName);
}
/**
* Gets the region dir of the mob files.
* It's {HBASE_DIR}/mobdir/data/{namespace}/{tableName}/{regionEncodedName}.
* @param conf The current configuration.
* @param tableName The current table name.
* @return The region dir of the mob files.
*/
public static Path getMobRegionPath(Configuration conf, TableName tableName) {
return getMobRegionPath(new Path(conf.get(HConstants.HBASE_DIR)), tableName);
}
/**
* Gets the region dir of the mob files under the specified root dir.
* It's {rootDir}/mobdir/data/{namespace}/{tableName}/{regionEncodedName}.
* @param rootDir The qualified path of HBase root directory.
* @param tableName The current table name.
* @return The region dir of the mob files.
*/
public static Path getMobRegionPath(Path rootDir, TableName tableName) {
Path tablePath = CommonFSUtils.getTableDir(getMobHome(rootDir), tableName);
RegionInfo regionInfo = getMobRegionInfo(tableName);
return new Path(tablePath, regionInfo.getEncodedName());
}
/**
* Gets the family dir of the mob files.
* It's {HBASE_DIR}/mobdir/{namespace}/{tableName}/{regionEncodedName}/{columnFamilyName}.
* @param conf The current configuration.
* @param tableName The current table name.
* @param familyName The current family name.
* @return The family dir of the mob files.
*/
public static Path getMobFamilyPath(Configuration conf, TableName tableName, String familyName) {
return new Path(getMobRegionPath(conf, tableName), familyName);
}
/**
* Gets the family dir of the mob files.
* It's {HBASE_DIR}/mobdir/{namespace}/{tableName}/{regionEncodedName}/{columnFamilyName}.
* @param regionPath The path of mob region which is a dummy one.
* @param familyName The current family name.
* @return The family dir of the mob files.
*/
public static Path getMobFamilyPath(Path regionPath, String familyName) {
return new Path(regionPath, familyName);
}
/**
* Gets the RegionInfo of the mob files.
* This is a dummy region. The mob files are not saved in a region in HBase.
* This is only used in mob snapshot. It's internally used only.
* @param tableName
* @return A dummy mob region info.
*/
public static RegionInfo getMobRegionInfo(TableName tableName) {
return RegionInfoBuilder.newBuilder(tableName)
.setStartKey(MobConstants.MOB_REGION_NAME_BYTES)
.setEndKey(HConstants.EMPTY_END_ROW)
.setSplit(false)
.setRegionId(0)
.build();
}
/**
* Gets whether the current RegionInfo is a mob one.
* @param regionInfo The current RegionInfo.
* @return If true, the current RegionInfo is a mob one.
*/
public static boolean isMobRegionInfo(RegionInfo regionInfo) {
return regionInfo == null ? false : getMobRegionInfo(regionInfo.getTable()).getEncodedName()
.equals(regionInfo.getEncodedName());
}
/**
* Gets whether the current region name follows the pattern of a mob region name.
* @param tableName The current table name.
* @param regionName The current region name.
* @return True if the current region name follows the pattern of a mob region name.
*/
public static boolean isMobRegionName(TableName tableName, byte[] regionName) {
return Bytes.equals(regionName, getMobRegionInfo(tableName).getRegionName());
}
/**
* Gets the working directory of the mob compaction.
* @param root The root directory of the mob compaction.
* @param jobName The current job name.
* @return The directory of the mob compaction for the current job.
*/
public static Path getCompactionWorkingPath(Path root, String jobName) {
return new Path(root, jobName);
}
/**
* Archives the mob files.
* @param conf The current configuration.
* @param fs The current file system.
* @param tableName The table name.
* @param tableDir The table directory.
* @param family The name of the column family.
* @param storeFiles The files to be deleted.
*/
public static void removeMobFiles(Configuration conf, FileSystem fs, TableName tableName,
Path tableDir, byte[] family, Collection<HStoreFile> storeFiles) throws IOException {
HFileArchiver.archiveStoreFiles(conf, fs, getMobRegionInfo(tableName), tableDir, family,
storeFiles);
}
/**
* Creates a mob reference KeyValue.
* The value of the mob reference KeyValue is mobCellValueSize + mobFileName.
* @param cell The original Cell.
* @param fileName The mob file name where the mob reference KeyValue is written.
* @param tableNameTag The tag of the current table name. It's very important in
* cloning the snapshot.
* @return The mob reference KeyValue.
*/
public static Cell createMobRefCell(Cell cell, byte[] fileName, Tag tableNameTag) {
// Append the tags to the KeyValue.
// The key is same, the value is the filename of the mob file
List<Tag> tags = new ArrayList<>();
// Add the ref tag as the 1st one.
tags.add(MobConstants.MOB_REF_TAG);
// Add the tag of the source table name, this table is where this mob file is flushed
// from.
// It's very useful in cloning the snapshot. When reading from the cloning table, we need to
// find the original mob files by this table name. For details please see cloning
// snapshot for mob files.
tags.add(tableNameTag);
return createMobRefCell(cell, fileName, TagUtil.fromList(tags));
}
public static Cell createMobRefCell(Cell cell, byte[] fileName, byte[] refCellTags) {
byte[] refValue = Bytes.add(Bytes.toBytes(cell.getValueLength()), fileName);
return PrivateCellUtil.createCell(cell, refValue, TagUtil.concatTags(refCellTags, cell));
}
/**
* Creates a writer for the mob file in temp directory.
* @param conf The current configuration.
* @param fs The current file system.
* @param family The descriptor of the current column family.
* @param date The date string, its format is yyyymmmdd.
* @param basePath The basic path for a temp directory.
* @param maxKeyCount The key count.
* @param compression The compression algorithm.
* @param startKey The hex string of the start key.
* @param cacheConfig The current cache config.
* @param cryptoContext The encryption context.
* @param isCompaction If the writer is used in compaction.
* @return The writer for the mob file.
*/
public static StoreFileWriter createWriter(Configuration conf, FileSystem fs,
ColumnFamilyDescriptor family, String date, Path basePath, long maxKeyCount,
Compression.Algorithm compression, String startKey, CacheConfig cacheConfig,
Encryption.Context cryptoContext, boolean isCompaction)
throws IOException {
MobFileName mobFileName = MobFileName.create(startKey, date,
UUID.randomUUID().toString().replaceAll("-", ""));
return createWriter(conf, fs, family, mobFileName, basePath, maxKeyCount, compression,
cacheConfig, cryptoContext, isCompaction);
}
/**
* Creates a writer for the ref file in temp directory.
* @param conf The current configuration.
* @param fs The current file system.
* @param family The descriptor of the current column family.
* @param basePath The basic path for a temp directory.
* @param maxKeyCount The key count.
* @param cacheConfig The current cache config.
* @param cryptoContext The encryption context.
* @param isCompaction If the writer is used in compaction.
* @return The writer for the mob file.
*/
public static StoreFileWriter createRefFileWriter(Configuration conf, FileSystem fs,
ColumnFamilyDescriptor family, Path basePath, long maxKeyCount, CacheConfig cacheConfig,
Encryption.Context cryptoContext, boolean isCompaction)
throws IOException {
return createWriter(conf, fs, family,
new Path(basePath, UUID.randomUUID().toString().replaceAll("-", "")), maxKeyCount,
family.getCompactionCompressionType(), cacheConfig, cryptoContext,
StoreUtils.getChecksumType(conf), StoreUtils.getBytesPerChecksum(conf), family.getBlocksize(),
family.getBloomFilterType(), isCompaction);
}
/**
* Creates a writer for the mob file in temp directory.
* @param conf The current configuration.
* @param fs The current file system.
* @param family The descriptor of the current column family.
* @param date The date string, its format is yyyymmmdd.
* @param basePath The basic path for a temp directory.
* @param maxKeyCount The key count.
* @param compression The compression algorithm.
* @param startKey The start key.
* @param cacheConfig The current cache config.
* @param cryptoContext The encryption context.
* @param isCompaction If the writer is used in compaction.
* @return The writer for the mob file.
*/
public static StoreFileWriter createWriter(Configuration conf, FileSystem fs,
ColumnFamilyDescriptor family, String date, Path basePath, long maxKeyCount,
Compression.Algorithm compression, byte[] startKey, CacheConfig cacheConfig,
Encryption.Context cryptoContext, boolean isCompaction)
throws IOException {
MobFileName mobFileName = MobFileName.create(startKey, date,
UUID.randomUUID().toString().replaceAll("-", ""));
return createWriter(conf, fs, family, mobFileName, basePath, maxKeyCount, compression,
cacheConfig, cryptoContext, isCompaction);
}
/**
* Creates a writer for the del file in temp directory.
* @param conf The current configuration.
* @param fs The current file system.
* @param family The descriptor of the current column family.
* @param date The date string, its format is yyyymmmdd.
* @param basePath The basic path for a temp directory.
* @param maxKeyCount The key count.
* @param compression The compression algorithm.
* @param startKey The start key.
* @param cacheConfig The current cache config.
* @param cryptoContext The encryption context.
* @return The writer for the del file.
*/
public static StoreFileWriter createDelFileWriter(Configuration conf, FileSystem fs,
ColumnFamilyDescriptor family, String date, Path basePath, long maxKeyCount,
Compression.Algorithm compression, byte[] startKey, CacheConfig cacheConfig,
Encryption.Context cryptoContext)
throws IOException {
String suffix = UUID
.randomUUID().toString().replaceAll("-", "") + "_del";
MobFileName mobFileName = MobFileName.create(startKey, date, suffix);
return createWriter(conf, fs, family, mobFileName, basePath, maxKeyCount, compression,
cacheConfig, cryptoContext, true);
}
/**
* Creates a writer for the mob file in temp directory.
* @param conf The current configuration.
* @param fs The current file system.
* @param family The descriptor of the current column family.
* @param mobFileName The mob file name.
* @param basePath The basic path for a temp directory.
* @param maxKeyCount The key count.
* @param compression The compression algorithm.
* @param cacheConfig The current cache config.
* @param cryptoContext The encryption context.
* @param isCompaction If the writer is used in compaction.
* @return The writer for the mob file.
*/
public static StoreFileWriter createWriter(Configuration conf, FileSystem fs,
ColumnFamilyDescriptor family, MobFileName mobFileName, Path basePath, long maxKeyCount,
Compression.Algorithm compression, CacheConfig cacheConfig, Encryption.Context cryptoContext,
boolean isCompaction)
throws IOException {
return createWriter(conf, fs, family,
new Path(basePath, mobFileName.getFileName()), maxKeyCount, compression, cacheConfig,
cryptoContext, StoreUtils.getChecksumType(conf), StoreUtils.getBytesPerChecksum(conf),
family.getBlocksize(), BloomType.NONE, isCompaction);
}
/**
* Creates a writer for the mob file in temp directory.
* @param conf The current configuration.
* @param fs The current file system.
* @param family The descriptor of the current column family.
* @param path The path for a temp directory.
* @param maxKeyCount The key count.
* @param compression The compression algorithm.
* @param cacheConfig The current cache config.
* @param cryptoContext The encryption context.
* @param checksumType The checksum type.
* @param bytesPerChecksum The bytes per checksum.
* @param blocksize The HFile block size.
* @param bloomType The bloom filter type.
* @param isCompaction If the writer is used in compaction.
* @return The writer for the mob file.
*/
public static StoreFileWriter createWriter(Configuration conf, FileSystem fs,
ColumnFamilyDescriptor family, Path path, long maxKeyCount,
Compression.Algorithm compression, CacheConfig cacheConfig, Encryption.Context cryptoContext,
ChecksumType checksumType, int bytesPerChecksum, int blocksize, BloomType bloomType,
boolean isCompaction)
throws IOException {
if (compression == null) {
compression = HFile.DEFAULT_COMPRESSION_ALGORITHM;
}
final CacheConfig writerCacheConf;
if (isCompaction) {
writerCacheConf = new CacheConfig(cacheConfig);
writerCacheConf.setCacheDataOnWrite(false);
} else {
writerCacheConf = cacheConfig;
}
HFileContext hFileContext = new HFileContextBuilder().withCompression(compression)
.withIncludesMvcc(true).withIncludesTags(true)
.withCompressTags(family.isCompressTags())
.withChecksumType(checksumType)
.withBytesPerCheckSum(bytesPerChecksum)
.withBlockSize(blocksize)
.withHBaseCheckSum(true).withDataBlockEncoding(family.getDataBlockEncoding())
.withEncryptionContext(cryptoContext)
.withCreateTime(EnvironmentEdgeManager.currentTime()).build();
StoreFileWriter w = new StoreFileWriter.Builder(conf, writerCacheConf, fs)
.withFilePath(path).withBloomType(bloomType)
.withMaxKeyCount(maxKeyCount).withFileContext(hFileContext).build();
return w;
}
/**
* Commits the mob file.
* @param conf The current configuration.
* @param fs The current file system.
* @param sourceFile The path where the mob file is saved.
* @param targetPath The directory path where the source file is renamed to.
* @param cacheConfig The current cache config.
* @return The target file path the source file is renamed to.
*/
public static Path commitFile(Configuration conf, FileSystem fs, final Path sourceFile,
Path targetPath, CacheConfig cacheConfig) throws IOException {
if (sourceFile == null) {
return null;
}
Path dstPath = new Path(targetPath, sourceFile.getName());
validateMobFile(conf, fs, sourceFile, cacheConfig, true);
String msg = "Renaming flushed file from " + sourceFile + " to " + dstPath;
LOG.info(msg);
Path parent = dstPath.getParent();
if (!fs.exists(parent)) {
fs.mkdirs(parent);
}
if (!fs.rename(sourceFile, dstPath)) {
throw new IOException("Failed rename of " + sourceFile + " to " + dstPath);
}
return dstPath;
}
/**
* Validates a mob file by opening and closing it.
* @param conf The current configuration.
* @param fs The current file system.
* @param path The path where the mob file is saved.
* @param cacheConfig The current cache config.
*/
private static void validateMobFile(Configuration conf, FileSystem fs, Path path,
CacheConfig cacheConfig, boolean primaryReplica) throws IOException {
HStoreFile storeFile = null;
try {
storeFile = new HStoreFile(fs, path, conf, cacheConfig, BloomType.NONE, primaryReplica);
storeFile.initReader();
} catch (IOException e) {
LOG.error("Failed to open mob file[" + path + "], keep it in temp directory.", e);
throw e;
} finally {
if (storeFile != null) {
storeFile.closeStoreFile(false);
}
}
}
/**
* Indicates whether the current mob ref cell has a valid value.
* A mob ref cell has a mob reference tag.
* The value of a mob ref cell consists of two parts, real mob value length and mob file name.
* The real mob value length takes 4 bytes.
* The remaining part is the mob file name.
* @param cell The mob ref cell.
* @return True if the cell has a valid value.
*/
public static boolean hasValidMobRefCellValue(Cell cell) {
return cell.getValueLength() > Bytes.SIZEOF_INT;
}
/**
* Gets the mob value length from the mob ref cell.
* A mob ref cell has a mob reference tag.
* The value of a mob ref cell consists of two parts, real mob value length and mob file name.
* The real mob value length takes 4 bytes.
* The remaining part is the mob file name.
* @param cell The mob ref cell.
* @return The real mob value length.
*/
public static int getMobValueLength(Cell cell) {
return PrivateCellUtil.getValueAsInt(cell);
}
/**
* Gets the mob file name from the mob ref cell.
* A mob ref cell has a mob reference tag.
* The value of a mob ref cell consists of two parts, real mob value length and mob file name.
* The real mob value length takes 4 bytes.
* The remaining part is the mob file name.
* @param cell The mob ref cell.
* @return The mob file name.
*/
public static String getMobFileName(Cell cell) {
return Bytes.toString(cell.getValueArray(), cell.getValueOffset() + Bytes.SIZEOF_INT,
cell.getValueLength() - Bytes.SIZEOF_INT);
}
/**
* Gets the table name used in the table lock.
* The table lock name is a dummy one, it's not a table name. It's tableName + ".mobLock".
* @param tn The table name.
* @return The table name used in table lock.
*/
public static TableName getTableLockName(TableName tn) {
byte[] tableName = tn.getName();
return TableName.valueOf(Bytes.add(tableName, MobConstants.MOB_TABLE_LOCK_SUFFIX));
}
/**
* Performs the mob compaction.
* @param conf the Configuration
* @param fs the file system
* @param tableName the table the compact
* @param hcd the column descriptor
* @param pool the thread pool
* @param allFiles Whether add all mob files into the compaction.
*/
public static void doMobCompaction(Configuration conf, FileSystem fs, TableName tableName,
ColumnFamilyDescriptor hcd, ExecutorService pool, boolean allFiles,
LockManager.MasterLock lock)
throws IOException {
String className = conf.get(MobConstants.MOB_COMPACTOR_CLASS_KEY,
PartitionedMobCompactor.class.getName());
// instantiate the mob compactor.
MobCompactor compactor = null;
try {
compactor = ReflectionUtils.instantiateWithCustomCtor(className, new Class[] {
Configuration.class, FileSystem.class, TableName.class, ColumnFamilyDescriptor.class,
ExecutorService.class }, new Object[] { conf, fs, tableName, hcd, pool });
} catch (Exception e) {
throw new IOException("Unable to load configured mob file compactor '" + className + "'", e);
}
// compact only for mob-enabled column.
// obtain a write table lock before performing compaction to avoid race condition
// with major compaction in mob-enabled column.
try {
lock.acquire();
LOG.info("start MOB compaction of files for table='{}', column='{}', allFiles={}, " +
"compactor='{}'", tableName, hcd.getNameAsString(), allFiles, compactor.getClass());
compactor.compact(allFiles);
} catch (Exception e) {
LOG.error("Failed to compact the mob files for the column " + hcd.getNameAsString()
+ " in the table " + tableName.getNameAsString(), e);
} finally {
LOG.info("end MOB compaction of files for table='{}', column='{}', allFiles={}, " +
"compactor='{}'", tableName, hcd.getNameAsString(), allFiles, compactor.getClass());
lock.release();
}
}
/**
* Creates a thread pool.
* @param conf the Configuration
* @return A thread pool.
*/
public static ExecutorService createMobCompactorThreadPool(Configuration conf) {
int maxThreads = conf.getInt(MobConstants.MOB_COMPACTION_THREADS_MAX,
MobConstants.DEFAULT_MOB_COMPACTION_THREADS_MAX);
// resets to default mob compaction thread number when the user sets this value incorrectly
if (maxThreads <= 0) {
maxThreads = 1;
}
final SynchronousQueue<Runnable> queue = new SynchronousQueue<>();
ThreadPoolExecutor pool = new ThreadPoolExecutor(1, maxThreads, 60, TimeUnit.SECONDS, queue,
new ThreadFactoryBuilder().setNameFormat("MobCompactor-pool-%d")
.setUncaughtExceptionHandler(Threads.LOGGING_EXCEPTION_HANDLER).build(), (r, executor) -> {
try {
// waiting for a thread to pick up instead of throwing exceptions.
queue.put(r);
} catch (InterruptedException e) {
throw new RejectedExecutionException(e);
}
});
pool.allowCoreThreadTimeOut(true);
return pool;
}
/**
* Checks whether this table has mob-enabled columns.
* @param htd The current table descriptor.
* @return Whether this table has mob-enabled columns.
*/
public static boolean hasMobColumns(TableDescriptor htd) {
ColumnFamilyDescriptor[] hcds = htd.getColumnFamilies();
for (ColumnFamilyDescriptor hcd : hcds) {
if (hcd.isMobEnabled()) {
return true;
}
}
return false;
}
/**
* Indicates whether return null value when the mob file is missing or corrupt.
* The information is set in the attribute "empty.value.on.mobcell.miss" of scan.
* @param scan The current scan.
* @return True if the readEmptyValueOnMobCellMiss is enabled.
*/
public static boolean isReadEmptyValueOnMobCellMiss(Scan scan) {
byte[] readEmptyValueOnMobCellMiss =
scan.getAttribute(MobConstants.EMPTY_VALUE_ON_MOBCELL_MISS);
try {
return readEmptyValueOnMobCellMiss != null && Bytes.toBoolean(readEmptyValueOnMobCellMiss);
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Creates a mob ref delete marker.
* @param cell The current delete marker.
* @return A delete marker with the ref tag.
*/
public static Cell createMobRefDeleteMarker(Cell cell) {
return PrivateCellUtil.createCell(cell, TagUtil.concatTags(REF_DELETE_MARKER_TAG_BYTES, cell));
}
/**
* Checks if the mob file is expired.
* @param column The descriptor of the current column family.
* @param current The current time.
* @param fileDate The date string parsed from the mob file name.
* @return True if the mob file is expired.
*/
public static boolean isMobFileExpired(ColumnFamilyDescriptor column, long current,
String fileDate) {
if (column.getMinVersions() > 0) {
return false;
}
long timeToLive = column.getTimeToLive();
if (Integer.MAX_VALUE == timeToLive) {
return false;
}
Date expireDate = new Date(current - timeToLive * 1000);
expireDate = new Date(expireDate.getYear(), expireDate.getMonth(), expireDate.getDate());
try {
Date date = parseDate(fileDate);
if (date.getTime() < expireDate.getTime()) {
return true;
}
} catch (ParseException e) {
LOG.warn("Failed to parse the date " + fileDate, e);
return false;
}
return false;
}
/**
* fill out partition id based on compaction policy and date, threshold...
* @param id Partition id to be filled out
* @param firstDayOfCurrentMonth The first day in the current month
* @param firstDayOfCurrentWeek The first day in the current week
* @param dateStr Date string from the mob file
* @param policy Mob compaction policy
* @param calendar Calendar object
* @param threshold Mob compaciton threshold configured
* @return true if the file needs to be excluded from compaction
*/
public static boolean fillPartitionId(final CompactionPartitionId id,
final Date firstDayOfCurrentMonth, final Date firstDayOfCurrentWeek, final String dateStr,
final MobCompactPartitionPolicy policy, final Calendar calendar, final long threshold) {
boolean skipCompcation = false;
id.setThreshold(threshold);
if (threshold <= 0) {
id.setDate(dateStr);
return skipCompcation;
}
long finalThreshold;
Date date;
try {
date = MobUtils.parseDate(dateStr);
} catch (ParseException e) {
LOG.warn("Failed to parse date " + dateStr, e);
id.setDate(dateStr);
return true;
}
/* The algorithm works as follows:
* For monthly policy:
* 1). If the file's date is in past months, apply 4 * 7 * threshold
* 2). If the file's date is in past weeks, apply 7 * threshold
* 3). If the file's date is in current week, exclude it from the compaction
* For weekly policy:
* 1). If the file's date is in past weeks, apply 7 * threshold
* 2). If the file's date in currently, apply threshold
* For daily policy:
* 1). apply threshold
*/
if (policy == MobCompactPartitionPolicy.MONTHLY) {
if (date.before(firstDayOfCurrentMonth)) {
// Check overflow
if (threshold < (Long.MAX_VALUE / MONTHLY_THRESHOLD_MULTIPLIER)) {
finalThreshold = MONTHLY_THRESHOLD_MULTIPLIER * threshold;
} else {
finalThreshold = Long.MAX_VALUE;
}
id.setThreshold(finalThreshold);
// set to the date for the first day of that month
id.setDate(MobUtils.formatDate(MobUtils.getFirstDayOfMonth(calendar, date)));
return skipCompcation;
}
}
if ((policy == MobCompactPartitionPolicy.MONTHLY) ||
(policy == MobCompactPartitionPolicy.WEEKLY)) {
// Check if it needs to apply weekly multiplier
if (date.before(firstDayOfCurrentWeek)) {
// Check overflow
if (threshold < (Long.MAX_VALUE / WEEKLY_THRESHOLD_MULTIPLIER)) {
finalThreshold = WEEKLY_THRESHOLD_MULTIPLIER * threshold;
} else {
finalThreshold = Long.MAX_VALUE;
}
id.setThreshold(finalThreshold);
id.setDate(MobUtils.formatDate(MobUtils.getFirstDayOfWeek(calendar, date)));
return skipCompcation;
} else if (policy == MobCompactPartitionPolicy.MONTHLY) {
skipCompcation = true;
}
}
// Rest is daily
id.setDate(dateStr);
return skipCompcation;
}
}
| hbase-server/src/main/java/org/apache/hadoop/hbase/mob/MobUtils.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.mob;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.PrivateCellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.Tag;
import org.apache.hadoop.hbase.TagType;
import org.apache.hadoop.hbase.TagUtil;
import org.apache.hadoop.hbase.backup.HFileArchiver;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
import org.apache.hadoop.hbase.client.MobCompactPartitionPolicy;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.RegionInfoBuilder;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.io.HFileLink;
import org.apache.hadoop.hbase.io.compress.Compression;
import org.apache.hadoop.hbase.io.crypto.Encryption;
import org.apache.hadoop.hbase.io.hfile.CacheConfig;
import org.apache.hadoop.hbase.io.hfile.HFile;
import org.apache.hadoop.hbase.io.hfile.HFileContext;
import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
import org.apache.hadoop.hbase.master.locking.LockManager;
import org.apache.hadoop.hbase.mob.compactions.MobCompactor;
import org.apache.hadoop.hbase.mob.compactions.PartitionedMobCompactionRequest.CompactionPartitionId;
import org.apache.hadoop.hbase.mob.compactions.PartitionedMobCompactor;
import org.apache.hadoop.hbase.regionserver.BloomType;
import org.apache.hadoop.hbase.regionserver.HStoreFile;
import org.apache.hadoop.hbase.regionserver.StoreFileWriter;
import org.apache.hadoop.hbase.regionserver.StoreUtils;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.ChecksumType;
import org.apache.hadoop.hbase.util.CommonFSUtils;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.ReflectionUtils;
import org.apache.hadoop.hbase.util.Threads;
import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.yetus.audience.InterfaceAudience;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The mob utilities
*/
@InterfaceAudience.Private
public final class MobUtils {
private static final Logger LOG = LoggerFactory.getLogger(MobUtils.class);
private final static long WEEKLY_THRESHOLD_MULTIPLIER = 7;
private final static long MONTHLY_THRESHOLD_MULTIPLIER = 4 * WEEKLY_THRESHOLD_MULTIPLIER;
private static final ThreadLocal<SimpleDateFormat> LOCAL_FORMAT =
new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyyMMdd");
}
};
private static final byte[] REF_DELETE_MARKER_TAG_BYTES;
static {
List<Tag> tags = new ArrayList<>();
tags.add(MobConstants.MOB_REF_TAG);
REF_DELETE_MARKER_TAG_BYTES = TagUtil.fromList(tags);
}
/**
* Private constructor to keep this class from being instantiated.
*/
private MobUtils() {
}
/**
* Formats a date to a string.
* @param date The date.
* @return The string format of the date, it's yyyymmdd.
*/
public static String formatDate(Date date) {
return LOCAL_FORMAT.get().format(date);
}
/**
* Parses the string to a date.
* @param dateString The string format of a date, it's yyyymmdd.
* @return A date.
*/
public static Date parseDate(String dateString) throws ParseException {
return LOCAL_FORMAT.get().parse(dateString);
}
/**
* Get the first day of the input date's month
* @param calendar Calendar object
* @param date The date to find out its first day of that month
* @return The first day in the month
*/
public static Date getFirstDayOfMonth(final Calendar calendar, final Date date) {
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date firstDayInMonth = calendar.getTime();
return firstDayInMonth;
}
/**
* Get the first day of the input date's week
* @param calendar Calendar object
* @param date The date to find out its first day of that week
* @return The first day in the week
*/
public static Date getFirstDayOfWeek(final Calendar calendar, final Date date) {
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
Date firstDayInWeek = calendar.getTime();
return firstDayInWeek;
}
/**
* Whether the current cell is a mob reference cell.
* @param cell The current cell.
* @return True if the cell has a mob reference tag, false if it doesn't.
*/
public static boolean isMobReferenceCell(Cell cell) {
if (cell.getTagsLength() > 0) {
Optional<Tag> tag = PrivateCellUtil.getTag(cell, TagType.MOB_REFERENCE_TAG_TYPE);
if (tag.isPresent()) {
return true;
}
}
return false;
}
/**
* Gets the table name tag.
* @param cell The current cell.
* @return The table name tag.
*/
public static Tag getTableNameTag(Cell cell) {
if (cell.getTagsLength() > 0) {
Optional<Tag> tag = PrivateCellUtil.getTag(cell, TagType.MOB_TABLE_NAME_TAG_TYPE);
if (tag.isPresent()) {
return tag.get();
}
}
return null;
}
/**
* Whether the tag list has a mob reference tag.
* @param tags The tag list.
* @return True if the list has a mob reference tag, false if it doesn't.
*/
public static boolean hasMobReferenceTag(List<Tag> tags) {
if (!tags.isEmpty()) {
for (Tag tag : tags) {
if (tag.getType() == TagType.MOB_REFERENCE_TAG_TYPE) {
return true;
}
}
}
return false;
}
/**
* Indicates whether it's a raw scan.
* The information is set in the attribute "hbase.mob.scan.raw" of scan.
* For a mob cell, in a normal scan the scanners retrieves the mob cell from the mob file.
* In a raw scan, the scanner directly returns cell in HBase without retrieve the one in
* the mob file.
* @param scan The current scan.
* @return True if it's a raw scan.
*/
public static boolean isRawMobScan(Scan scan) {
byte[] raw = scan.getAttribute(MobConstants.MOB_SCAN_RAW);
try {
return raw != null && Bytes.toBoolean(raw);
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Indicates whether it's a reference only scan.
* The information is set in the attribute "hbase.mob.scan.ref.only" of scan.
* If it's a ref only scan, only the cells with ref tag are returned.
* @param scan The current scan.
* @return True if it's a ref only scan.
*/
public static boolean isRefOnlyScan(Scan scan) {
byte[] refOnly = scan.getAttribute(MobConstants.MOB_SCAN_REF_ONLY);
try {
return refOnly != null && Bytes.toBoolean(refOnly);
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Indicates whether the scan contains the information of caching blocks.
* The information is set in the attribute "hbase.mob.cache.blocks" of scan.
* @param scan The current scan.
* @return True when the Scan attribute specifies to cache the MOB blocks.
*/
public static boolean isCacheMobBlocks(Scan scan) {
byte[] cache = scan.getAttribute(MobConstants.MOB_CACHE_BLOCKS);
try {
return cache != null && Bytes.toBoolean(cache);
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Sets the attribute of caching blocks in the scan.
*
* @param scan
* The current scan.
* @param cacheBlocks
* True, set the attribute of caching blocks into the scan, the scanner with this scan
* caches blocks.
* False, the scanner doesn't cache blocks for this scan.
*/
public static void setCacheMobBlocks(Scan scan, boolean cacheBlocks) {
scan.setAttribute(MobConstants.MOB_CACHE_BLOCKS, Bytes.toBytes(cacheBlocks));
}
/**
* Cleans the expired mob files.
* Cleans the files whose creation date is older than (current - columnFamily.ttl), and
* the minVersions of that column family is 0.
* @param fs The current file system.
* @param conf The current configuration.
* @param tableName The current table name.
* @param columnDescriptor The descriptor of the current column family.
* @param cacheConfig The cacheConfig that disables the block cache.
* @param current The current time.
*/
public static void cleanExpiredMobFiles(FileSystem fs, Configuration conf, TableName tableName,
ColumnFamilyDescriptor columnDescriptor, CacheConfig cacheConfig, long current)
throws IOException {
long timeToLive = columnDescriptor.getTimeToLive();
if (Integer.MAX_VALUE == timeToLive) {
// no need to clean, because the TTL is not set.
return;
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(current - timeToLive * 1000);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date expireDate = calendar.getTime();
LOG.info("MOB HFiles older than " + expireDate.toGMTString() + " will be deleted!");
FileStatus[] stats = null;
Path mobTableDir = CommonFSUtils.getTableDir(getMobHome(conf), tableName);
Path path = getMobFamilyPath(conf, tableName, columnDescriptor.getNameAsString());
try {
stats = fs.listStatus(path);
} catch (FileNotFoundException e) {
LOG.warn("Failed to find the mob file " + path, e);
}
if (null == stats) {
// no file found
return;
}
List<HStoreFile> filesToClean = new ArrayList<>();
int deletedFileCount = 0;
for (FileStatus file : stats) {
String fileName = file.getPath().getName();
try {
if (HFileLink.isHFileLink(file.getPath())) {
HFileLink hfileLink = HFileLink.buildFromHFileLinkPattern(conf, file.getPath());
fileName = hfileLink.getOriginPath().getName();
}
Date fileDate = parseDate(MobFileName.getDateFromName(fileName));
if (LOG.isDebugEnabled()) {
LOG.debug("Checking file " + fileName);
}
if (fileDate.getTime() < expireDate.getTime()) {
if (LOG.isDebugEnabled()) {
LOG.debug(fileName + " is an expired file");
}
filesToClean
.add(new HStoreFile(fs, file.getPath(), conf, cacheConfig, BloomType.NONE, true));
}
} catch (Exception e) {
LOG.error("Cannot parse the fileName " + fileName, e);
}
}
if (!filesToClean.isEmpty()) {
try {
removeMobFiles(conf, fs, tableName, mobTableDir, columnDescriptor.getName(),
filesToClean);
deletedFileCount = filesToClean.size();
} catch (IOException e) {
LOG.error("Failed to delete the mob files " + filesToClean, e);
}
}
LOG.info(deletedFileCount + " expired mob files are deleted");
}
/**
* Gets the root dir of the mob files.
* It's {HBASE_DIR}/mobdir.
* @param conf The current configuration.
* @return the root dir of the mob file.
*/
public static Path getMobHome(Configuration conf) {
Path hbaseDir = new Path(conf.get(HConstants.HBASE_DIR));
return getMobHome(hbaseDir);
}
/**
* Gets the root dir of the mob files under the qualified HBase root dir.
* It's {rootDir}/mobdir.
* @param rootDir The qualified path of HBase root directory.
* @return The root dir of the mob file.
*/
public static Path getMobHome(Path rootDir) {
return new Path(rootDir, MobConstants.MOB_DIR_NAME);
}
/**
* Gets the qualified root dir of the mob files.
* @param conf The current configuration.
* @return The qualified root dir.
*/
public static Path getQualifiedMobRootDir(Configuration conf) throws IOException {
Path hbaseDir = new Path(conf.get(HConstants.HBASE_DIR));
Path mobRootDir = new Path(hbaseDir, MobConstants.MOB_DIR_NAME);
FileSystem fs = mobRootDir.getFileSystem(conf);
return mobRootDir.makeQualified(fs.getUri(), fs.getWorkingDirectory());
}
/**
* Gets the table dir of the mob files under the qualified HBase root dir.
* It's {rootDir}/mobdir/data/${namespace}/${tableName}
* @param rootDir The qualified path of HBase root directory.
* @param tableName The name of table.
* @return The table dir of the mob file.
*/
public static Path getMobTableDir(Path rootDir, TableName tableName) {
return CommonFSUtils.getTableDir(getMobHome(rootDir), tableName);
}
/**
* Gets the region dir of the mob files.
* It's {HBASE_DIR}/mobdir/data/{namespace}/{tableName}/{regionEncodedName}.
* @param conf The current configuration.
* @param tableName The current table name.
* @return The region dir of the mob files.
*/
public static Path getMobRegionPath(Configuration conf, TableName tableName) {
return getMobRegionPath(new Path(conf.get(HConstants.HBASE_DIR)), tableName);
}
/**
* Gets the region dir of the mob files under the specified root dir.
* It's {rootDir}/mobdir/data/{namespace}/{tableName}/{regionEncodedName}.
* @param rootDir The qualified path of HBase root directory.
* @param tableName The current table name.
* @return The region dir of the mob files.
*/
public static Path getMobRegionPath(Path rootDir, TableName tableName) {
Path tablePath = CommonFSUtils.getTableDir(getMobHome(rootDir), tableName);
RegionInfo regionInfo = getMobRegionInfo(tableName);
return new Path(tablePath, regionInfo.getEncodedName());
}
/**
* Gets the family dir of the mob files.
* It's {HBASE_DIR}/mobdir/{namespace}/{tableName}/{regionEncodedName}/{columnFamilyName}.
* @param conf The current configuration.
* @param tableName The current table name.
* @param familyName The current family name.
* @return The family dir of the mob files.
*/
public static Path getMobFamilyPath(Configuration conf, TableName tableName, String familyName) {
return new Path(getMobRegionPath(conf, tableName), familyName);
}
/**
* Gets the family dir of the mob files.
* It's {HBASE_DIR}/mobdir/{namespace}/{tableName}/{regionEncodedName}/{columnFamilyName}.
* @param regionPath The path of mob region which is a dummy one.
* @param familyName The current family name.
* @return The family dir of the mob files.
*/
public static Path getMobFamilyPath(Path regionPath, String familyName) {
return new Path(regionPath, familyName);
}
/**
* Gets the RegionInfo of the mob files.
* This is a dummy region. The mob files are not saved in a region in HBase.
* This is only used in mob snapshot. It's internally used only.
* @param tableName
* @return A dummy mob region info.
*/
public static RegionInfo getMobRegionInfo(TableName tableName) {
return RegionInfoBuilder.newBuilder(tableName)
.setStartKey(MobConstants.MOB_REGION_NAME_BYTES)
.setEndKey(HConstants.EMPTY_END_ROW)
.setSplit(false)
.setRegionId(0)
.build();
}
/**
* Gets whether the current RegionInfo is a mob one.
* @param regionInfo The current RegionInfo.
* @return If true, the current RegionInfo is a mob one.
*/
public static boolean isMobRegionInfo(RegionInfo regionInfo) {
return regionInfo == null ? false : getMobRegionInfo(regionInfo.getTable()).getEncodedName()
.equals(regionInfo.getEncodedName());
}
/**
* Gets whether the current region name follows the pattern of a mob region name.
* @param tableName The current table name.
* @param regionName The current region name.
* @return True if the current region name follows the pattern of a mob region name.
*/
public static boolean isMobRegionName(TableName tableName, byte[] regionName) {
return Bytes.equals(regionName, getMobRegionInfo(tableName).getRegionName());
}
/**
* Gets the working directory of the mob compaction.
* @param root The root directory of the mob compaction.
* @param jobName The current job name.
* @return The directory of the mob compaction for the current job.
*/
public static Path getCompactionWorkingPath(Path root, String jobName) {
return new Path(root, jobName);
}
/**
* Archives the mob files.
* @param conf The current configuration.
* @param fs The current file system.
* @param tableName The table name.
* @param tableDir The table directory.
* @param family The name of the column family.
* @param storeFiles The files to be deleted.
*/
public static void removeMobFiles(Configuration conf, FileSystem fs, TableName tableName,
Path tableDir, byte[] family, Collection<HStoreFile> storeFiles) throws IOException {
HFileArchiver.archiveStoreFiles(conf, fs, getMobRegionInfo(tableName), tableDir, family,
storeFiles);
}
/**
* Creates a mob reference KeyValue.
* The value of the mob reference KeyValue is mobCellValueSize + mobFileName.
* @param cell The original Cell.
* @param fileName The mob file name where the mob reference KeyValue is written.
* @param tableNameTag The tag of the current table name. It's very important in
* cloning the snapshot.
* @return The mob reference KeyValue.
*/
public static Cell createMobRefCell(Cell cell, byte[] fileName, Tag tableNameTag) {
// Append the tags to the KeyValue.
// The key is same, the value is the filename of the mob file
List<Tag> tags = new ArrayList<>();
// Add the ref tag as the 1st one.
tags.add(MobConstants.MOB_REF_TAG);
// Add the tag of the source table name, this table is where this mob file is flushed
// from.
// It's very useful in cloning the snapshot. When reading from the cloning table, we need to
// find the original mob files by this table name. For details please see cloning
// snapshot for mob files.
tags.add(tableNameTag);
return createMobRefCell(cell, fileName, TagUtil.fromList(tags));
}
public static Cell createMobRefCell(Cell cell, byte[] fileName, byte[] refCellTags) {
byte[] refValue = Bytes.add(Bytes.toBytes(cell.getValueLength()), fileName);
return PrivateCellUtil.createCell(cell, refValue, TagUtil.concatTags(refCellTags, cell));
}
/**
* Creates a writer for the mob file in temp directory.
* @param conf The current configuration.
* @param fs The current file system.
* @param family The descriptor of the current column family.
* @param date The date string, its format is yyyymmmdd.
* @param basePath The basic path for a temp directory.
* @param maxKeyCount The key count.
* @param compression The compression algorithm.
* @param startKey The hex string of the start key.
* @param cacheConfig The current cache config.
* @param cryptoContext The encryption context.
* @param isCompaction If the writer is used in compaction.
* @return The writer for the mob file.
*/
public static StoreFileWriter createWriter(Configuration conf, FileSystem fs,
ColumnFamilyDescriptor family, String date, Path basePath, long maxKeyCount,
Compression.Algorithm compression, String startKey, CacheConfig cacheConfig,
Encryption.Context cryptoContext, boolean isCompaction)
throws IOException {
MobFileName mobFileName = MobFileName.create(startKey, date,
UUID.randomUUID().toString().replaceAll("-", ""));
return createWriter(conf, fs, family, mobFileName, basePath, maxKeyCount, compression,
cacheConfig, cryptoContext, isCompaction);
}
/**
* Creates a writer for the ref file in temp directory.
* @param conf The current configuration.
* @param fs The current file system.
* @param family The descriptor of the current column family.
* @param basePath The basic path for a temp directory.
* @param maxKeyCount The key count.
* @param cacheConfig The current cache config.
* @param cryptoContext The encryption context.
* @param isCompaction If the writer is used in compaction.
* @return The writer for the mob file.
*/
public static StoreFileWriter createRefFileWriter(Configuration conf, FileSystem fs,
ColumnFamilyDescriptor family, Path basePath, long maxKeyCount, CacheConfig cacheConfig,
Encryption.Context cryptoContext, boolean isCompaction)
throws IOException {
return createWriter(conf, fs, family,
new Path(basePath, UUID.randomUUID().toString().replaceAll("-", "")), maxKeyCount,
family.getCompactionCompressionType(), cacheConfig, cryptoContext,
StoreUtils.getChecksumType(conf), StoreUtils.getBytesPerChecksum(conf), family.getBlocksize(),
family.getBloomFilterType(), isCompaction);
}
/**
* Creates a writer for the mob file in temp directory.
* @param conf The current configuration.
* @param fs The current file system.
* @param family The descriptor of the current column family.
* @param date The date string, its format is yyyymmmdd.
* @param basePath The basic path for a temp directory.
* @param maxKeyCount The key count.
* @param compression The compression algorithm.
* @param startKey The start key.
* @param cacheConfig The current cache config.
* @param cryptoContext The encryption context.
* @param isCompaction If the writer is used in compaction.
* @return The writer for the mob file.
*/
public static StoreFileWriter createWriter(Configuration conf, FileSystem fs,
ColumnFamilyDescriptor family, String date, Path basePath, long maxKeyCount,
Compression.Algorithm compression, byte[] startKey, CacheConfig cacheConfig,
Encryption.Context cryptoContext, boolean isCompaction)
throws IOException {
MobFileName mobFileName = MobFileName.create(startKey, date,
UUID.randomUUID().toString().replaceAll("-", ""));
return createWriter(conf, fs, family, mobFileName, basePath, maxKeyCount, compression,
cacheConfig, cryptoContext, isCompaction);
}
/**
* Creates a writer for the del file in temp directory.
* @param conf The current configuration.
* @param fs The current file system.
* @param family The descriptor of the current column family.
* @param date The date string, its format is yyyymmmdd.
* @param basePath The basic path for a temp directory.
* @param maxKeyCount The key count.
* @param compression The compression algorithm.
* @param startKey The start key.
* @param cacheConfig The current cache config.
* @param cryptoContext The encryption context.
* @return The writer for the del file.
*/
public static StoreFileWriter createDelFileWriter(Configuration conf, FileSystem fs,
ColumnFamilyDescriptor family, String date, Path basePath, long maxKeyCount,
Compression.Algorithm compression, byte[] startKey, CacheConfig cacheConfig,
Encryption.Context cryptoContext)
throws IOException {
String suffix = UUID
.randomUUID().toString().replaceAll("-", "") + "_del";
MobFileName mobFileName = MobFileName.create(startKey, date, suffix);
return createWriter(conf, fs, family, mobFileName, basePath, maxKeyCount, compression,
cacheConfig, cryptoContext, true);
}
/**
* Creates a writer for the mob file in temp directory.
* @param conf The current configuration.
* @param fs The current file system.
* @param family The descriptor of the current column family.
* @param mobFileName The mob file name.
* @param basePath The basic path for a temp directory.
* @param maxKeyCount The key count.
* @param compression The compression algorithm.
* @param cacheConfig The current cache config.
* @param cryptoContext The encryption context.
* @param isCompaction If the writer is used in compaction.
* @return The writer for the mob file.
*/
public static StoreFileWriter createWriter(Configuration conf, FileSystem fs,
ColumnFamilyDescriptor family, MobFileName mobFileName, Path basePath, long maxKeyCount,
Compression.Algorithm compression, CacheConfig cacheConfig, Encryption.Context cryptoContext,
boolean isCompaction)
throws IOException {
return createWriter(conf, fs, family,
new Path(basePath, mobFileName.getFileName()), maxKeyCount, compression, cacheConfig,
cryptoContext, StoreUtils.getChecksumType(conf), StoreUtils.getBytesPerChecksum(conf),
family.getBlocksize(), BloomType.NONE, isCompaction);
}
/**
* Creates a writer for the mob file in temp directory.
* @param conf The current configuration.
* @param fs The current file system.
* @param family The descriptor of the current column family.
* @param path The path for a temp directory.
* @param maxKeyCount The key count.
* @param compression The compression algorithm.
* @param cacheConfig The current cache config.
* @param cryptoContext The encryption context.
* @param checksumType The checksum type.
* @param bytesPerChecksum The bytes per checksum.
* @param blocksize The HFile block size.
* @param bloomType The bloom filter type.
* @param isCompaction If the writer is used in compaction.
* @return The writer for the mob file.
*/
public static StoreFileWriter createWriter(Configuration conf, FileSystem fs,
ColumnFamilyDescriptor family, Path path, long maxKeyCount,
Compression.Algorithm compression, CacheConfig cacheConfig, Encryption.Context cryptoContext,
ChecksumType checksumType, int bytesPerChecksum, int blocksize, BloomType bloomType,
boolean isCompaction)
throws IOException {
if (compression == null) {
compression = HFile.DEFAULT_COMPRESSION_ALGORITHM;
}
final CacheConfig writerCacheConf;
if (isCompaction) {
writerCacheConf = new CacheConfig(cacheConfig);
writerCacheConf.setCacheDataOnWrite(false);
} else {
writerCacheConf = cacheConfig;
}
HFileContext hFileContext = new HFileContextBuilder().withCompression(compression)
.withIncludesMvcc(true).withIncludesTags(true)
.withCompressTags(family.isCompressTags())
.withChecksumType(checksumType)
.withBytesPerCheckSum(bytesPerChecksum)
.withBlockSize(blocksize)
.withHBaseCheckSum(true).withDataBlockEncoding(family.getDataBlockEncoding())
.withEncryptionContext(cryptoContext)
.withCreateTime(EnvironmentEdgeManager.currentTime()).build();
StoreFileWriter w = new StoreFileWriter.Builder(conf, writerCacheConf, fs)
.withFilePath(path).withBloomType(bloomType)
.withMaxKeyCount(maxKeyCount).withFileContext(hFileContext).build();
return w;
}
/**
* Commits the mob file.
* @param conf The current configuration.
* @param fs The current file system.
* @param sourceFile The path where the mob file is saved.
* @param targetPath The directory path where the source file is renamed to.
* @param cacheConfig The current cache config.
* @return The target file path the source file is renamed to.
*/
public static Path commitFile(Configuration conf, FileSystem fs, final Path sourceFile,
Path targetPath, CacheConfig cacheConfig) throws IOException {
if (sourceFile == null) {
return null;
}
Path dstPath = new Path(targetPath, sourceFile.getName());
validateMobFile(conf, fs, sourceFile, cacheConfig, true);
String msg = "Renaming flushed file from " + sourceFile + " to " + dstPath;
LOG.info(msg);
Path parent = dstPath.getParent();
if (!fs.exists(parent)) {
fs.mkdirs(parent);
}
if (!fs.rename(sourceFile, dstPath)) {
throw new IOException("Failed rename of " + sourceFile + " to " + dstPath);
}
return dstPath;
}
/**
* Validates a mob file by opening and closing it.
* @param conf The current configuration.
* @param fs The current file system.
* @param path The path where the mob file is saved.
* @param cacheConfig The current cache config.
*/
private static void validateMobFile(Configuration conf, FileSystem fs, Path path,
CacheConfig cacheConfig, boolean primaryReplica) throws IOException {
HStoreFile storeFile = null;
try {
storeFile = new HStoreFile(fs, path, conf, cacheConfig, BloomType.NONE, primaryReplica);
storeFile.initReader();
} catch (IOException e) {
LOG.error("Failed to open mob file[" + path + "], keep it in temp directory.", e);
throw e;
} finally {
if (storeFile != null) {
storeFile.closeStoreFile(false);
}
}
}
/**
* Indicates whether the current mob ref cell has a valid value.
* A mob ref cell has a mob reference tag.
* The value of a mob ref cell consists of two parts, real mob value length and mob file name.
* The real mob value length takes 4 bytes.
* The remaining part is the mob file name.
* @param cell The mob ref cell.
* @return True if the cell has a valid value.
*/
public static boolean hasValidMobRefCellValue(Cell cell) {
return cell.getValueLength() > Bytes.SIZEOF_INT;
}
/**
* Gets the mob value length from the mob ref cell.
* A mob ref cell has a mob reference tag.
* The value of a mob ref cell consists of two parts, real mob value length and mob file name.
* The real mob value length takes 4 bytes.
* The remaining part is the mob file name.
* @param cell The mob ref cell.
* @return The real mob value length.
*/
public static int getMobValueLength(Cell cell) {
return PrivateCellUtil.getValueAsInt(cell);
}
/**
* Gets the mob file name from the mob ref cell.
* A mob ref cell has a mob reference tag.
* The value of a mob ref cell consists of two parts, real mob value length and mob file name.
* The real mob value length takes 4 bytes.
* The remaining part is the mob file name.
* @param cell The mob ref cell.
* @return The mob file name.
*/
public static String getMobFileName(Cell cell) {
return Bytes.toString(cell.getValueArray(), cell.getValueOffset() + Bytes.SIZEOF_INT,
cell.getValueLength() - Bytes.SIZEOF_INT);
}
/**
* Gets the table name used in the table lock.
* The table lock name is a dummy one, it's not a table name. It's tableName + ".mobLock".
* @param tn The table name.
* @return The table name used in table lock.
*/
public static TableName getTableLockName(TableName tn) {
byte[] tableName = tn.getName();
return TableName.valueOf(Bytes.add(tableName, MobConstants.MOB_TABLE_LOCK_SUFFIX));
}
/**
* Performs the mob compaction.
* @param conf the Configuration
* @param fs the file system
* @param tableName the table the compact
* @param hcd the column descriptor
* @param pool the thread pool
* @param allFiles Whether add all mob files into the compaction.
*/
public static void doMobCompaction(Configuration conf, FileSystem fs, TableName tableName,
ColumnFamilyDescriptor hcd, ExecutorService pool, boolean allFiles,
LockManager.MasterLock lock)
throws IOException {
String className = conf.get(MobConstants.MOB_COMPACTOR_CLASS_KEY,
PartitionedMobCompactor.class.getName());
// instantiate the mob compactor.
MobCompactor compactor = null;
try {
compactor = ReflectionUtils.instantiateWithCustomCtor(className, new Class[] {
Configuration.class, FileSystem.class, TableName.class, ColumnFamilyDescriptor.class,
ExecutorService.class }, new Object[] { conf, fs, tableName, hcd, pool });
} catch (Exception e) {
throw new IOException("Unable to load configured mob file compactor '" + className + "'", e);
}
// compact only for mob-enabled column.
// obtain a write table lock before performing compaction to avoid race condition
// with major compaction in mob-enabled column.
try {
lock.acquire();
LOG.info("start MOB compaction of files for table='{}', column='{}', allFiles={}, " +
"compactor='{}'", tableName, hcd.getNameAsString(), allFiles, compactor.getClass());
compactor.compact(allFiles);
} catch (Exception e) {
LOG.error("Failed to compact the mob files for the column " + hcd.getNameAsString()
+ " in the table " + tableName.getNameAsString(), e);
} finally {
LOG.info("end MOB compaction of files for table='{}', column='{}', allFiles={}, " +
"compactor='{}'", tableName, hcd.getNameAsString(), allFiles, compactor.getClass());
lock.release();
}
}
/**
* Creates a thread pool.
* @param conf the Configuration
* @return A thread pool.
*/
public static ExecutorService createMobCompactorThreadPool(Configuration conf) {
int maxThreads = conf.getInt(MobConstants.MOB_COMPACTION_THREADS_MAX,
MobConstants.DEFAULT_MOB_COMPACTION_THREADS_MAX);
if (maxThreads == 0) {
maxThreads = 1;
}
final SynchronousQueue<Runnable> queue = new SynchronousQueue<>();
ThreadPoolExecutor pool = new ThreadPoolExecutor(1, maxThreads, 60, TimeUnit.SECONDS, queue,
new ThreadFactoryBuilder().setNameFormat("MobCompactor-pool-%d")
.setUncaughtExceptionHandler(Threads.LOGGING_EXCEPTION_HANDLER).build(), (r, executor) -> {
try {
// waiting for a thread to pick up instead of throwing exceptions.
queue.put(r);
} catch (InterruptedException e) {
throw new RejectedExecutionException(e);
}
});
pool.allowCoreThreadTimeOut(true);
return pool;
}
/**
* Checks whether this table has mob-enabled columns.
* @param htd The current table descriptor.
* @return Whether this table has mob-enabled columns.
*/
public static boolean hasMobColumns(TableDescriptor htd) {
ColumnFamilyDescriptor[] hcds = htd.getColumnFamilies();
for (ColumnFamilyDescriptor hcd : hcds) {
if (hcd.isMobEnabled()) {
return true;
}
}
return false;
}
/**
* Indicates whether return null value when the mob file is missing or corrupt.
* The information is set in the attribute "empty.value.on.mobcell.miss" of scan.
* @param scan The current scan.
* @return True if the readEmptyValueOnMobCellMiss is enabled.
*/
public static boolean isReadEmptyValueOnMobCellMiss(Scan scan) {
byte[] readEmptyValueOnMobCellMiss =
scan.getAttribute(MobConstants.EMPTY_VALUE_ON_MOBCELL_MISS);
try {
return readEmptyValueOnMobCellMiss != null && Bytes.toBoolean(readEmptyValueOnMobCellMiss);
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Creates a mob ref delete marker.
* @param cell The current delete marker.
* @return A delete marker with the ref tag.
*/
public static Cell createMobRefDeleteMarker(Cell cell) {
return PrivateCellUtil.createCell(cell, TagUtil.concatTags(REF_DELETE_MARKER_TAG_BYTES, cell));
}
/**
* Checks if the mob file is expired.
* @param column The descriptor of the current column family.
* @param current The current time.
* @param fileDate The date string parsed from the mob file name.
* @return True if the mob file is expired.
*/
public static boolean isMobFileExpired(ColumnFamilyDescriptor column, long current,
String fileDate) {
if (column.getMinVersions() > 0) {
return false;
}
long timeToLive = column.getTimeToLive();
if (Integer.MAX_VALUE == timeToLive) {
return false;
}
Date expireDate = new Date(current - timeToLive * 1000);
expireDate = new Date(expireDate.getYear(), expireDate.getMonth(), expireDate.getDate());
try {
Date date = parseDate(fileDate);
if (date.getTime() < expireDate.getTime()) {
return true;
}
} catch (ParseException e) {
LOG.warn("Failed to parse the date " + fileDate, e);
return false;
}
return false;
}
/**
* fill out partition id based on compaction policy and date, threshold...
* @param id Partition id to be filled out
* @param firstDayOfCurrentMonth The first day in the current month
* @param firstDayOfCurrentWeek The first day in the current week
* @param dateStr Date string from the mob file
* @param policy Mob compaction policy
* @param calendar Calendar object
* @param threshold Mob compaciton threshold configured
* @return true if the file needs to be excluded from compaction
*/
public static boolean fillPartitionId(final CompactionPartitionId id,
final Date firstDayOfCurrentMonth, final Date firstDayOfCurrentWeek, final String dateStr,
final MobCompactPartitionPolicy policy, final Calendar calendar, final long threshold) {
boolean skipCompcation = false;
id.setThreshold(threshold);
if (threshold <= 0) {
id.setDate(dateStr);
return skipCompcation;
}
long finalThreshold;
Date date;
try {
date = MobUtils.parseDate(dateStr);
} catch (ParseException e) {
LOG.warn("Failed to parse date " + dateStr, e);
id.setDate(dateStr);
return true;
}
/* The algorithm works as follows:
* For monthly policy:
* 1). If the file's date is in past months, apply 4 * 7 * threshold
* 2). If the file's date is in past weeks, apply 7 * threshold
* 3). If the file's date is in current week, exclude it from the compaction
* For weekly policy:
* 1). If the file's date is in past weeks, apply 7 * threshold
* 2). If the file's date in currently, apply threshold
* For daily policy:
* 1). apply threshold
*/
if (policy == MobCompactPartitionPolicy.MONTHLY) {
if (date.before(firstDayOfCurrentMonth)) {
// Check overflow
if (threshold < (Long.MAX_VALUE / MONTHLY_THRESHOLD_MULTIPLIER)) {
finalThreshold = MONTHLY_THRESHOLD_MULTIPLIER * threshold;
} else {
finalThreshold = Long.MAX_VALUE;
}
id.setThreshold(finalThreshold);
// set to the date for the first day of that month
id.setDate(MobUtils.formatDate(MobUtils.getFirstDayOfMonth(calendar, date)));
return skipCompcation;
}
}
if ((policy == MobCompactPartitionPolicy.MONTHLY) ||
(policy == MobCompactPartitionPolicy.WEEKLY)) {
// Check if it needs to apply weekly multiplier
if (date.before(firstDayOfCurrentWeek)) {
// Check overflow
if (threshold < (Long.MAX_VALUE / WEEKLY_THRESHOLD_MULTIPLIER)) {
finalThreshold = WEEKLY_THRESHOLD_MULTIPLIER * threshold;
} else {
finalThreshold = Long.MAX_VALUE;
}
id.setThreshold(finalThreshold);
id.setDate(MobUtils.formatDate(MobUtils.getFirstDayOfWeek(calendar, date)));
return skipCompcation;
} else if (policy == MobCompactPartitionPolicy.MONTHLY) {
skipCompcation = true;
}
}
// Rest is daily
id.setDate(dateStr);
return skipCompcation;
}
}
| HBASE-26114 when “hbase.mob.compaction.threads.max” is set to a negative number, HMaster cannot start normally (#3541)
Signed-off-by: Anoop <[email protected]> | hbase-server/src/main/java/org/apache/hadoop/hbase/mob/MobUtils.java | HBASE-26114 when “hbase.mob.compaction.threads.max” is set to a negative number, HMaster cannot start normally (#3541) |
|
Java | apache-2.0 | 0574bc80973a949947e020416df3b69bee0ffffd | 0 | vadmeste/minio-java,minio/minio-java,balamurugana/minio-java | /*
* Minio Java Library for Amazon S3 Compatible Cloud Storage, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.minio;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.google.gson.Gson;
import com.squareup.okhttp.mockwebserver.MockResponse;
import okio.Buffer;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import io.minio.messages.ErrorResponse;
import io.minio.messages.Item;
import io.minio.messages.Owner;
import org.junit.Assert;
import org.junit.Test;
import org.xmlpull.v1.XmlPullParserException;
import java.nio.charset.StandardCharsets;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import static org.junit.Assert.assertEquals;
@SuppressWarnings("unused")
public class MinioClientTest {
private static final String EXPECTED_EXCEPTION_DID_NOT_FIRE = "Expected exception did not fire";
private static final String BUCKET = "bucket";
private static final String CONTENT_LENGTH = "Content-Length";
private static final String APPLICATION_OCTET_STREAM = "application/octet-stream";
private static final String CONTENT_TYPE = "Content-Type";
private static final String MON_04_MAY_2015_07_58_51_GMT = "Mon, 04 May 2015 07:58:51 GMT";
private static final String LAST_MODIFIED = "Last-Modified";
private static final String HELLO_WORLD = "hello world";
private static final String HELLO = "hello";
private static final String BYTES = "bytes";
private static final String ACCEPT_RANGES = "Accept-Ranges";
private static final String CONTENT_RANGE = "Content-Range";
private static final String SUN_29_JUN_2015_22_01_10_GMT = "Sun, 29 Jun 2015 22:01:10 GMT";
private static final String MON_04_MAY_2015_07_58_51_UTC = "Mon, 04 May 2015 07:58:51 UTC";
private static final String BUCKET_KEY = "/bucket/key";
private static final String MD5_HASH_STRING = "\"5eb63bbbe01eeed093cb22bb8f5acdc3\"";
private static final Gson gson = new Gson();
@Test()
public void setUserAgentOnceSet() throws IOException, MinioException {
String expectedHost = "example.com";
MinioClient client = new MinioClient("http://" + expectedHost + "/");
client.setAppInfo("testApp", "2.0.1");
}
@Test(expected = MinioException.class)
public void newClientWithPathFails() throws MinioException {
new MinioClient("http://example.com/path");
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test(expected = NullPointerException.class)
public void newClientWithNullUrlFails() throws NullPointerException, MinioException {
URL url = null;
new MinioClient(url);
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test(expected = MinioException.class)
public void newClientWithNullStringFails() throws InvalidArgumentException, MinioException {
String url = null;
new MinioClient(url);
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test(expected = ErrorResponseException.class)
public void testForbidden()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(403));
server.start();
MinioClient client = new MinioClient(server.url(""));
client.statObject(BUCKET, "key");
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test(expected = ErrorResponseException.class)
public void getMissingObjectHeaders()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(404));
server.start();
MinioClient client = new MinioClient(server.url(""));
client.statObject(BUCKET, "key");
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test
public void testGetObjectHeaders()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.setResponseCode(200);
response.setHeader("Date", "Sun, 05 Jun 2015 22:01:10 GMT");
response.setHeader(CONTENT_LENGTH, "5080");
response.setHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.setHeader("ETag", "\"a670520d9d36833b3e28d1e4b73cbe22\"");
response.setHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT);
server.enqueue(response);
server.start();
// build expected request
Calendar expectedDate = Calendar.getInstance();
expectedDate.clear();
expectedDate.setTimeZone(TimeZone.getTimeZone("GMT"));
expectedDate.set(2015, Calendar.MAY, 4, 7, 58, 51);
ObjectStat expectedStatInfo = new ObjectStat(BUCKET, "key",
expectedDate.getTime(),
5080,
"a670520d9d36833b3e28d1e4b73cbe22",
APPLICATION_OCTET_STREAM);
// get request
MinioClient client = new MinioClient(server.url(""));
ObjectStat objectStatInfo = client.statObject(BUCKET, "key");
assertEquals(expectedStatInfo, objectStatInfo);
}
@Test(expected = InvalidExpiresRangeException.class)
public void testPresignGetObjectFail()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
client.presignedGetObject(BUCKET, "key", 604801);
}
@Test
public void testPresignGetObject()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
String presignedObjectUrl = client.presignedGetObject(BUCKET, "key");
assertEquals(presignedObjectUrl.isEmpty(), false);
}
@Test
public void testGetObject()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
final String expectedObject = HELLO_WORLD;
response.addHeader("Date", "Sun, 05 Jun 2015 22:01:10 GMT");
response.addHeader(CONTENT_LENGTH, "5080");
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.addHeader("ETag", MD5_HASH_STRING);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT);
response.setResponseCode(200);
response.setBody(new Buffer().writeUtf8(expectedObject));
server.enqueue(response);
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
InputStream object = client.getObject(BUCKET, "key");
byte[] result = new byte[20];
int read = object.read(result);
result = Arrays.copyOf(result, read);
assertEquals(expectedObject, new String(result, StandardCharsets.UTF_8));
}
@Test
public void testPartialObject()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
final String expectedObject = HELLO;
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader(CONTENT_LENGTH, "5");
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.addHeader("ETag", MD5_HASH_STRING);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT);
response.addHeader(ACCEPT_RANGES, BYTES);
response.addHeader(CONTENT_RANGE, "0-4/11");
response.setResponseCode(206);
response.setBody(new Buffer().writeUtf8(expectedObject));
server.enqueue(response);
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
InputStream object = client.getObject(BUCKET, "key", 0L, 5L);
byte[] result = new byte[20];
int read = object.read(result);
result = Arrays.copyOf(result, read);
assertEquals(expectedObject, new String(result, StandardCharsets.UTF_8));
}
@Test(expected = InvalidArgumentException.class)
public void testGetObjectOffsetIsNegativeReturnsError()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
final String expectedObject = HELLO;
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader(CONTENT_LENGTH, "5");
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.addHeader("ETag", MD5_HASH_STRING);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT);
response.addHeader(ACCEPT_RANGES, BYTES);
response.addHeader(CONTENT_RANGE, "0-4/11");
response.setResponseCode(206);
response.setBody(new Buffer().writeUtf8(expectedObject));
server.enqueue(response);
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
client.getObject(BUCKET, "key", -1L, 5L);
Assert.fail("Should of thrown an exception");
}
@Test(expected = InvalidArgumentException.class)
public void testGetObjectLengthIsZeroReturnsError()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
final String expectedObject = HELLO;
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader(CONTENT_LENGTH, "5");
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.addHeader("ETag", MD5_HASH_STRING);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT);
response.addHeader(ACCEPT_RANGES, BYTES);
response.addHeader(CONTENT_RANGE, "0-4/11");
response.setResponseCode(206);
response.setBody(new Buffer().writeUtf8(expectedObject));
server.enqueue(response);
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
client.getObject(BUCKET, "key", 0L, 0L);
Assert.fail("Should of thrown an exception");
}
/**
* test GetObjectWithOffset.
*/
public void testGetObjectWithOffset()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
final String expectedObject = "world";
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader(CONTENT_LENGTH, "6");
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.addHeader("ETag", MD5_HASH_STRING);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT);
response.addHeader(ACCEPT_RANGES, BYTES);
response.addHeader(CONTENT_RANGE, "5-10/11");
response.setResponseCode(206);
response.setBody(new Buffer().writeUtf8(expectedObject));
server.enqueue(response);
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
InputStream object = client.getObject(BUCKET, "key", 6);
byte[] result = new byte[5];
int read = object.read(result);
result = Arrays.copyOf(result, read);
assertEquals(expectedObject, new String(result, StandardCharsets.UTF_8));
}
@Test
public void testListObjects()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
final String body = "<ListBucketResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Name>bucket</Name><Prefix></Prefix><Marker></Marker><MaxKeys>1000</MaxKeys><Delimiter></Delimiter><IsTruncated>false</IsTruncated><Contents><Key>key</Key><LastModified>2015-05-05T02:21:15.716Z</LastModified><ETag>\"5eb63bbbe01eeed093cb22bb8f5acdc3\"</ETag><Size>11</Size><StorageClass>STANDARD</StorageClass><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></Contents><Contents><Key>key2</Key><LastModified>2015-05-05T20:36:17.498Z</LastModified><ETag>\"2a60eaffa7a82804bdc682ce1df6c2d4\"</ETag><Size>1661</Size><StorageClass>STANDARD</StorageClass><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></Contents></ListBucketResult>";
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.addHeader(CONTENT_LENGTH, "414");
response.addHeader(CONTENT_TYPE, "application/xml");
response.setBody(new Buffer().writeUtf8(body));
response.setResponseCode(200);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
Iterator<Result<Item>> objectsInBucket = client.listObjects(BUCKET).iterator();
Item item = objectsInBucket.next().get();
assertEquals("key", item.objectName());
assertEquals(11, item.objectSize());
assertEquals("STANDARD", item.storageClass());
Calendar expectedDate = Calendar.getInstance();
expectedDate.clear();
expectedDate.setTimeZone(TimeZone.getTimeZone("UTC"));
expectedDate.set(2015, Calendar.MAY, 5, 2, 21, 15);
expectedDate.set(Calendar.MILLISECOND, 716);
assertEquals(expectedDate.getTime(), item.lastModified());
Owner owner = item.owner();
assertEquals("minio", owner.id());
assertEquals("minio", owner.displayName());
}
@Test
public void testListBuckets()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException,
ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
final String body = "<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-05T20:35:51.410Z</CreationDate></Bucket><Bucket><Name>foo</Name><CreationDate>2015-05-05T20:35:47.170Z</CreationDate></Bucket></Buckets></ListAllMyBucketsResult>";
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.addHeader(CONTENT_LENGTH, "351");
response.addHeader(CONTENT_TYPE, "application/xml");
response.setBody(new Buffer().writeUtf8(body));
response.setResponseCode(200);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
Iterator<Bucket> buckets = client.listBuckets().iterator();
Bucket bucket = buckets.next();
assertEquals(BUCKET, bucket.name());
assertEquals(dateFormat.parse("2015-05-05T20:35:51.410Z"), bucket.creationDate());
bucket = buckets.next();
assertEquals("foo", bucket.name());
assertEquals(dateFormat.parse("2015-05-05T20:35:47.170Z"), bucket.creationDate());
Calendar expectedDate = Calendar.getInstance();
expectedDate.clear();
expectedDate.setTimeZone(TimeZone.getTimeZone("UTC"));
expectedDate.set(2015, Calendar.MAY, 5, 20, 35, 47);
expectedDate.set(Calendar.MILLISECOND, 170);
assertEquals(expectedDate.getTime(), bucket.creationDate());
}
@Test
public void testBucketExists()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(200);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
boolean result = client.bucketExists(BUCKET);
assertEquals(true, result);
}
@Test
public void testBucketExistsFails()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(404);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
boolean result = client.bucketExists(BUCKET);
assertEquals(false, result);
}
@Test
public void testMakeBucket()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response1 = new MockResponse();
MockResponse response2 = new MockResponse();
response1.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response1.setResponseCode(200);
response2.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response2.setResponseCode(200);
server.enqueue(response1);
server.enqueue(response2);
server.start();
MinioClient client = new MinioClient(server.url(""));
client.makeBucket(BUCKET);
}
@Test(expected = ErrorResponseException.class)
public void testMakeBucketFails()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
final ErrorResponse errResponse = new ErrorResponse(ErrorCode.BUCKET_ALREADY_EXISTS, null, null, "/bucket", "1",
null);
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(409); // status conflict
response.setBody(new Buffer().writeUtf8(errResponse.toString()));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
client.makeBucket(BUCKET);
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test
public void testPutSmallObject()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_UTC);
response.addHeader("ETag", MD5_HASH_STRING);
response.setResponseCode(200);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
String inputString = HELLO_WORLD;
ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
client.putObject(BUCKET, "key", data, 11, APPLICATION_OCTET_STREAM);
}
// this case only occurs for minio cloud storage
@Test(expected = ErrorResponseException.class)
public void testPutSmallObjectFails()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
final ErrorResponse errResponse = new ErrorResponse(ErrorCode.METHOD_NOT_ALLOWED, null, null, BUCKET_KEY, "1",
null);
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(405); // method not allowed set by minio cloud storage
response.setBody(new Buffer().writeUtf8(errResponse.toString()));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
String inputString = HELLO_WORLD;
ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
client.putObject(BUCKET, "key", data, 11, APPLICATION_OCTET_STREAM);
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test(expected = EOFException.class)
public void testPutIncompleteSmallPut()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
final ErrorResponse errResponse = new ErrorResponse(ErrorCode.METHOD_NOT_ALLOWED, null, null, BUCKET_KEY, "1",
null);
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(405); // method not allowed set by minio cloud storage
response.setBody(new Buffer().writeUtf8(errResponse.toString()));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
String inputString = "hello worl";
ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
client.putObject(BUCKET, "key", data, 11, APPLICATION_OCTET_STREAM);
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test(expected = ErrorResponseException.class)
public void testPutOversizedSmallPut()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
final ErrorResponse errResponse = new ErrorResponse(ErrorCode.METHOD_NOT_ALLOWED, null, null, BUCKET_KEY, "1",
null);
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(405); // method not allowed set by minio cloud storage
response.setBody(new Buffer().writeUtf8(errResponse.toString()));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
String inputString = "how long is a piece of string? too long!";
ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
client.putObject(BUCKET, "key", data, 11, APPLICATION_OCTET_STREAM);
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test
public void testSpecialCharsNameWorks()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_UTC);
response.addHeader("ETag", MD5_HASH_STRING);
response.setResponseCode(200);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
String inputString = HELLO_WORLD;
ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
byte[] ascii = new byte[255];
for (int i = 1; i < 256; i++) {
ascii[i - 1] = (byte) i;
}
client.putObject(BUCKET, "世界" + new String(ascii, "UTF-8"), data, 11, null);
}
@Test
public void testNullContentTypeWorks()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_UTC);
response.addHeader("ETag", MD5_HASH_STRING);
response.setResponseCode(200);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
String inputString = HELLO_WORLD;
ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
client.putObject(BUCKET, "key", data, 11, null);
}
@Test
public void testSigningKey()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.addHeader(CONTENT_LENGTH, "5080");
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.addHeader("ETag", "\"a670520d9d36833b3e28d1e4b73cbe22\"");
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_UTC);
response.setResponseCode(200);
server.enqueue(response);
server.start();
// build expected request
Calendar expectedDate = Calendar.getInstance();
expectedDate.clear();
expectedDate.setTimeZone(TimeZone.getTimeZone("UTC"));
expectedDate.set(2015, Calendar.MAY, 4, 7, 58, 51);
String contentType = APPLICATION_OCTET_STREAM;
ObjectStat expectedStatInfo = new ObjectStat(BUCKET, "key", expectedDate.getTime(), 5080,
"a670520d9d36833b3e28d1e4b73cbe22", contentType);
// get request
MinioClient client = new MinioClient(server.url(""), "foo", "bar");
ObjectStat objectStatInfo = client.statObject(BUCKET, "key");
assertEquals(expectedStatInfo, objectStatInfo);
}
@Test
public void testSetBucketPolicyReadOnly()
throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException,
InsufficientDataException, IOException, InvalidKeyException, NoResponseException,
XmlPullParserException, ErrorResponseException, InternalException,
NoSuchBucketPolicyException, MinioException {
// Create Mock web server and mocked responses
MockWebServer server = new MockWebServer();
MockResponse response1 = new MockResponse();
MockResponse response2 = new MockResponse();
response1.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response1.setResponseCode(200);
/* Second response is expected to return a blank policy as
* we are creating a new bucket, so create a blank policy */
BucketAccessPolicy none = BucketAccessPolicy.none();
/* serialize the object into its equivalent Json representation and set it in the
* response body */
response1.setBody(gson.toJson(none));
response2.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response2.setResponseCode(200);
server.enqueue(response1);
server.enqueue(response2);
server.start();
MinioClient client = new MinioClient(server.url(""));
// Set the bucket policy for a bucket
client.setBucketPolicy(BUCKET, "uploads", BucketPolicy.ReadOnly);
}
@Test
public void testSetBucketPolicyReadWrite()
throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException,
InsufficientDataException, IOException, InvalidKeyException, NoResponseException,
XmlPullParserException, ErrorResponseException, InternalException,
NoSuchBucketPolicyException, MinioException {
// Create Mock web server and mocked responses
MockWebServer server = new MockWebServer();
MockResponse response1 = new MockResponse();
MockResponse response2 = new MockResponse();
response1.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response1.setResponseCode(200);
/* Second response is expected to return a blank policy as
* we are creating a new bucket, so create a blank policy */
BucketAccessPolicy none = BucketAccessPolicy.none();
/* serialize the object into its equivalent Json representation and set it in the
* response body */
response1.setBody(gson.toJson(none));
response2.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response2.setResponseCode(200);
server.enqueue(response1);
server.enqueue(response2);
server.start();
MinioClient client = new MinioClient(server.url(""));
// Set the bucket policy for a bucket
client.setBucketPolicy(BUCKET, "uploads", BucketPolicy.ReadWrite);
}
@Test
public void testSetBucketPolicyWriteOnly()
throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException,
InsufficientDataException, IOException, InvalidKeyException, NoResponseException,
XmlPullParserException, ErrorResponseException, InternalException,
NoSuchBucketPolicyException, MinioException {
// Create Mock web server and mocked responses
MockWebServer server = new MockWebServer();
MockResponse response1 = new MockResponse();
MockResponse response2 = new MockResponse();
response1.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response1.setResponseCode(200);
/* Second response is expected to return a blank policy as
* we are creating a new bucket, so create a blank policy */
BucketAccessPolicy none = BucketAccessPolicy.none();
/* serialize the object into its equivalent Json representation and set it in the
* response body */
response1.setBody(gson.toJson(none));
response2.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response2.setResponseCode(200);
server.enqueue(response1);
server.enqueue(response2);
server.start();
MinioClient client = new MinioClient(server.url(""));
// Set the bucket policy for a bucket
client.setBucketPolicy(BUCKET, "uploads", BucketPolicy.WriteOnly);
}
@Test
public void testGetBucketPolicyReadOnly()
throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException,
InsufficientDataException, IOException, InvalidKeyException, NoResponseException,
XmlPullParserException, ErrorResponseException, InternalException,
NoSuchBucketPolicyException, MinioException {
// Create Mock web server and mocked responses
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(200);
/* Second response is expected to return a blank policy as
* we are creating a new bucket, so create a blank policy */
BucketAccessPolicy none = BucketAccessPolicy.none();
// Generate statements
List<Statement> generatedStatements = BucketAccessPolicy.generatePolicyStatements(BucketPolicy.ReadOnly,
BUCKET, "uploads");
// Add statements to the BucketAccessPolicy
none.setStatements(generatedStatements);
/* serialize the object into its equivalent Json representation and set it in the
* response body */
response.setBody(gson.toJson(none));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
// Get the bucket policy for the new bucket and check
BucketPolicy responseBucketPolicy = client.getBucketPolicy(BUCKET, "uploads");
assertEquals(BucketPolicy.ReadOnly, responseBucketPolicy);
}
@Test
public void testGetBucketPolicyReadWrite()
throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException,
InsufficientDataException, IOException, InvalidKeyException, NoResponseException,
XmlPullParserException, ErrorResponseException, InternalException,
NoSuchBucketPolicyException, MinioException {
// Create Mock web server and mocked responses
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(200);
/* Second response is expected to return a blank policy as
* we are creating a new bucket, so create a blank policy */
BucketAccessPolicy none = BucketAccessPolicy.none();
// Generate statements
List<Statement> generatedStatements = BucketAccessPolicy.generatePolicyStatements(BucketPolicy.ReadWrite,
BUCKET, "uploads");
// Add statements to the BucketAccessPolicy
none.setStatements(generatedStatements);
/* serialize the object into its equivalent Json representation and set it in the
* response body */
response.setBody(gson.toJson(none));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
// Get the bucket policy for the new bucket and check
BucketPolicy responseBucketPolicy = client.getBucketPolicy(BUCKET, "uploads");
assertEquals(BucketPolicy.ReadWrite, responseBucketPolicy);
}
@Test
public void testGetBucketPolicyWriteOnly()
throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException,
InsufficientDataException, IOException, InvalidKeyException, NoResponseException,
XmlPullParserException, ErrorResponseException, InternalException,
NoSuchBucketPolicyException, MinioException {
// Create Mock web server and mocked responses
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(200);
/* Second response is expected to return a blank policy as
* we are creating a new bucket, so create a blank policy */
BucketAccessPolicy none = BucketAccessPolicy.none();
// Generate statements
List<Statement> generatedStatements = BucketAccessPolicy.generatePolicyStatements(BucketPolicy.WriteOnly,
BUCKET, "uploads");
// Add statements to the BucketAccessPolicy
none.setStatements(generatedStatements);
/* serialize the object into its equivalent Json representation and set it in the
* response body */
response.setBody(gson.toJson(none));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
// Get the bucket policy for the new bucket and check
BucketPolicy responseBucketPolicy = client.getBucketPolicy(BUCKET, "uploads");
assertEquals(BucketPolicy.WriteOnly, responseBucketPolicy);
}
}
| src/test/java/io/minio/MinioClientTest.java | /*
* Minio Java Library for Amazon S3 Compatible Cloud Storage, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.minio;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.google.gson.Gson;
import com.squareup.okhttp.mockwebserver.MockResponse;
import okio.Buffer;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import io.minio.messages.ErrorResponse;
import io.minio.messages.Item;
import io.minio.messages.Owner;
import org.junit.Assert;
import org.junit.Test;
import org.xmlpull.v1.XmlPullParserException;
import java.nio.charset.StandardCharsets;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import static org.junit.Assert.assertEquals;
@SuppressWarnings("unused")
public class MinioClientTest {
private static final String EXPECTED_EXCEPTION_DID_NOT_FIRE = "Expected exception did not fire";
private static final String BUCKET = "bucket";
private static final String CONTENT_LENGTH = "Content-Length";
private static final String APPLICATION_OCTET_STREAM = "application/octet-stream";
private static final String CONTENT_TYPE = "Content-Type";
private static final String MON_04_MAY_2015_07_58_51_GMT = "Mon, 04 May 2015 07:58:51 GMT";
private static final String LAST_MODIFIED = "Last-Modified";
private static final String HELLO_WORLD = "hello world";
private static final String HELLO = "hello";
private static final String BYTES = "bytes";
private static final String ACCEPT_RANGES = "Accept-Ranges";
private static final String CONTENT_RANGE = "Content-Range";
private static final String SUN_29_JUN_2015_22_01_10_GMT = "Sun, 29 Jun 2015 22:01:10 GMT";
private static final String MON_04_MAY_2015_07_58_51_UTC = "Mon, 04 May 2015 07:58:51 UTC";
private static final String BUCKET_KEY = "/bucket/key";
private static final String MD5_HASH_STRING = "\"5eb63bbbe01eeed093cb22bb8f5acdc3\"";
private static final Gson gson = new Gson();
@Test()
public void setUserAgentOnceSet() throws IOException, MinioException {
String expectedHost = "example.com";
MinioClient client = new MinioClient("http://" + expectedHost + "/");
client.setAppInfo("testApp", "2.0.1");
}
@Test(expected = MinioException.class)
public void newClientWithPathFails() throws MinioException {
new MinioClient("http://example.com/path");
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test(expected = NullPointerException.class)
public void newClientWithNullUrlFails() throws NullPointerException, MinioException {
URL url = null;
new MinioClient(url);
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test(expected = MinioException.class)
public void newClientWithNullStringFails() throws InvalidArgumentException, MinioException {
String url = null;
new MinioClient(url);
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test(expected = ErrorResponseException.class)
public void testForbidden()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(403));
server.start();
MinioClient client = new MinioClient(server.url(""));
client.statObject(BUCKET, "key");
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test(expected = ErrorResponseException.class)
public void getMissingObjectHeaders()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(404));
server.start();
MinioClient client = new MinioClient(server.url(""));
client.statObject(BUCKET, "key");
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test
public void testGetObjectHeaders()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.setResponseCode(200);
response.setHeader("Date", "Sun, 05 Jun 2015 22:01:10 GMT");
response.setHeader(CONTENT_LENGTH, "5080");
response.setHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.setHeader("ETag", "\"a670520d9d36833b3e28d1e4b73cbe22\"");
response.setHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT);
server.enqueue(response);
server.start();
// build expected request
Calendar expectedDate = Calendar.getInstance();
expectedDate.clear();
expectedDate.setTimeZone(TimeZone.getTimeZone("GMT"));
expectedDate.set(2015, Calendar.MAY, 4, 7, 58, 51);
ObjectStat expectedStatInfo = new ObjectStat(BUCKET, "key",
expectedDate.getTime(),
5080,
"a670520d9d36833b3e28d1e4b73cbe22",
APPLICATION_OCTET_STREAM);
// get request
MinioClient client = new MinioClient(server.url(""));
ObjectStat objectStatInfo = client.statObject(BUCKET, "key");
assertEquals(expectedStatInfo, objectStatInfo);
}
@Test(expected = InvalidExpiresRangeException.class)
public void testPresignGetObjectFail()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
client.presignedGetObject(BUCKET, "key", 604801);
}
@Test
public void testPresignGetObject()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
String presignedObjectUrl = client.presignedGetObject(BUCKET, "key");
assertEquals(presignedObjectUrl.isEmpty(), false);
}
@Test
public void testGetObject()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
final String expectedObject = HELLO_WORLD;
response.addHeader("Date", "Sun, 05 Jun 2015 22:01:10 GMT");
response.addHeader(CONTENT_LENGTH, "5080");
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.addHeader("ETag", MD5_HASH_STRING);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT);
response.setResponseCode(200);
response.setBody(new Buffer().writeUtf8(expectedObject));
server.enqueue(response);
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
InputStream object = client.getObject(BUCKET, "key");
byte[] result = new byte[20];
int read = object.read(result);
result = Arrays.copyOf(result, read);
assertEquals(expectedObject, new String(result, StandardCharsets.UTF_8));
}
@Test
public void testPartialObject()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
final String expectedObject = HELLO;
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader(CONTENT_LENGTH, "5");
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.addHeader("ETag", MD5_HASH_STRING);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT);
response.addHeader(ACCEPT_RANGES, BYTES);
response.addHeader(CONTENT_RANGE, "0-4/11");
response.setResponseCode(206);
response.setBody(new Buffer().writeUtf8(expectedObject));
server.enqueue(response);
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
InputStream object = client.getObject(BUCKET, "key", 0L, 5L);
byte[] result = new byte[20];
int read = object.read(result);
result = Arrays.copyOf(result, read);
assertEquals(expectedObject, new String(result, StandardCharsets.UTF_8));
}
@Test(expected = InvalidArgumentException.class)
public void testGetObjectOffsetIsNegativeReturnsError()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
final String expectedObject = HELLO;
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader(CONTENT_LENGTH, "5");
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.addHeader("ETag", MD5_HASH_STRING);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT);
response.addHeader(ACCEPT_RANGES, BYTES);
response.addHeader(CONTENT_RANGE, "0-4/11");
response.setResponseCode(206);
response.setBody(new Buffer().writeUtf8(expectedObject));
server.enqueue(response);
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
client.getObject(BUCKET, "key", -1L, 5L);
Assert.fail("Should of thrown an exception");
}
@Test(expected = InvalidArgumentException.class)
public void testGetObjectLengthIsZeroReturnsError()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
final String expectedObject = HELLO;
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader(CONTENT_LENGTH, "5");
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.addHeader("ETag", MD5_HASH_STRING);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT);
response.addHeader(ACCEPT_RANGES, BYTES);
response.addHeader(CONTENT_RANGE, "0-4/11");
response.setResponseCode(206);
response.setBody(new Buffer().writeUtf8(expectedObject));
server.enqueue(response);
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
client.getObject(BUCKET, "key", 0L, 0L);
Assert.fail("Should of thrown an exception");
}
/**
* test GetObjectWithOffset.
*/
public void testGetObjectWithOffset()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
final String expectedObject = "world";
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader(CONTENT_LENGTH, "6");
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.addHeader("ETag", MD5_HASH_STRING);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT);
response.addHeader(ACCEPT_RANGES, BYTES);
response.addHeader(CONTENT_RANGE, "5-10/11");
response.setResponseCode(206);
response.setBody(new Buffer().writeUtf8(expectedObject));
server.enqueue(response);
server.start();
// get request
MinioClient client = new MinioClient(server.url(""));
InputStream object = client.getObject(BUCKET, "key", 6);
byte[] result = new byte[5];
int read = object.read(result);
result = Arrays.copyOf(result, read);
assertEquals(expectedObject, new String(result, StandardCharsets.UTF_8));
}
@Test
public void testListObjects()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
final String body = "<ListBucketResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Name>bucket</Name><Prefix></Prefix><Marker></Marker><MaxKeys>1000</MaxKeys><Delimiter></Delimiter><IsTruncated>false</IsTruncated><Contents><Key>key</Key><LastModified>2015-05-05T02:21:15.716Z</LastModified><ETag>\"5eb63bbbe01eeed093cb22bb8f5acdc3\"</ETag><Size>11</Size><StorageClass>STANDARD</StorageClass><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></Contents><Contents><Key>key2</Key><LastModified>2015-05-05T20:36:17.498Z</LastModified><ETag>\"2a60eaffa7a82804bdc682ce1df6c2d4\"</ETag><Size>1661</Size><StorageClass>STANDARD</StorageClass><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></Contents></ListBucketResult>";
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.addHeader(CONTENT_LENGTH, "414");
response.addHeader(CONTENT_TYPE, "application/xml");
response.setBody(new Buffer().writeUtf8(body));
response.setResponseCode(200);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
Iterator<Result<Item>> objectsInBucket = client.listObjects(BUCKET).iterator();
Item item = objectsInBucket.next().get();
assertEquals("key", item.objectName());
assertEquals(11, item.objectSize());
assertEquals("STANDARD", item.storageClass());
Calendar expectedDate = Calendar.getInstance();
expectedDate.clear();
expectedDate.setTimeZone(TimeZone.getTimeZone("UTC"));
expectedDate.set(2015, Calendar.MAY, 5, 2, 21, 15);
expectedDate.set(Calendar.MILLISECOND, 716);
assertEquals(expectedDate.getTime(), item.lastModified());
Owner owner = item.owner();
assertEquals("minio", owner.id());
assertEquals("minio", owner.displayName());
}
@Test
public void testListBuckets()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException,
ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
final String body = "<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-05T20:35:51.410Z</CreationDate></Bucket><Bucket><Name>foo</Name><CreationDate>2015-05-05T20:35:47.170Z</CreationDate></Bucket></Buckets></ListAllMyBucketsResult>";
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.addHeader(CONTENT_LENGTH, "351");
response.addHeader(CONTENT_TYPE, "application/xml");
response.setBody(new Buffer().writeUtf8(body));
response.setResponseCode(200);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
Iterator<Bucket> buckets = client.listBuckets().iterator();
Bucket bucket = buckets.next();
assertEquals(BUCKET, bucket.name());
assertEquals(dateFormat.parse("2015-05-05T20:35:51.410Z"), bucket.creationDate());
bucket = buckets.next();
assertEquals("foo", bucket.name());
assertEquals(dateFormat.parse("2015-05-05T20:35:47.170Z"), bucket.creationDate());
Calendar expectedDate = Calendar.getInstance();
expectedDate.clear();
expectedDate.setTimeZone(TimeZone.getTimeZone("UTC"));
expectedDate.set(2015, Calendar.MAY, 5, 20, 35, 47);
expectedDate.set(Calendar.MILLISECOND, 170);
assertEquals(expectedDate.getTime(), bucket.creationDate());
}
@Test
public void testBucketExists()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(200);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
boolean result = client.bucketExists(BUCKET);
assertEquals(true, result);
}
@Test
public void testBucketExistsFails()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(404);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
boolean result = client.bucketExists(BUCKET);
assertEquals(false, result);
}
@Test
public void testMakeBucket()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response1 = new MockResponse();
MockResponse response2 = new MockResponse();
response1.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response1.setResponseCode(200);
response2.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response2.setResponseCode(200);
server.enqueue(response1);
server.enqueue(response2);
server.start();
MinioClient client = new MinioClient(server.url(""));
client.makeBucket(BUCKET);
}
@Test(expected = ErrorResponseException.class)
public void testMakeBucketFails()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
final ErrorResponse errResponse = new ErrorResponse(ErrorCode.BUCKET_ALREADY_EXISTS, null, null, "/bucket", "1",
null);
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(409); // status conflict
response.setBody(new Buffer().writeUtf8(errResponse.toString()));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
client.makeBucket(BUCKET);
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test
public void testPutSmallObject()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_UTC);
response.addHeader("ETag", MD5_HASH_STRING);
response.setResponseCode(200);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
String inputString = HELLO_WORLD;
ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
client.putObject(BUCKET, "key", data, 11, APPLICATION_OCTET_STREAM);
}
// this case only occurs for minio cloud storage
@Test(expected = ErrorResponseException.class)
public void testPutSmallObjectFails()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
final ErrorResponse errResponse = new ErrorResponse(ErrorCode.METHOD_NOT_ALLOWED, null, null, BUCKET_KEY, "1",
null);
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(405); // method not allowed set by minio cloud storage
response.setBody(new Buffer().writeUtf8(errResponse.toString()));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
String inputString = HELLO_WORLD;
ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
client.putObject(BUCKET, "key", data, 11, APPLICATION_OCTET_STREAM);
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test(expected = EOFException.class)
public void testPutIncompleteSmallPut()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
final ErrorResponse errResponse = new ErrorResponse(ErrorCode.METHOD_NOT_ALLOWED, null, null, BUCKET_KEY, "1",
null);
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(405); // method not allowed set by minio cloud storage
response.setBody(new Buffer().writeUtf8(errResponse.toString()));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
String inputString = "hello worl";
ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
client.putObject(BUCKET, "key", data, 11, APPLICATION_OCTET_STREAM);
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test(expected = ErrorResponseException.class)
public void testPutOversizedSmallPut()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
final ErrorResponse errResponse = new ErrorResponse(ErrorCode.METHOD_NOT_ALLOWED, null, null, BUCKET_KEY, "1",
null);
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(405); // method not allowed set by minio cloud storage
response.setBody(new Buffer().writeUtf8(errResponse.toString()));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
String inputString = "how long is a piece of string? too long!";
ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
client.putObject(BUCKET, "key", data, 11, APPLICATION_OCTET_STREAM);
throw new RuntimeException(EXPECTED_EXCEPTION_DID_NOT_FIRE);
}
@Test
public void testSpecialCharsNameWorks()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_UTC);
response.addHeader("ETag", MD5_HASH_STRING);
response.setResponseCode(200);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
String inputString = HELLO_WORLD;
ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
byte[] ascii = new byte[255];
for (int i = 1; i < 256; i++) {
ascii[i - 1] = (byte) i;
}
client.putObject(BUCKET, "世界" + new String(ascii, "UTF-8"), data, 11, null);
}
@Test
public void testNullContentTypeWorks()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_UTC);
response.addHeader("ETag", MD5_HASH_STRING);
response.setResponseCode(200);
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
String inputString = HELLO_WORLD;
ByteArrayInputStream data = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
client.putObject(BUCKET, "key", data, 11, null);
}
@Test
public void testSigningKey()
throws NoSuchAlgorithmException, InvalidKeyException, IOException, XmlPullParserException, MinioException {
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.addHeader(CONTENT_LENGTH, "5080");
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
response.addHeader("ETag", "\"a670520d9d36833b3e28d1e4b73cbe22\"");
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_UTC);
response.setResponseCode(200);
server.enqueue(response);
server.start();
// build expected request
Calendar expectedDate = Calendar.getInstance();
expectedDate.clear();
expectedDate.setTimeZone(TimeZone.getTimeZone("UTC"));
expectedDate.set(2015, Calendar.MAY, 4, 7, 58, 51);
String contentType = APPLICATION_OCTET_STREAM;
ObjectStat expectedStatInfo = new ObjectStat(BUCKET, "key", expectedDate.getTime(), 5080,
"a670520d9d36833b3e28d1e4b73cbe22", contentType);
// get request
MinioClient client = new MinioClient(server.url(""), "foo", "bar");
ObjectStat objectStatInfo = client.statObject(BUCKET, "key");
assertEquals(expectedStatInfo, objectStatInfo);
}
@Test
public void testSetBucketPolicyReadOnly()
throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException,
InsufficientDataException, IOException, InvalidKeyException, NoResponseException,
XmlPullParserException, ErrorResponseException, InternalException,
NoSuchBucketPolicyException, MinioException {
// Create Mock web server and mocked responses
MockWebServer server = new MockWebServer();
MockResponse response1 = new MockResponse();
MockResponse response2 = new MockResponse();
response1.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response1.setResponseCode(200);
/* Second response is expected to return a blank policy as
* we are creating a new bucket, so create a blank policy */
BucketAccessPolicy none = BucketAccessPolicy.none();
/* serialize the object into its equivalent Json representation and set it in the
* response body */
response1.setBody(gson.toJson(none));
response2.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response2.setResponseCode(200);
server.enqueue(response1);
server.enqueue(response2);
server.start();
MinioClient client = new MinioClient(server.url(""));
// Set the bucket policy for a bucket
client.setBucketPolicy(BUCKET, "uploads", BucketPolicy.ReadOnly);
}
@Test
public void testSetBucketPolicyReadWrite()
throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException,
InsufficientDataException, IOException, InvalidKeyException, NoResponseException,
XmlPullParserException, ErrorResponseException, InternalException,
NoSuchBucketPolicyException, MinioException {
// Create Mock web server and mocked responses
MockWebServer server = new MockWebServer();
MockResponse response1 = new MockResponse();
MockResponse response2 = new MockResponse();
response1.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response1.setResponseCode(200);
/* Second response is expected to return a blank policy as
* we are creating a new bucket, so create a blank policy */
BucketAccessPolicy none = BucketAccessPolicy.none();
/* serialize the object into its equivalent Json representation and set it in the
* response body */
response1.setBody(gson.toJson(none));
response2.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response2.setResponseCode(200);
server.enqueue(response1);
server.enqueue(response2);
server.start();
MinioClient client = new MinioClient(server.url(""));
// Set the bucket policy for a bucket
client.setBucketPolicy(BUCKET, "uploads", BucketPolicy.ReadWrite);
}
@Test
public void testSetBucketPolicyWriteOnly()
throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException,
InsufficientDataException, IOException, InvalidKeyException, NoResponseException,
XmlPullParserException, ErrorResponseException, InternalException,
NoSuchBucketPolicyException, MinioException {
// Create Mock web server and mocked responses
MockWebServer server = new MockWebServer();
MockResponse response1 = new MockResponse();
MockResponse response2 = new MockResponse();
response1.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response1.setResponseCode(200);
/* Second response is expected to return a blank policy as
* we are creating a new bucket, so create a blank policy */
BucketAccessPolicy none = BucketAccessPolicy.none();
/* serialize the object into its equivalent Json representation and set it in the
* response body */
response1.setBody(gson.toJson(none));
response2.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response2.setResponseCode(200);
server.enqueue(response1);
server.enqueue(response2);
server.start();
MinioClient client = new MinioClient(server.url(""));
// Set the bucket policy for a bucket
client.setBucketPolicy(BUCKET, "uploads", BucketPolicy.WriteOnly);
}
@Test
public void testGetBucketPolicyReadOnly()
throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException,
InsufficientDataException, IOException, InvalidKeyException, NoResponseException,
XmlPullParserException, ErrorResponseException, InternalException,
NoSuchBucketPolicyException, MinioException {
// Create Mock web server and mocked responses
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(200);
/* Second response is expected to return a blank policy as
* we are creating a new bucket, so create a blank policy */
BucketAccessPolicy none = BucketAccessPolicy.none();
// Generate statements
List<Statement> generatedStatements = BucketAccessPolicy.generatePolicyStatements(BucketPolicy.ReadOnly,
BUCKET, "uploads");
// Add statements to the BucketAccessPolicy
none.setStatements(generatedStatements);
/* serialize the object into its equivalent Json representation and set it in the
* response body */
response.setBody(gson.toJson(none));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
// Get the bucket policy for the new bucket and check
BucketPolicy responseBucketPolicy = client.getBucketPolicy(BUCKET, "uploads");
assertEquals(BucketPolicy.ReadOnly, responseBucketPolicy);
}
@Test
public void testGetBucketPolicyReadWrite()
throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException,
InsufficientDataException, IOException, InvalidKeyException, NoResponseException,
XmlPullParserException, ErrorResponseException, InternalException,
NoSuchBucketPolicyException, MinioException {
// Create Mock web server and mocked responses
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(200);
/* Second response is expected to return a blank policy as
* we are creating a new bucket, so create a blank policy */
BucketAccessPolicy none = BucketAccessPolicy.none();
// Generate statements
List<Statement> generatedStatements = BucketAccessPolicy.generatePolicyStatements(BucketPolicy.ReadWrite,
BUCKET, "uploads");
// Add statements to the BucketAccessPolicy
none.setStatements(generatedStatements);
/* serialize the object into its equivalent Json representation and set it in the
* response body */
response.setBody(gson.toJson(none));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
// Get the bucket policy for the new bucket and check
BucketPolicy responseBucketPolicy = client.getBucketPolicy(BUCKET, "uploads");
assertEquals(BucketPolicy.ReadWrite, responseBucketPolicy);
}
@Test
public void testGetBucketPolicyWriteOnly()
throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException,
InsufficientDataException, IOException, InvalidKeyException, NoResponseException,
XmlPullParserException, ErrorResponseException, InternalException,
NoSuchBucketPolicyException, MinioException {
// Create Mock web server and mocked responses
MockWebServer server = new MockWebServer();
MockResponse response = new MockResponse();
response.addHeader("Date", SUN_29_JUN_2015_22_01_10_GMT);
response.setResponseCode(200);
/* Second response is expected to return a blank policy as
* we are creating a new bucket, so create a blank policy */
BucketAccessPolicy none = BucketAccessPolicy.none();
// Generate statements
List<Statement> generatedStatements = BucketAccessPolicy.generatePolicyStatements(BucketPolicy.WriteOnly,
BUCKET, "uploads");
// Add statements to the BucketAccessPolicy
none.setStatements(generatedStatements);
/* serialize the object into its equivalent Json representation and set it in the
* response body */
response.setBody(gson.toJson(none));
server.enqueue(response);
server.start();
MinioClient client = new MinioClient(server.url(""));
// Get the bucket policy for the new bucket and check
BucketPolicy responseBucketPolicy = client.getBucketPolicy(BUCKET, "uploads");
assertEquals(BucketPolicy.WriteOnly, responseBucketPolicy);
}
}
| fix: checkstyle errors in MinioClientTest. (#445)
| src/test/java/io/minio/MinioClientTest.java | fix: checkstyle errors in MinioClientTest. (#445) |
|
Java | apache-2.0 | 322bf405028d9398162ec30941d255f429a532b7 | 0 | PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr | package org.apache.lucene.index;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.CannedTokenStream;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.analysis.MockPayloadAnalyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.English;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;
import org.apache.lucene.util._TestUtil;
// TODO: we really need to test indexingoffsets, but then getting only docs / docs + freqs.
// not all codecs store prx separate...
// TODO: fix sep codec to index offsets so we can greatly reduce this list!
@SuppressCodecs({"Lucene3x", "MockFixedIntBlock", "MockVariableIntBlock", "MockSep", "MockRandom"})
public class TestPostingsOffsets extends LuceneTestCase {
IndexWriterConfig iwc;
public void setUp() throws Exception {
super.setUp();
iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
}
public void testBasic() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
Document doc = new Document();
FieldType ft = new FieldType(TextField.TYPE_UNSTORED);
ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
if (random().nextBoolean()) {
ft.setStoreTermVectors(true);
ft.setStoreTermVectorPositions(random().nextBoolean());
ft.setStoreTermVectorOffsets(random().nextBoolean());
}
Token[] tokens = new Token[] {
makeToken("a", 1, 0, 6),
makeToken("b", 1, 8, 9),
makeToken("a", 1, 9, 17),
makeToken("c", 1, 19, 50),
};
doc.add(new Field("content", new CannedTokenStream(tokens), ft));
w.addDocument(doc);
IndexReader r = w.getReader();
w.close();
DocsAndPositionsEnum dp = MultiFields.getTermPositionsEnum(r, null, "content", new BytesRef("a"), true);
assertNotNull(dp);
assertEquals(0, dp.nextDoc());
assertEquals(2, dp.freq());
assertEquals(0, dp.nextPosition());
assertEquals(0, dp.startOffset());
assertEquals(6, dp.endOffset());
assertEquals(2, dp.nextPosition());
assertEquals(9, dp.startOffset());
assertEquals(17, dp.endOffset());
assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc());
dp = MultiFields.getTermPositionsEnum(r, null, "content", new BytesRef("b"), true);
assertNotNull(dp);
assertEquals(0, dp.nextDoc());
assertEquals(1, dp.freq());
assertEquals(1, dp.nextPosition());
assertEquals(8, dp.startOffset());
assertEquals(9, dp.endOffset());
assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc());
dp = MultiFields.getTermPositionsEnum(r, null, "content", new BytesRef("c"), true);
assertNotNull(dp);
assertEquals(0, dp.nextDoc());
assertEquals(1, dp.freq());
assertEquals(3, dp.nextPosition());
assertEquals(19, dp.startOffset());
assertEquals(50, dp.endOffset());
assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc());
r.close();
dir.close();
}
public void testSkipping() throws Exception {
doTestNumbers(false);
}
public void testPayloads() throws Exception {
doTestNumbers(true);
}
public void doTestNumbers(boolean withPayloads) throws Exception {
Directory dir = newDirectory();
Analyzer analyzer = withPayloads ? new MockPayloadAnalyzer() : new MockAnalyzer(random());
iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
iwc.setMergePolicy(newLogMergePolicy()); // will rely on docids a bit for skipping
RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
FieldType ft = new FieldType(TextField.TYPE_STORED);
ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
if (random().nextBoolean()) {
ft.setStoreTermVectors(true);
ft.setStoreTermVectorOffsets(random().nextBoolean());
ft.setStoreTermVectorPositions(random().nextBoolean());
}
int numDocs = atLeast(500);
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
doc.add(new Field("numbers", English.intToEnglish(i), ft));
doc.add(new Field("oddeven", (i % 2) == 0 ? "even" : "odd", ft));
doc.add(new StringField("id", "" + i));
w.addDocument(doc);
}
IndexReader reader = w.getReader();
w.close();
String terms[] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "hundred" };
for (String term : terms) {
DocsAndPositionsEnum dp = MultiFields.getTermPositionsEnum(reader, null, "numbers", new BytesRef(term), true);
int doc;
while((doc = dp.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
String storedNumbers = reader.document(doc).get("numbers");
int freq = dp.freq();
for (int i = 0; i < freq; i++) {
dp.nextPosition();
int start = dp.startOffset();
assert start >= 0;
int end = dp.endOffset();
assert end >= 0 && end >= start;
// check that the offsets correspond to the term in the src text
assertTrue(storedNumbers.substring(start, end).equals(term));
if (withPayloads) {
// check that we have a payload and it starts with "pos"
assertTrue(dp.hasPayload());
BytesRef payload = dp.getPayload();
assertTrue(payload.utf8ToString().startsWith("pos:"));
} // note: withPayloads=false doesnt necessarily mean we dont have them from MockAnalyzer!
}
}
}
// check we can skip correctly
int numSkippingTests = atLeast(50);
for (int j = 0; j < numSkippingTests; j++) {
int num = _TestUtil.nextInt(random(), 100, Math.min(numDocs-1, 999));
DocsAndPositionsEnum dp = MultiFields.getTermPositionsEnum(reader, null, "numbers", new BytesRef("hundred"), true);
int doc = dp.advance(num);
assertEquals(num, doc);
int freq = dp.freq();
for (int i = 0; i < freq; i++) {
String storedNumbers = reader.document(doc).get("numbers");
dp.nextPosition();
int start = dp.startOffset();
assert start >= 0;
int end = dp.endOffset();
assert end >= 0 && end >= start;
// check that the offsets correspond to the term in the src text
assertTrue(storedNumbers.substring(start, end).equals("hundred"));
if (withPayloads) {
// check that we have a payload and it starts with "pos"
assertTrue(dp.hasPayload());
BytesRef payload = dp.getPayload();
assertTrue(payload.utf8ToString().startsWith("pos:"));
} // note: withPayloads=false doesnt necessarily mean we dont have them from MockAnalyzer!
}
}
// check that other fields (without offsets) work correctly
for (int i = 0; i < numDocs; i++) {
DocsEnum dp = MultiFields.getTermDocsEnum(reader, null, "id", new BytesRef("" + i), false);
assertEquals(i, dp.nextDoc());
assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc());
}
reader.close();
dir.close();
}
public void testRandom() throws Exception {
// token -> docID -> tokens
final Map<String,Map<Integer,List<Token>>> actualTokens = new HashMap<String,Map<Integer,List<Token>>>();
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
final int numDocs = atLeast(20);
//final int numDocs = atLeast(5);
FieldType ft = new FieldType(TextField.TYPE_UNSTORED);
// TODO: randomize what IndexOptions we use; also test
// changing this up in one IW buffered segment...:
ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
if (random().nextBoolean()) {
ft.setStoreTermVectors(true);
ft.setStoreTermVectorOffsets(random().nextBoolean());
ft.setStoreTermVectorPositions(random().nextBoolean());
}
for(int docCount=0;docCount<numDocs;docCount++) {
Document doc = new Document();
doc.add(new IntField("id", docCount));
List<Token> tokens = new ArrayList<Token>();
final int numTokens = atLeast(100);
//final int numTokens = atLeast(20);
int pos = -1;
int offset = 0;
//System.out.println("doc id=" + docCount);
for(int tokenCount=0;tokenCount<numTokens;tokenCount++) {
final String text;
if (random().nextBoolean()) {
text = "a";
} else if (random().nextBoolean()) {
text = "b";
} else if (random().nextBoolean()) {
text = "c";
} else {
text = "d";
}
int posIncr = random().nextBoolean() ? 1 : random().nextInt(5);
if (tokenCount == 0 && posIncr == 0) {
posIncr = 1;
}
final int offIncr = random().nextBoolean() ? 0 : random().nextInt(5);
final int tokenOffset = random().nextInt(5);
final Token token = makeToken(text, posIncr, offset+offIncr, offset+offIncr+tokenOffset);
if (!actualTokens.containsKey(text)) {
actualTokens.put(text, new HashMap<Integer,List<Token>>());
}
final Map<Integer,List<Token>> postingsByDoc = actualTokens.get(text);
if (!postingsByDoc.containsKey(docCount)) {
postingsByDoc.put(docCount, new ArrayList<Token>());
}
postingsByDoc.get(docCount).add(token);
tokens.add(token);
pos += posIncr;
// stuff abs position into type:
token.setType(""+pos);
offset += offIncr + tokenOffset;
//System.out.println(" " + token + " posIncr=" + token.getPositionIncrement() + " pos=" + pos + " off=" + token.startOffset() + "/" + token.endOffset() + " (freq=" + postingsByDoc.get(docCount).size() + ")");
}
doc.add(new Field("content", new CannedTokenStream(tokens.toArray(new Token[tokens.size()])), ft));
w.addDocument(doc);
}
final DirectoryReader r = w.getReader();
w.close();
final String[] terms = new String[] {"a", "b", "c", "d"};
for(IndexReader reader : r.getSequentialSubReaders()) {
// TODO: improve this
AtomicReader sub = (AtomicReader) reader;
//System.out.println("\nsub=" + sub);
final TermsEnum termsEnum = sub.fields().terms("content").iterator(null);
DocsEnum docs = null;
DocsAndPositionsEnum docsAndPositions = null;
DocsAndPositionsEnum docsAndPositionsAndOffsets = null;
final int docIDToID[] = FieldCache.DEFAULT.getInts(sub, "id", false);
for(String term : terms) {
//System.out.println(" term=" + term);
if (termsEnum.seekExact(new BytesRef(term), random().nextBoolean())) {
docs = termsEnum.docs(null, docs, true);
assertNotNull(docs);
int doc;
//System.out.println(" doc/freq");
while((doc = docs.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " docID=" + doc + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docs.freq());
}
docsAndPositions = termsEnum.docsAndPositions(null, docsAndPositions, false);
assertNotNull(docsAndPositions);
//System.out.println(" doc/freq/pos");
while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docsAndPositions.freq());
for(Token token : expected) {
int pos = Integer.parseInt(token.type());
//System.out.println(" pos=" + pos);
assertEquals(pos, docsAndPositions.nextPosition());
}
}
docsAndPositionsAndOffsets = termsEnum.docsAndPositions(null, docsAndPositions, true);
assertNotNull(docsAndPositionsAndOffsets);
//System.out.println(" doc/freq/pos/offs");
while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docsAndPositions.freq());
for(Token token : expected) {
int pos = Integer.parseInt(token.type());
//System.out.println(" pos=" + pos);
assertEquals(pos, docsAndPositions.nextPosition());
assertEquals(token.startOffset(), docsAndPositions.startOffset());
assertEquals(token.endOffset(), docsAndPositions.endOffset());
}
}
}
}
// TODO: test advance:
}
r.close();
dir.close();
}
private Token makeToken(String text, int posIncr, int startOffset, int endOffset) {
final Token t = new Token();
t.append(text);
t.setPositionIncrement(posIncr);
t.setOffset(startOffset, endOffset);
return t;
}
}
| lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java | package org.apache.lucene.index;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.CannedTokenStream;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.analysis.MockPayloadAnalyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.lucene40.Lucene40PostingsFormat;
import org.apache.lucene.codecs.memory.MemoryPostingsFormat;
import org.apache.lucene.codecs.nestedpulsing.NestedPulsingPostingsFormat;
import org.apache.lucene.codecs.pulsing.Pulsing40PostingsFormat;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.English;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;
// TODO: we really need to test indexingoffsets, but then getting only docs / docs + freqs.
// not all codecs store prx separate...
public class TestPostingsOffsets extends LuceneTestCase {
IndexWriterConfig iwc;
public void setUp() throws Exception {
super.setUp();
// Currently only SimpleText and Lucene40 can index offsets into postings:
String codecName = Codec.getDefault().getName();
assumeTrue("Codec does not support offsets: " + codecName,
codecName.equals("SimpleText") ||
codecName.equals("Lucene40"));
iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
if (codecName.equals("Lucene40")) {
// Sep etc are not implemented
switch(random().nextInt(4)) {
case 0: iwc.setCodec(_TestUtil.alwaysPostingsFormat(new Lucene40PostingsFormat())); break;
case 1: iwc.setCodec(_TestUtil.alwaysPostingsFormat(new MemoryPostingsFormat())); break;
case 2: iwc.setCodec(_TestUtil.alwaysPostingsFormat(
new Pulsing40PostingsFormat(_TestUtil.nextInt(random(), 1, 3)))); break;
case 3: iwc.setCodec(_TestUtil.alwaysPostingsFormat(new NestedPulsingPostingsFormat())); break;
}
}
}
public void testBasic() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
Document doc = new Document();
FieldType ft = new FieldType(TextField.TYPE_UNSTORED);
ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
if (random().nextBoolean()) {
ft.setStoreTermVectors(true);
ft.setStoreTermVectorPositions(random().nextBoolean());
ft.setStoreTermVectorOffsets(random().nextBoolean());
}
Token[] tokens = new Token[] {
makeToken("a", 1, 0, 6),
makeToken("b", 1, 8, 9),
makeToken("a", 1, 9, 17),
makeToken("c", 1, 19, 50),
};
doc.add(new Field("content", new CannedTokenStream(tokens), ft));
w.addDocument(doc);
IndexReader r = w.getReader();
w.close();
DocsAndPositionsEnum dp = MultiFields.getTermPositionsEnum(r, null, "content", new BytesRef("a"), true);
assertNotNull(dp);
assertEquals(0, dp.nextDoc());
assertEquals(2, dp.freq());
assertEquals(0, dp.nextPosition());
assertEquals(0, dp.startOffset());
assertEquals(6, dp.endOffset());
assertEquals(2, dp.nextPosition());
assertEquals(9, dp.startOffset());
assertEquals(17, dp.endOffset());
assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc());
dp = MultiFields.getTermPositionsEnum(r, null, "content", new BytesRef("b"), true);
assertNotNull(dp);
assertEquals(0, dp.nextDoc());
assertEquals(1, dp.freq());
assertEquals(1, dp.nextPosition());
assertEquals(8, dp.startOffset());
assertEquals(9, dp.endOffset());
assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc());
dp = MultiFields.getTermPositionsEnum(r, null, "content", new BytesRef("c"), true);
assertNotNull(dp);
assertEquals(0, dp.nextDoc());
assertEquals(1, dp.freq());
assertEquals(3, dp.nextPosition());
assertEquals(19, dp.startOffset());
assertEquals(50, dp.endOffset());
assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc());
r.close();
dir.close();
}
public void testSkipping() throws Exception {
doTestNumbers(false);
}
public void testPayloads() throws Exception {
doTestNumbers(true);
}
public void doTestNumbers(boolean withPayloads) throws Exception {
Directory dir = newDirectory();
Analyzer analyzer = withPayloads ? new MockPayloadAnalyzer() : new MockAnalyzer(random());
iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
if (Codec.getDefault().getName().equals("Lucene40")) {
// sep etc are not implemented
switch(random().nextInt(4)) {
case 0: iwc.setCodec(_TestUtil.alwaysPostingsFormat(new Lucene40PostingsFormat())); break;
case 1: iwc.setCodec(_TestUtil.alwaysPostingsFormat(new MemoryPostingsFormat())); break;
case 2: iwc.setCodec(_TestUtil.alwaysPostingsFormat(
new Pulsing40PostingsFormat(_TestUtil.nextInt(random(), 1, 3)))); break;
case 3: iwc.setCodec(_TestUtil.alwaysPostingsFormat(new NestedPulsingPostingsFormat())); break;
}
}
iwc.setMergePolicy(newLogMergePolicy()); // will rely on docids a bit for skipping
RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
FieldType ft = new FieldType(TextField.TYPE_STORED);
ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
if (random().nextBoolean()) {
ft.setStoreTermVectors(true);
ft.setStoreTermVectorOffsets(random().nextBoolean());
ft.setStoreTermVectorPositions(random().nextBoolean());
}
int numDocs = atLeast(500);
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
doc.add(new Field("numbers", English.intToEnglish(i), ft));
doc.add(new Field("oddeven", (i % 2) == 0 ? "even" : "odd", ft));
doc.add(new StringField("id", "" + i));
w.addDocument(doc);
}
IndexReader reader = w.getReader();
w.close();
String terms[] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "hundred" };
for (String term : terms) {
DocsAndPositionsEnum dp = MultiFields.getTermPositionsEnum(reader, null, "numbers", new BytesRef(term), true);
int doc;
while((doc = dp.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
String storedNumbers = reader.document(doc).get("numbers");
int freq = dp.freq();
for (int i = 0; i < freq; i++) {
dp.nextPosition();
int start = dp.startOffset();
assert start >= 0;
int end = dp.endOffset();
assert end >= 0 && end >= start;
// check that the offsets correspond to the term in the src text
assertTrue(storedNumbers.substring(start, end).equals(term));
if (withPayloads) {
// check that we have a payload and it starts with "pos"
assertTrue(dp.hasPayload());
BytesRef payload = dp.getPayload();
assertTrue(payload.utf8ToString().startsWith("pos:"));
} // note: withPayloads=false doesnt necessarily mean we dont have them from MockAnalyzer!
}
}
}
// check we can skip correctly
int numSkippingTests = atLeast(50);
for (int j = 0; j < numSkippingTests; j++) {
int num = _TestUtil.nextInt(random(), 100, Math.min(numDocs-1, 999));
DocsAndPositionsEnum dp = MultiFields.getTermPositionsEnum(reader, null, "numbers", new BytesRef("hundred"), true);
int doc = dp.advance(num);
assertEquals(num, doc);
int freq = dp.freq();
for (int i = 0; i < freq; i++) {
String storedNumbers = reader.document(doc).get("numbers");
dp.nextPosition();
int start = dp.startOffset();
assert start >= 0;
int end = dp.endOffset();
assert end >= 0 && end >= start;
// check that the offsets correspond to the term in the src text
assertTrue(storedNumbers.substring(start, end).equals("hundred"));
if (withPayloads) {
// check that we have a payload and it starts with "pos"
assertTrue(dp.hasPayload());
BytesRef payload = dp.getPayload();
assertTrue(payload.utf8ToString().startsWith("pos:"));
} // note: withPayloads=false doesnt necessarily mean we dont have them from MockAnalyzer!
}
}
// check that other fields (without offsets) work correctly
for (int i = 0; i < numDocs; i++) {
DocsEnum dp = MultiFields.getTermDocsEnum(reader, null, "id", new BytesRef("" + i), false);
assertEquals(i, dp.nextDoc());
assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc());
}
reader.close();
dir.close();
}
public void testRandom() throws Exception {
// token -> docID -> tokens
final Map<String,Map<Integer,List<Token>>> actualTokens = new HashMap<String,Map<Integer,List<Token>>>();
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
final int numDocs = atLeast(20);
//final int numDocs = atLeast(5);
FieldType ft = new FieldType(TextField.TYPE_UNSTORED);
// TODO: randomize what IndexOptions we use; also test
// changing this up in one IW buffered segment...:
ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
if (random().nextBoolean()) {
ft.setStoreTermVectors(true);
ft.setStoreTermVectorOffsets(random().nextBoolean());
ft.setStoreTermVectorPositions(random().nextBoolean());
}
for(int docCount=0;docCount<numDocs;docCount++) {
Document doc = new Document();
doc.add(new IntField("id", docCount));
List<Token> tokens = new ArrayList<Token>();
final int numTokens = atLeast(100);
//final int numTokens = atLeast(20);
int pos = -1;
int offset = 0;
//System.out.println("doc id=" + docCount);
for(int tokenCount=0;tokenCount<numTokens;tokenCount++) {
final String text;
if (random().nextBoolean()) {
text = "a";
} else if (random().nextBoolean()) {
text = "b";
} else if (random().nextBoolean()) {
text = "c";
} else {
text = "d";
}
int posIncr = random().nextBoolean() ? 1 : random().nextInt(5);
if (tokenCount == 0 && posIncr == 0) {
posIncr = 1;
}
final int offIncr = random().nextBoolean() ? 0 : random().nextInt(5);
final int tokenOffset = random().nextInt(5);
final Token token = makeToken(text, posIncr, offset+offIncr, offset+offIncr+tokenOffset);
if (!actualTokens.containsKey(text)) {
actualTokens.put(text, new HashMap<Integer,List<Token>>());
}
final Map<Integer,List<Token>> postingsByDoc = actualTokens.get(text);
if (!postingsByDoc.containsKey(docCount)) {
postingsByDoc.put(docCount, new ArrayList<Token>());
}
postingsByDoc.get(docCount).add(token);
tokens.add(token);
pos += posIncr;
// stuff abs position into type:
token.setType(""+pos);
offset += offIncr + tokenOffset;
//System.out.println(" " + token + " posIncr=" + token.getPositionIncrement() + " pos=" + pos + " off=" + token.startOffset() + "/" + token.endOffset() + " (freq=" + postingsByDoc.get(docCount).size() + ")");
}
doc.add(new Field("content", new CannedTokenStream(tokens.toArray(new Token[tokens.size()])), ft));
w.addDocument(doc);
}
final DirectoryReader r = w.getReader();
w.close();
final String[] terms = new String[] {"a", "b", "c", "d"};
for(IndexReader reader : r.getSequentialSubReaders()) {
// TODO: improve this
AtomicReader sub = (AtomicReader) reader;
//System.out.println("\nsub=" + sub);
final TermsEnum termsEnum = sub.fields().terms("content").iterator(null);
DocsEnum docs = null;
DocsAndPositionsEnum docsAndPositions = null;
DocsAndPositionsEnum docsAndPositionsAndOffsets = null;
final int docIDToID[] = FieldCache.DEFAULT.getInts(sub, "id", false);
for(String term : terms) {
//System.out.println(" term=" + term);
if (termsEnum.seekExact(new BytesRef(term), random().nextBoolean())) {
docs = termsEnum.docs(null, docs, true);
assertNotNull(docs);
int doc;
//System.out.println(" doc/freq");
while((doc = docs.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " docID=" + doc + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docs.freq());
}
docsAndPositions = termsEnum.docsAndPositions(null, docsAndPositions, false);
assertNotNull(docsAndPositions);
//System.out.println(" doc/freq/pos");
while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docsAndPositions.freq());
for(Token token : expected) {
int pos = Integer.parseInt(token.type());
//System.out.println(" pos=" + pos);
assertEquals(pos, docsAndPositions.nextPosition());
}
}
docsAndPositionsAndOffsets = termsEnum.docsAndPositions(null, docsAndPositions, true);
assertNotNull(docsAndPositionsAndOffsets);
//System.out.println(" doc/freq/pos/offs");
while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docsAndPositions.freq());
for(Token token : expected) {
int pos = Integer.parseInt(token.type());
//System.out.println(" pos=" + pos);
assertEquals(pos, docsAndPositions.nextPosition());
assertEquals(token.startOffset(), docsAndPositions.startOffset());
assertEquals(token.endOffset(), docsAndPositions.endOffset());
}
}
}
}
// TODO: test advance:
}
r.close();
dir.close();
}
private Token makeToken(String text, int posIncr, int startOffset, int endOffset) {
final Token t = new Token();
t.append(text);
t.setPositionIncrement(posIncr);
t.setOffset(startOffset, endOffset);
return t;
}
}
| switch test over to suppresscodecs annotation
git-svn-id: 13f9c63152c129021c7e766f4ef575faaaa595a2@1343969 13f79535-47bb-0310-9956-ffa450edef68
| lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java | switch test over to suppresscodecs annotation |
|
Java | bsd-2-clause | 41eb1edcb7783ee04d0f0566c12681d4bdca36bc | 0 | laffer1/justjournal,laffer1/justjournal,laffer1/justjournal,laffer1/justjournal | package com.justjournal;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* User: laffer1
* Date: Sep 25, 2005
* Time: 9:04:00 PM
*/
public class JustJournalBaseServlet extends HttpServlet {
protected static final char endl = '\n';
/**
* Initializes the servlet.
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException {
final StringBuffer sb = new StringBuffer();
final HttpSession session = request.getSession(true);
response.setContentType("text/html");
response.setDateHeader("Expires", System.currentTimeMillis());
response.setDateHeader("Last-Modified", System.currentTimeMillis());
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.setHeader("Pragma", "no-cache");
execute(request, response, session, sb);
final ServletOutputStream outstream = response.getOutputStream();
outstream.println(sb.toString());
outstream.flush();
}
public long getLastModified(HttpServletRequest request )
{
return new java.util.Date().getTime() / 1000 * 1000;
}
protected void execute(HttpServletRequest request, HttpServletResponse response, HttpSession session, StringBuffer sb) {
}
protected String fixInput(HttpServletRequest request, String input) {
String fixed = request.getParameter(input);
if (fixed == null)
fixed = "";
return fixed.trim();
}
protected String fixHeaderInput(HttpServletRequest request, String input) {
String fixed = request.getHeader(input);
if (fixed == null)
fixed = "";
return fixed.trim();
}
}
| src/com/justjournal/JustJournalBaseServlet.java | package com.justjournal;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* User: laffer1
* Date: Sep 25, 2005
* Time: 9:04:00 PM
*/
public class JustJournalBaseServlet extends HttpServlet {
protected static final char endl = '\n';
/**
* Initializes the servlet.
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException {
final StringBuffer sb = new StringBuffer();
final HttpSession session = request.getSession(true);
response.setContentType("text/html");
response.setDateHeader("Expires", System.currentTimeMillis());
response.setDateHeader("Last-Modified", System.currentTimeMillis());
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.setHeader("Pragma", "no-cache");
execute(request, response, session, sb);
final ServletOutputStream outstream = response.getOutputStream();
outstream.println(sb.toString());
outstream.flush();
}
protected void execute(HttpServletRequest request, HttpServletResponse response, HttpSession session, StringBuffer sb) {
}
protected String fixInput(HttpServletRequest request, String input) {
String fixed = request.getParameter(input);
if (fixed == null)
fixed = "";
return fixed.trim();
}
protected String fixHeaderInput(HttpServletRequest request, String input) {
String fixed = request.getHeader(input);
if (fixed == null)
fixed = "";
return fixed.trim();
}
}
| Minor tweaks, added getLastModified
| src/com/justjournal/JustJournalBaseServlet.java | Minor tweaks, added getLastModified |
|
Java | bsd-3-clause | fccc97cdad46b217677d63472f66a94489f9e44a | 0 | JOverseer/joverseer,JOverseer/joverseer,JOverseer/joverseer | package org.joverseer.ui.listviews;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import org.jdesktop.swingx.autocomplete.ComboBoxCellEditor;
import org.joverseer.domain.Character;
import org.joverseer.domain.CharacterDeathReasonEnum;
import org.joverseer.domain.Order;
import org.joverseer.domain.PlayerInfo;
import org.joverseer.domain.PopulationCenter;
import org.joverseer.game.Game;
import org.joverseer.game.TurnElementsEnum;
import org.joverseer.metadata.GameMetadata;
import org.joverseer.metadata.orders.OrderMetadata;
import org.joverseer.support.Container;
import org.joverseer.support.GameHolder;
import org.joverseer.tools.OrderParameterValidator;
import org.joverseer.tools.OrderValidationResult;
import org.joverseer.tools.ordercheckerIntegration.OrderResult;
import org.joverseer.tools.ordercheckerIntegration.OrderResultContainer;
import org.joverseer.ui.LifecycleEventsEnum;
import org.joverseer.ui.orders.OrderVisualizationData;
import org.joverseer.ui.support.GraphicUtils;
import org.joverseer.ui.support.JOverseerEvent;
import org.joverseer.ui.support.controls.AutocompletionComboBox;
import org.joverseer.ui.support.controls.JOverseerTable;
import org.springframework.binding.value.support.ListListModel;
import org.springframework.context.ApplicationEvent;
import org.springframework.richclient.application.Application;
import org.springframework.richclient.command.ActionCommand;
import org.springframework.richclient.command.CommandGroup;
import org.springframework.richclient.list.ComboBoxListModelAdapter;
import org.springframework.richclient.list.SortedListModel;
import org.springframework.richclient.table.BeanTableModel;
import org.springframework.richclient.table.ColumnToSort;
import org.springframework.richclient.table.ShuttleSortableTableModel;
import org.springframework.richclient.table.SortOrder;
import org.springframework.richclient.table.SortableTableModel;
import org.springframework.richclient.table.TableUtils;
import org.springframework.richclient.table.renderer.BooleanTableCellRenderer;
/**
* List view that shows orders and also allows the editing of these orders It is
* also integrated with the OrderParameterValidator object to display errors in
* the orders.
*
* @author Marios Skounakis
*/
public class OrderEditorListView extends ItemListView {
ActionCommand deleteOrderAction = new DeleteOrderAction();
ActionCommand editOrderAction = new EditOrderAction();
JComboBox combo;
OrderParameterValidator validator = new OrderParameterValidator();
Color paramErrorColor = Color.decode("#ffff99");
Color paramWarningColor = Color.decode("#99ffff");
Color paramInfoColor = Color.decode("#99FF99");
HashMap<Character, Integer> characterIndices = new HashMap<Character, Integer>();
public OrderEditorListView() {
super(TurnElementsEnum.Character, OrderEditorTableModel.class);
}
@Override
protected int[] columnWidths() {
return new int[] { 32, 64, 32, 64, 80, 48, 48, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 30, 64, 64, 64 };
}
@Override
protected void setItems() {
Game g = ((GameHolder) Application.instance().getApplicationContext().getBean("gameHolder")).getGame();
if (!Game.isInitialized(g))
return;
ArrayList<Order> orders = new ArrayList<Order>();
for (Character c : g.getTurn().getCharacters()) {
boolean acceptChar = true;
for (JComboBox filter : this.filters) {
if (filter.getSelectedItem() != null) {
acceptChar = acceptChar && ((OrderFilter) filter.getSelectedItem()).acceptCharacter(c);
}
}
AbstractListViewFilter textFilter = getTextFilter(this.textFilterField.getText());
if (textFilter != null)
acceptChar = acceptChar && ((OrderFilter) textFilter).acceptCharacter(c);
if (!acceptChar)
continue;
for (int i = 0; i < c.getNumberOfOrders(); i++) {
orders.add(c.getOrders()[i]);
}
}
int row = this.table.getSelectedRow();
Object o = null;
try {
o = this.tableModel.getRow(row); // get the object for this row
} catch (Exception e) {
// do nothing
}
int column = this.table.getSelectedColumn();
this.tableModel.setRows(orders);
this.characterIndices.clear();
try {
if (o != null && o.equals(this.tableModel.getRow(row))) {
// if row is still showing same order, keep selection
this.table.setRowSelectionInterval(row, row);
this.table.setColumnSelectionInterval(column, column);
}
} catch (Exception e) {
// do nothing
}
}
private ArrayList<OrderFilter> createOrderTypeFilterList() {
ArrayList<OrderFilter> filterList = new ArrayList<OrderFilter>();
OrderFilter f = new OrderFilter("All") {
@Override
public boolean acceptCharacter(Character c) {
return true;
}
};
filterList.add(f);
f = new OrderFilter("Commanders (C>0)") {
@Override
public boolean acceptCharacter(Character c) {
return c.getCommander() > 0;
}
};
filterList.add(f);
f = new OrderFilter("Agent (A>0)") {
@Override
public boolean acceptCharacter(Character c) {
return c.getAgent() > 0;
}
};
filterList.add(f);
f = new OrderFilter("Emissaries (E>0)") {
@Override
public boolean acceptCharacter(Character c) {
return c.getEmmisary() > 0;
}
};
filterList.add(f);
f = new OrderFilter("Mages (M>0)") {
@Override
public boolean acceptCharacter(Character c) {
return c.getMage() > 0;
}
};
filterList.add(f);
if (GameHolder.hasInitializedGame()) {
Game g = GameHolder.instance().getGame();
GameMetadata gm = g.getMetadata();
for (int i = 1; i < 26; i++) {
PlayerInfo pi = (PlayerInfo) g.getTurn().getContainer(TurnElementsEnum.PlayerInfo).findFirstByProperty("nationNo", i);
if (pi == null)
continue;
f = new OrderFilter(gm.getNationByNum(i).getName()) {
@Override
public boolean acceptCharacter(Character c) {
Game g1 = GameHolder.instance().getGame();
GameMetadata gm1 = g1.getMetadata();
return c.getDeathReason().equals(CharacterDeathReasonEnum.NotDead) && c.getX() > 0 && gm1.getNationByNum(c.getNationNo()).getName().equals(getDescription());
}
};
filterList.add(f);
}
}
f = new OrderFilter("Army/Navy Movement") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "830,840,850,860");
}
};
filterList.add(f);
f = new OrderFilter("Char/Comp Movement") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "810,820,870,825");
}
};
filterList.add(f);
f = new OrderFilter("Recon/Scout/Palantir") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "925,905,910,915,920,925,930,935");
}
};
filterList.add(f);
f = new OrderFilter("Product Transfers") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "947,948");
}
};
filterList.add(f);
f = new OrderFilter("Gold Transfers") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasGoldTransferOrder(c);
}
};
filterList.add(f);
f = new OrderFilter("Character Naming") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "725,728,731,734,737");
}
};
filterList.add(f);
f = new OrderFilter("Lore Spells") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "940");
}
};
filterList.add(f);
f = new OrderFilter("Combat") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "230,235,240,250,255,498");
}
};
filterList.add(f);
return filterList;
}
protected boolean characterHasOrderInList(Character c, String orderList) {
String[] parts = orderList.split(",");
for (String p : parts) {
int orderNo = Integer.parseInt(p);
for (Order o : c.getOrders()) {
if (o.getOrderNo() == orderNo)
return true;
}
}
return false;
}
protected boolean characterHasGoldTransferOrder(Character c) {
for (Order o : c.getOrders()) {
if (o.getOrderNo() == 948) {
if ("go".equals(o.getP2())) {
return true;
}
}
}
return false;
}
private ArrayList<OrderFilter> createOrderNationFilterList() {
ArrayList<OrderFilter> filterList = new ArrayList<OrderFilter>();
OrderFilter f = new OrderFilter("All characters with orders") {
@Override
public boolean acceptCharacter(Character c) {
return c.getDeathReason().equals(CharacterDeathReasonEnum.NotDead) && c.getX() > 0 && (!c.getOrders()[0].isBlank() || !c.getOrders()[1].isBlank()|| !c.getOrders()[2].isBlank());
}
};
filterList.add(f);
f = new OrderFilter("Characters without all orders") {
@Override
public boolean acceptCharacter(Character c) {
if (!GameHolder.hasInitializedGame())
return false;
PlayerInfo pi = (PlayerInfo) GameHolder.instance().getGame().getTurn().getContainer(TurnElementsEnum.PlayerInfo).findFirstByProperty("nationNo", c.getNationNo());
return pi != null && c.getDeathReason().equals(CharacterDeathReasonEnum.NotDead) && c.getX() > 0 && (c.getOrders()[0].isBlank() || c.getOrders()[1].isBlank()|| !c.getOrders()[2].isBlank());
}
};
filterList.add(f);
f = new OrderFilter("All Imported") {
@Override
public boolean acceptCharacter(Character c) {
if (!GameHolder.hasInitializedGame())
return false;
PlayerInfo pi = (PlayerInfo) GameHolder.instance().getGame().getTurn().getContainer(TurnElementsEnum.PlayerInfo).findFirstByProperty("nationNo", c.getNationNo());
return pi != null && c.getDeathReason().equals(CharacterDeathReasonEnum.NotDead) && c.getX() > 0;
}
};
filterList.add(f);
if (GameHolder.hasInitializedGame()) {
Game g = GameHolder.instance().getGame();
GameMetadata gm = g.getMetadata();
for (int i = 1; i < 26; i++) {
PlayerInfo pi = (PlayerInfo) g.getTurn().getContainer(TurnElementsEnum.PlayerInfo).findFirstByProperty("nationNo", i);
if (pi == null)
continue;
f = new OrderFilter(gm.getNationByNum(i).getName()) {
@Override
public boolean acceptCharacter(Character c) {
Game g1 = GameHolder.instance().getGame();
GameMetadata gm1 = g1.getMetadata();
return c.getDeathReason().equals(CharacterDeathReasonEnum.NotDead) && c.getX() > 0 && gm1.getNationByNum(c.getNationNo()).getName().equals(getDescription());
}
};
filterList.add(f);
}
}
return filterList;
}
@Override
protected AbstractListViewFilter[][] getFilters() {
return new AbstractListViewFilter[][] { createOrderNationFilterList().toArray(new AbstractListViewFilter[] {}), createOrderTypeFilterList().toArray(new AbstractListViewFilter[] {}), };
}
@Override
protected boolean hasTextFilter() {
return true;
}
@Override
protected AbstractListViewFilter getTextFilter(String txt) {
if (txt == null || txt.length() == 0)
return null;
boolean isHexNo = false;
try {
if (txt.length() == 4 && Integer.parseInt(txt) > 0) {
isHexNo = true;
}
} catch (Exception e) {
}
if (isHexNo)
return new OrderHexFilter("Hex", txt);
return new OrderTextFilter("Text", txt);
}
@Override
protected JTable createTable() {
JTable table1 = TableUtils.createStandardSortableTable(this.tableModel);
JTable newTable = new JOverseerTable(table1.getModel()) {
Color selectionBackground = (Color) UIManager.get("Table.selectionBackground");
Color normalBackground = (Color) UIManager.get("Table.background");
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
if (isCellSelected(row, column)) {
if (!c.getBackground().equals(OrderEditorListView.this.paramErrorColor) && !c.getBackground().equals(OrderEditorListView.this.paramWarningColor) && !c.getBackground().equals(OrderEditorListView.this.paramInfoColor)) {
c.setBackground(this.selectionBackground);
}
} else {
if (!c.getBackground().equals(OrderEditorListView.this.paramErrorColor) && !c.getBackground().equals(OrderEditorListView.this.paramWarningColor) && !c.getBackground().equals(OrderEditorListView.this.paramInfoColor)) {
if (OrderEditorListView.this.characterIndices.size() == 0) {
Character current = null;
int charIndex = -1;
for (int i = 0; i < this.getRowCount(); i++) {
int rowI = ((ShuttleSortableTableModel) this.getModel()).convertSortedIndexToDataIndex(i);
Order order = (Order) OrderEditorListView.this.tableModel.getRow(rowI);
Character oc = order.getCharacter();
if (!oc.equals(current)) {
current = oc;
charIndex++;
OrderEditorListView.this.characterIndices.put(oc, charIndex);
}
}
}
int rowI = ((ShuttleSortableTableModel) this.getModel()).convertSortedIndexToDataIndex(row);
Order order = (Order) OrderEditorListView.this.tableModel.getRow(rowI);
int charIndex = OrderEditorListView.this.characterIndices.get(order.getCharacter());
if (charIndex % 2 == 1) {
c.setBackground(Color.decode("#efefef"));
} else {
c.setBackground(this.normalBackground);
}
}
}
return c;
}
};
newTable.setColumnModel(table1.getColumnModel());
newTable.setAutoResizeMode(table1.getAutoResizeMode());
table1 = null;
return newTable;
}
@Override
protected JComponent createControlImpl() {
JComponent tableComp = super.createControlImpl();
// TableLayoutBuilder tlb = new TableLayoutBuilder();
// tlb.cell(combo = new JComboBox(), "align=left");
// combo.setPreferredSize(new Dimension(200, 24));
// combo.addActionListener(new ActionListener() {
//
// public void actionPerformed(ActionEvent e) {
// setItems();
// }
// });
GraphicUtils.setTableColumnRenderer(this.table, OrderEditorTableModel.iDraw, new BooleanTableCellRenderer() {
Color selectionBackground = (Color) UIManager.get("Table.selectionBackground");
Color normalBackground = (Color) UIManager.get("Table.background");
// specialized renderer for rendering the "Draw" column
// it is rendered with a check box
// and shown only when appropriate
@Override
public Component getTableCellRendererComponent(JTable table1, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
try {
Order o = (Order) OrderEditorListView.this.tableModel.getRow(((SortableTableModel) table1.getModel()).convertSortedIndexToDataIndex(row));
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, "", isSelected, hasFocus, row, column);
if (GraphicUtils.canRenderOrder(o)) {
JCheckBox b = new JCheckBox();
b.setSelected((Boolean) value);
b.setHorizontalAlignment(SwingConstants.CENTER);
System.out.println("row == table.getSelectedRow() = " + String.valueOf(row == table1.getSelectedRow()));
System.out.println("isSelected = " + String.valueOf(isSelected));
b.setBackground(row == table1.getSelectedRow() && isSelected ? this.selectionBackground : this.normalBackground);
return b;
} else {
return lbl;
}
} catch (Exception exc) {
// do nothing
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, "", isSelected, hasFocus, row, column);
return lbl;
}
}
});
// specialized renderer for the icon returned by the orderResultType
// virtual field
GraphicUtils.setTableColumnRenderer(this.table, OrderEditorTableModel.iResults, new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table1, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
try {
ImageIcon ico = (ImageIcon) value;
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, "", isSelected, hasFocus, row, column);
lbl.setIcon(ico);
if (ico != null) {
OrderResultContainer container = (OrderResultContainer) Application.instance().getApplicationContext().getBean("orderResultContainer");
int idx = ((SortableTableModel) table1.getModel()).convertSortedIndexToDataIndex(row);
Object obj = OrderEditorListView.this.tableModel.getRow(idx);
Order o = (Order) obj;
String txt = "";
for (OrderResult result : container.getResultsForOrder(o)) {
txt += (txt.equals("") ? "" : "") + "<li>" + result.getType().toString() + ": " + result.getMessage() + "</li>";
}
txt = "<html><body><lu>" + txt + "</lu></body></html>";
lbl.setToolTipText(txt);
}
lbl.setHorizontalAlignment(SwingConstants.CENTER);
return lbl;
} catch (Exception exc) {
// do nothing
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, "", isSelected, hasFocus, row, column);
return lbl;
}
}
});
// renderer for hex - boldify capital hex
GraphicUtils.setTableColumnRenderer(this.table, OrderEditorTableModel.iHexNo, new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table1, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
try {
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, value, isSelected, hasFocus, row, column);
// find capital and compare
int idx = ((SortableTableModel) table1.getModel()).convertSortedIndexToDataIndex(row);
Object obj = OrderEditorListView.this.tableModel.getRow(idx);
Order o = (Order) obj;
Character c = o.getCharacter();
PopulationCenter capital = (PopulationCenter) GameHolder.instance().getGame().getTurn().getContainer(TurnElementsEnum.PopulationCenter).findFirstByProperties(new String[] { "nationNo", "capital" }, new Object[] { c.getNationNo(), Boolean.TRUE });
if (capital != null && c.getHexNo() == capital.getHexNo()) {
lbl.setFont(GraphicUtils.getFont(lbl.getFont().getName(), Font.BOLD, lbl.getFont().getSize()));
}
lbl.setHorizontalAlignment(SwingConstants.CENTER);
return lbl;
} catch (Exception exc) {
// do nothing
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, "", isSelected, hasFocus, row, column);
return lbl;
}
};
});
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table1, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, value, isSelected, hasFocus, row, column);
lbl.setHorizontalAlignment(SwingConstants.CENTER);
return lbl;
};
};
// render stats - center alignment
GraphicUtils.setTableColumnRenderer(this.table, OrderEditorTableModel.iStats, centerRenderer);
for (int i = OrderEditorTableModel.iParamStart; i <= OrderEditorTableModel.iParamEnd; i++) {
GraphicUtils.setTableColumnRenderer(this.table, i, new OrderParameterCellRenderer(i - OrderEditorTableModel.iParamStart));
}
GraphicUtils.setTableColumnRenderer(this.table, OrderEditorTableModel.iNoAndCode, new OrderNumberCellRenderer());
// tlb.row();
// tlb.cell(tableComp);
// tlb.row();
// return tlb.getPanel();
return tableComp;
}
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
if (applicationEvent instanceof JOverseerEvent) {
JOverseerEvent e = (JOverseerEvent) applicationEvent;
if (e.getEventType().equals(LifecycleEventsEnum.SelectedTurnChangedEvent.toString())) {
refreshFilters();
setItems();
} else if (e.getEventType().equals(LifecycleEventsEnum.SelectedHexChangedEvent.toString())) {
setItems();
} else if (e.getEventType().equals(LifecycleEventsEnum.GameChangedEvent.toString())) {
// setFilters();
refreshFilters();
TableColumn noAndCodeColumn = this.table.getColumnModel().getColumn(OrderEditorTableModel.iNoAndCode);
Game g = ((GameHolder) Application.instance().getApplicationContext().getBean("gameHolder")).getGame();
ListListModel orders = new ListListModel();
orders.add(Order.NA);
if (Game.isInitialized(g)) {
GameMetadata gm = g.getMetadata();
Container<OrderMetadata> orderMetadata = gm.getOrders();
for (OrderMetadata om : orderMetadata) {
orders.add(om.getNumber() + " " + om.getCode());
}
}
SortedListModel slm = new SortedListModel(orders);
// ComboBox Editor for the order number
final JComboBox comboBox = new AutocompletionComboBox(new ComboBoxListModelAdapter(slm));
comboBox.setEditable(true);
comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
final ComboBoxCellEditor editor = new ComboBoxCellEditor(comboBox);
noAndCodeColumn.setCellEditor(editor);
editor.addCellEditorListener(new CellEditorListener() {
@Override
public void editingCanceled(ChangeEvent e1) {
OrderEditorListView.this.table.requestFocus();
}
@Override
public void editingStopped(ChangeEvent e1) {
OrderEditorListView.this.table.requestFocus();
}
});
comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == KeyEvent.VK_ESCAPE) {
editor.cancelCellEditing();
arg0.consume();
}
}
});
setItems();
} else if (e.getEventType().equals(LifecycleEventsEnum.OrderChangedEvent.toString())) {
// setItems();
} else if (e.getEventType().equals(LifecycleEventsEnum.RefreshMapItems.toString())) {
setItems();
} else if (e.getEventType().equals(LifecycleEventsEnum.RefreshOrders.toString())) {
setItems();
}
}
}
@Override
public JPopupMenu getPopupMenu(boolean hasSelectedItem) {
if (!hasSelectedItem)
return null;
CommandGroup group = Application.instance().getActiveWindow().getCommandManager().createCommandGroup("orderCommandGroup", new Object[] { this.editOrderAction, this.deleteOrderAction,
// sendOrderByChatAction,
"separator", new DrawAllOrdersAction(), new UnDrawAllOrdersAction(),
// new SendAllOrdersByChatAction()
});
return group.createPopupMenu();
}
/**
* Edit the selected order
*
* @author Marios Skounakis
*/
private class EditOrderAction extends ActionCommand {
@Override
protected void doExecuteCommand() {
int row = OrderEditorListView.this.table.getSelectedRow();
if (row >= 0) {
int idx = ((SortableTableModel) OrderEditorListView.this.table.getModel()).convertSortedIndexToDataIndex(row);
if (idx >= OrderEditorListView.this.tableModel.getRowCount())
return;
try {
Object obj = OrderEditorListView.this.tableModel.getRow(idx);
Order order = (Order) obj;
Application.instance().getApplicationContext().publishEvent(new JOverseerEvent(LifecycleEventsEnum.EditOrderEvent.toString(), order, this));
} catch (Exception exc) {
}
}
}
}
/**
* Delete the selected order
*
* @author Marios Skounakis
*/
private class DeleteOrderAction extends ActionCommand {
@Override
protected void doExecuteCommand() {
int row = OrderEditorListView.this.table.getSelectedRow();
if (row >= 0) {
int idx = ((SortableTableModel) OrderEditorListView.this.table.getModel()).convertSortedIndexToDataIndex(row);
if (idx >= OrderEditorListView.this.tableModel.getRowCount())
return;
try {
Object obj = OrderEditorListView.this.tableModel.getRow(idx);
Order order = (Order) obj;
order.clear();
((BeanTableModel) OrderEditorListView.this.table.getModel()).fireTableDataChanged();
Application.instance().getApplicationContext().publishEvent(new JOverseerEvent(LifecycleEventsEnum.OrderChangedEvent.toString(), order, this));
} catch (Exception exc) {
System.out.println(exc);
}
}
}
}
/**
* Set Draw = true for all orders in the list view
*
* @author Marios Skounakis
*/
private class DrawAllOrdersAction extends ActionCommand {
@Override
protected void doExecuteCommand() {
OrderVisualizationData ovd = (OrderVisualizationData) Application.instance().getApplicationContext().getBean("orderVisualizationData");
for (Object o : OrderEditorListView.this.tableModel.getRows()) {
Order order = (Order) o;
if (GraphicUtils.canRenderOrder(order)) {
ovd.addOrder(order);
}
}
Application.instance().getApplicationContext().publishEvent(new JOverseerEvent(LifecycleEventsEnum.RefreshMapItems.toString(), this, this));
}
}
/**
* Set Draw = false for all orders in the list view
*
* @author Marios Skounakis
*/
private class UnDrawAllOrdersAction extends ActionCommand {
@Override
protected void doExecuteCommand() {
OrderVisualizationData ovd = (OrderVisualizationData) Application.instance().getApplicationContext().getBean("orderVisualizationData");
ovd.clear();
Application.instance().getApplicationContext().publishEvent(new JOverseerEvent(LifecycleEventsEnum.RefreshMapItems.toString(), this, this));
}
}
/**
* Generic Order filter
*
* @author Marios Skounakis
*/
private abstract class OrderFilter extends AbstractListViewFilter {
public abstract boolean acceptCharacter(Character c);
// dummy, basically ignored
@Override
public boolean accept(Object o) {
return true;
}
public OrderFilter(String description) {
super(description);
}
}
public class OrderHexFilter extends OrderFilter {
String hexNo;
public OrderHexFilter(String description, String hexNo) {
super(description);
this.hexNo = hexNo;
}
@Override
public boolean acceptCharacter(Character c) {
for (Order o : c.getOrders()) {
if (o.isBlank())
continue;
for (int i = 0; i <= o.getLastParamIndex(); i++) {
if (o.getParameter(i).equals(this.hexNo))
return true;
}
}
return false;
}
}
public class OrderTextFilter extends OrderFilter {
String text;
public OrderTextFilter(String description, String text) {
super(description);
this.text = text;
}
@Override
public boolean acceptCharacter(Character c) {
for (Order o : c.getOrders()) {
if (o.isBlank())
continue;
for (int i = 0; i <= o.getLastParamIndex(); i++) {
if (o.getParameter(i).contains(this.text))
return true;
}
}
return false;
}
}
@Override
public ColumnToSort[] getDefaultSort() {
// set comparator to sort using the character ids
((SortableTableModel) this.table.getModel()).setComparator(1, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1 != null && o2 != null) {
return Character.getIdFromName(o1).compareTo(Character.getIdFromName(o2));
}
return 0;
}
});
return new ColumnToSort[] { new ColumnToSort(0, 0, SortOrder.ASCENDING), new ColumnToSort(0, 1, SortOrder.ASCENDING) };
}
/**
* Cell renderer for the order parameters - Changes the background to
* erroneous parameters - Shows a tooltip with the error message
*
* @author Marios Skounakis
*/
class OrderParameterCellRenderer extends DefaultTableCellRenderer {
int paramNo;
Color selectionBackground = (Color) UIManager.get("Table.selectionBackground");
Color normalBackground = (Color) UIManager.get("Table.background");
private OrderParameterCellRenderer(int paramNo) {
super();
this.paramNo = paramNo;
}
@Override
public Component getTableCellRendererComponent(JTable table1, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, value, isSelected, hasFocus, row, column);
int idx = ((SortableTableModel) table1.getModel()).convertSortedIndexToDataIndex(row);
Object obj = OrderEditorListView.this.tableModel.getRow(idx);
Order o = (Order) obj;
OrderValidationResult res = null;
// TODO handle larger paramNos
if (this.paramNo < 9) {
res = OrderEditorListView.this.validator.checkParam(o, this.paramNo);
}
if (res != null) {
if (isSelected) {
lbl.setBackground(this.selectionBackground);
} else if (res.getLevel() == OrderValidationResult.ERROR) {
lbl.setBackground(OrderEditorListView.this.paramErrorColor);
} else if (res.getLevel() == OrderValidationResult.WARNING) {
lbl.setBackground(OrderEditorListView.this.paramWarningColor);
} else if (res.getLevel() == OrderValidationResult.INFO) {
lbl.setBackground(OrderEditorListView.this.paramInfoColor);
}
lbl.setToolTipText(res.getMessage());
} else {
if (isSelected) {
lbl.setBackground(this.selectionBackground);
} else {
lbl.setBackground(this.normalBackground);
}
lbl.setToolTipText(null);
}
return lbl;
}
}
/**
* Renderer for the order number - Changes the background to erroneous
* orders - Shows a tooltip with the error message
*
* @author Marios Skounakis
*/
class OrderNumberCellRenderer extends DefaultTableCellRenderer {
Color selectionBackground = (Color) UIManager.get("Table.selectionBackground");
Color normalBackground = (Color) UIManager.get("Table.background");
private OrderNumberCellRenderer() {
super();
}
@Override
public Component getTableCellRendererComponent(JTable table1, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, value, isSelected, hasFocus, row, column);
int idx = ((SortableTableModel) table1.getModel()).convertSortedIndexToDataIndex(row);
Object obj = OrderEditorListView.this.tableModel.getRow(idx);
Order o = (Order) obj;
OrderValidationResult res = OrderEditorListView.this.validator.checkOrder(o);
if (res != null) {
if (isSelected) {
lbl.setBackground(this.selectionBackground);
} else if (res.getLevel() == OrderValidationResult.ERROR) {
lbl.setBackground(OrderEditorListView.this.paramErrorColor);
} else if (res.getLevel() == OrderValidationResult.WARNING) {
lbl.setBackground(OrderEditorListView.this.paramWarningColor);
} else if (res.getLevel() == OrderValidationResult.INFO) {
lbl.setBackground(OrderEditorListView.this.paramInfoColor);
}
lbl.setToolTipText(res.getMessage());
} else {
if (isSelected) {
lbl.setBackground(this.selectionBackground);
} else {
lbl.setBackground(this.normalBackground);
}
lbl.setToolTipText(null);
}
return lbl;
}
}
}
| joverseerjar/src/org/joverseer/ui/listviews/OrderEditorListView.java | package org.joverseer.ui.listviews;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import org.jdesktop.swingx.autocomplete.ComboBoxCellEditor;
import org.joverseer.domain.Character;
import org.joverseer.domain.CharacterDeathReasonEnum;
import org.joverseer.domain.Order;
import org.joverseer.domain.PlayerInfo;
import org.joverseer.domain.PopulationCenter;
import org.joverseer.game.Game;
import org.joverseer.game.TurnElementsEnum;
import org.joverseer.metadata.GameMetadata;
import org.joverseer.metadata.orders.OrderMetadata;
import org.joverseer.support.Container;
import org.joverseer.support.GameHolder;
import org.joverseer.tools.OrderParameterValidator;
import org.joverseer.tools.OrderValidationResult;
import org.joverseer.tools.ordercheckerIntegration.OrderResult;
import org.joverseer.tools.ordercheckerIntegration.OrderResultContainer;
import org.joverseer.ui.LifecycleEventsEnum;
import org.joverseer.ui.orders.OrderVisualizationData;
import org.joverseer.ui.support.GraphicUtils;
import org.joverseer.ui.support.JOverseerEvent;
import org.joverseer.ui.support.controls.AutocompletionComboBox;
import org.joverseer.ui.support.controls.JOverseerTable;
import org.springframework.binding.value.support.ListListModel;
import org.springframework.context.ApplicationEvent;
import org.springframework.richclient.application.Application;
import org.springframework.richclient.command.ActionCommand;
import org.springframework.richclient.command.CommandGroup;
import org.springframework.richclient.list.ComboBoxListModelAdapter;
import org.springframework.richclient.list.SortedListModel;
import org.springframework.richclient.table.BeanTableModel;
import org.springframework.richclient.table.ColumnToSort;
import org.springframework.richclient.table.ShuttleSortableTableModel;
import org.springframework.richclient.table.SortOrder;
import org.springframework.richclient.table.SortableTableModel;
import org.springframework.richclient.table.TableUtils;
import org.springframework.richclient.table.renderer.BooleanTableCellRenderer;
/**
* List view that shows orders and also allows the editing of these orders It is
* also integrated with the OrderParameterValidator object to display errors in
* the orders.
*
* @author Marios Skounakis
*/
public class OrderEditorListView extends ItemListView {
ActionCommand deleteOrderAction = new DeleteOrderAction();
ActionCommand editOrderAction = new EditOrderAction();
JComboBox combo;
OrderParameterValidator validator = new OrderParameterValidator();
Color paramErrorColor = Color.decode("#ffff99");
Color paramWarningColor = Color.decode("#99ffff");
Color paramInfoColor = Color.decode("#99FF99");
HashMap<Character, Integer> characterIndices = new HashMap<Character, Integer>();
public OrderEditorListView() {
super(TurnElementsEnum.Character, OrderEditorTableModel.class);
}
@Override
protected int[] columnWidths() {
return new int[] { 32, 64, 32, 64, 80, 48, 48, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 30, 64, 64, 64 };
}
@Override
protected void setItems() {
Game g = ((GameHolder) Application.instance().getApplicationContext().getBean("gameHolder")).getGame();
if (!Game.isInitialized(g))
return;
ArrayList<Order> orders = new ArrayList<Order>();
for (Character c : g.getTurn().getCharacters()) {
boolean acceptChar = true;
for (JComboBox filter : this.filters) {
if (filter.getSelectedItem() != null) {
acceptChar = acceptChar && ((OrderFilter) filter.getSelectedItem()).acceptCharacter(c);
}
}
AbstractListViewFilter textFilter = getTextFilter(this.textFilterField.getText());
if (textFilter != null)
acceptChar = acceptChar && ((OrderFilter) textFilter).acceptCharacter(c);
if (!acceptChar)
continue;
for (int i = 0; i < c.getNumberOfOrders(); i++) {
orders.add(c.getOrders()[i]);
}
}
int row = this.table.getSelectedRow();
Object o = null;
try {
o = this.tableModel.getRow(row); // get the object for this row
} catch (Exception e) {
// do nothing
}
int column = this.table.getSelectedColumn();
this.tableModel.setRows(orders);
this.characterIndices.clear();
try {
if (o != null && o.equals(this.tableModel.getRow(row))) {
// if row is still showing same order, keep selection
this.table.setRowSelectionInterval(row, row);
this.table.setColumnSelectionInterval(column, column);
}
} catch (Exception e) {
// do nothing
}
}
private ArrayList<OrderFilter> createOrderTypeFilterList() {
ArrayList<OrderFilter> filterList = new ArrayList<OrderFilter>();
OrderFilter f = new OrderFilter("All") {
@Override
public boolean acceptCharacter(Character c) {
return true;
}
};
filterList.add(f);
f = new OrderFilter("Emissaries (E>=30)") {
@Override
public boolean acceptCharacter(Character c) {
return c.getEmmisary() >= 30;
}
};
filterList.add(f);
f = new OrderFilter("Agent (A>=30)") {
@Override
public boolean acceptCharacter(Character c) {
return c.getAgent() >= 30;
}
};
filterList.add(f);
f = new OrderFilter("Army/Navy Movement") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "830,840,850,860");
}
};
filterList.add(f);
f = new OrderFilter("Char/Comp Movement") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "810,820,870,825");
}
};
filterList.add(f);
f = new OrderFilter("Recon/Scout/Palantir") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "925,905,910,915,920,925,930,935");
}
};
filterList.add(f);
f = new OrderFilter("Product Transfers") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "947,948");
}
};
filterList.add(f);
f = new OrderFilter("Gold Transfers") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasGoldTransferOrder(c);
}
};
filterList.add(f);
f = new OrderFilter("Character Naming") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "725,728,731,734,737");
}
};
filterList.add(f);
f = new OrderFilter("Lore Spells") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "940");
}
};
filterList.add(f);
f = new OrderFilter("Combat") {
@Override
public boolean acceptCharacter(Character c) {
return characterHasOrderInList(c, "230,235,240,250,255,498");
}
};
filterList.add(f);
return filterList;
}
protected boolean characterHasOrderInList(Character c, String orderList) {
String[] parts = orderList.split(",");
for (String p : parts) {
int orderNo = Integer.parseInt(p);
for (Order o : c.getOrders()) {
if (o.getOrderNo() == orderNo)
return true;
}
}
return false;
}
protected boolean characterHasGoldTransferOrder(Character c) {
for (Order o : c.getOrders()) {
if (o.getOrderNo() == 948) {
if ("go".equals(o.getP2())) {
return true;
}
}
}
return false;
}
private ArrayList<OrderFilter> createOrderNationFilterList() {
ArrayList<OrderFilter> filterList = new ArrayList<OrderFilter>();
OrderFilter f = new OrderFilter("All characters with orders") {
@Override
public boolean acceptCharacter(Character c) {
return c.getDeathReason().equals(CharacterDeathReasonEnum.NotDead) && c.getX() > 0 && (!c.getOrders()[0].isBlank() || !c.getOrders()[1].isBlank()|| !c.getOrders()[2].isBlank());
}
};
filterList.add(f);
f = new OrderFilter("Characters without all orders") {
@Override
public boolean acceptCharacter(Character c) {
if (!GameHolder.hasInitializedGame())
return false;
PlayerInfo pi = (PlayerInfo) GameHolder.instance().getGame().getTurn().getContainer(TurnElementsEnum.PlayerInfo).findFirstByProperty("nationNo", c.getNationNo());
return pi != null && c.getDeathReason().equals(CharacterDeathReasonEnum.NotDead) && c.getX() > 0 && (c.getOrders()[0].isBlank() || c.getOrders()[1].isBlank()|| !c.getOrders()[2].isBlank());
}
};
filterList.add(f);
f = new OrderFilter("All Imported") {
@Override
public boolean acceptCharacter(Character c) {
if (!GameHolder.hasInitializedGame())
return false;
PlayerInfo pi = (PlayerInfo) GameHolder.instance().getGame().getTurn().getContainer(TurnElementsEnum.PlayerInfo).findFirstByProperty("nationNo", c.getNationNo());
return pi != null && c.getDeathReason().equals(CharacterDeathReasonEnum.NotDead) && c.getX() > 0;
}
};
filterList.add(f);
if (GameHolder.hasInitializedGame()) {
Game g = GameHolder.instance().getGame();
GameMetadata gm = g.getMetadata();
for (int i = 1; i < 26; i++) {
PlayerInfo pi = (PlayerInfo) g.getTurn().getContainer(TurnElementsEnum.PlayerInfo).findFirstByProperty("nationNo", i);
if (pi == null)
continue;
f = new OrderFilter(gm.getNationByNum(i).getName()) {
@Override
public boolean acceptCharacter(Character c) {
Game g1 = GameHolder.instance().getGame();
GameMetadata gm1 = g1.getMetadata();
return c.getDeathReason().equals(CharacterDeathReasonEnum.NotDead) && c.getX() > 0 && gm1.getNationByNum(c.getNationNo()).getName().equals(getDescription());
}
};
filterList.add(f);
}
}
return filterList;
}
@Override
protected AbstractListViewFilter[][] getFilters() {
return new AbstractListViewFilter[][] { createOrderNationFilterList().toArray(new AbstractListViewFilter[] {}), createOrderTypeFilterList().toArray(new AbstractListViewFilter[] {}), };
}
@Override
protected boolean hasTextFilter() {
return true;
}
@Override
protected AbstractListViewFilter getTextFilter(String txt) {
if (txt == null || txt.length() == 0)
return null;
boolean isHexNo = false;
try {
if (txt.length() == 4 && Integer.parseInt(txt) > 0) {
isHexNo = true;
}
} catch (Exception e) {
}
if (isHexNo)
return new OrderHexFilter("Hex", txt);
return new OrderTextFilter("Text", txt);
}
@Override
protected JTable createTable() {
JTable table1 = TableUtils.createStandardSortableTable(this.tableModel);
JTable newTable = new JOverseerTable(table1.getModel()) {
Color selectionBackground = (Color) UIManager.get("Table.selectionBackground");
Color normalBackground = (Color) UIManager.get("Table.background");
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
if (isCellSelected(row, column)) {
if (!c.getBackground().equals(OrderEditorListView.this.paramErrorColor) && !c.getBackground().equals(OrderEditorListView.this.paramWarningColor) && !c.getBackground().equals(OrderEditorListView.this.paramInfoColor)) {
c.setBackground(this.selectionBackground);
}
} else {
if (!c.getBackground().equals(OrderEditorListView.this.paramErrorColor) && !c.getBackground().equals(OrderEditorListView.this.paramWarningColor) && !c.getBackground().equals(OrderEditorListView.this.paramInfoColor)) {
if (OrderEditorListView.this.characterIndices.size() == 0) {
Character current = null;
int charIndex = -1;
for (int i = 0; i < this.getRowCount(); i++) {
int rowI = ((ShuttleSortableTableModel) this.getModel()).convertSortedIndexToDataIndex(i);
Order order = (Order) OrderEditorListView.this.tableModel.getRow(rowI);
Character oc = order.getCharacter();
if (!oc.equals(current)) {
current = oc;
charIndex++;
OrderEditorListView.this.characterIndices.put(oc, charIndex);
}
}
}
int rowI = ((ShuttleSortableTableModel) this.getModel()).convertSortedIndexToDataIndex(row);
Order order = (Order) OrderEditorListView.this.tableModel.getRow(rowI);
int charIndex = OrderEditorListView.this.characterIndices.get(order.getCharacter());
if (charIndex % 2 == 1) {
c.setBackground(Color.decode("#efefef"));
} else {
c.setBackground(this.normalBackground);
}
}
}
return c;
}
};
newTable.setColumnModel(table1.getColumnModel());
newTable.setAutoResizeMode(table1.getAutoResizeMode());
table1 = null;
return newTable;
}
@Override
protected JComponent createControlImpl() {
JComponent tableComp = super.createControlImpl();
// TableLayoutBuilder tlb = new TableLayoutBuilder();
// tlb.cell(combo = new JComboBox(), "align=left");
// combo.setPreferredSize(new Dimension(200, 24));
// combo.addActionListener(new ActionListener() {
//
// public void actionPerformed(ActionEvent e) {
// setItems();
// }
// });
GraphicUtils.setTableColumnRenderer(this.table, OrderEditorTableModel.iDraw, new BooleanTableCellRenderer() {
Color selectionBackground = (Color) UIManager.get("Table.selectionBackground");
Color normalBackground = (Color) UIManager.get("Table.background");
// specialized renderer for rendering the "Draw" column
// it is rendered with a check box
// and shown only when appropriate
@Override
public Component getTableCellRendererComponent(JTable table1, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
try {
Order o = (Order) OrderEditorListView.this.tableModel.getRow(((SortableTableModel) table1.getModel()).convertSortedIndexToDataIndex(row));
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, "", isSelected, hasFocus, row, column);
if (GraphicUtils.canRenderOrder(o)) {
JCheckBox b = new JCheckBox();
b.setSelected((Boolean) value);
b.setHorizontalAlignment(SwingConstants.CENTER);
System.out.println("row == table.getSelectedRow() = " + String.valueOf(row == table1.getSelectedRow()));
System.out.println("isSelected = " + String.valueOf(isSelected));
b.setBackground(row == table1.getSelectedRow() && isSelected ? this.selectionBackground : this.normalBackground);
return b;
} else {
return lbl;
}
} catch (Exception exc) {
// do nothing
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, "", isSelected, hasFocus, row, column);
return lbl;
}
}
});
// specialized renderer for the icon returned by the orderResultType
// virtual field
GraphicUtils.setTableColumnRenderer(this.table, OrderEditorTableModel.iResults, new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table1, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
try {
ImageIcon ico = (ImageIcon) value;
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, "", isSelected, hasFocus, row, column);
lbl.setIcon(ico);
if (ico != null) {
OrderResultContainer container = (OrderResultContainer) Application.instance().getApplicationContext().getBean("orderResultContainer");
int idx = ((SortableTableModel) table1.getModel()).convertSortedIndexToDataIndex(row);
Object obj = OrderEditorListView.this.tableModel.getRow(idx);
Order o = (Order) obj;
String txt = "";
for (OrderResult result : container.getResultsForOrder(o)) {
txt += (txt.equals("") ? "" : "") + "<li>" + result.getType().toString() + ": " + result.getMessage() + "</li>";
}
txt = "<html><body><lu>" + txt + "</lu></body></html>";
lbl.setToolTipText(txt);
}
lbl.setHorizontalAlignment(SwingConstants.CENTER);
return lbl;
} catch (Exception exc) {
// do nothing
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, "", isSelected, hasFocus, row, column);
return lbl;
}
}
});
// renderer for hex - boldify capital hex
GraphicUtils.setTableColumnRenderer(this.table, OrderEditorTableModel.iHexNo, new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table1, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
try {
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, value, isSelected, hasFocus, row, column);
// find capital and compare
int idx = ((SortableTableModel) table1.getModel()).convertSortedIndexToDataIndex(row);
Object obj = OrderEditorListView.this.tableModel.getRow(idx);
Order o = (Order) obj;
Character c = o.getCharacter();
PopulationCenter capital = (PopulationCenter) GameHolder.instance().getGame().getTurn().getContainer(TurnElementsEnum.PopulationCenter).findFirstByProperties(new String[] { "nationNo", "capital" }, new Object[] { c.getNationNo(), Boolean.TRUE });
if (capital != null && c.getHexNo() == capital.getHexNo()) {
lbl.setFont(GraphicUtils.getFont(lbl.getFont().getName(), Font.BOLD, lbl.getFont().getSize()));
}
lbl.setHorizontalAlignment(SwingConstants.CENTER);
return lbl;
} catch (Exception exc) {
// do nothing
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, "", isSelected, hasFocus, row, column);
return lbl;
}
};
});
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table1, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, value, isSelected, hasFocus, row, column);
lbl.setHorizontalAlignment(SwingConstants.CENTER);
return lbl;
};
};
// render stats - center alignment
GraphicUtils.setTableColumnRenderer(this.table, OrderEditorTableModel.iStats, centerRenderer);
for (int i = OrderEditorTableModel.iParamStart; i <= OrderEditorTableModel.iParamEnd; i++) {
GraphicUtils.setTableColumnRenderer(this.table, i, new OrderParameterCellRenderer(i - OrderEditorTableModel.iParamStart));
}
GraphicUtils.setTableColumnRenderer(this.table, OrderEditorTableModel.iNoAndCode, new OrderNumberCellRenderer());
// tlb.row();
// tlb.cell(tableComp);
// tlb.row();
// return tlb.getPanel();
return tableComp;
}
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
if (applicationEvent instanceof JOverseerEvent) {
JOverseerEvent e = (JOverseerEvent) applicationEvent;
if (e.getEventType().equals(LifecycleEventsEnum.SelectedTurnChangedEvent.toString())) {
refreshFilters();
setItems();
} else if (e.getEventType().equals(LifecycleEventsEnum.SelectedHexChangedEvent.toString())) {
setItems();
} else if (e.getEventType().equals(LifecycleEventsEnum.GameChangedEvent.toString())) {
// setFilters();
refreshFilters();
TableColumn noAndCodeColumn = this.table.getColumnModel().getColumn(OrderEditorTableModel.iNoAndCode);
Game g = ((GameHolder) Application.instance().getApplicationContext().getBean("gameHolder")).getGame();
ListListModel orders = new ListListModel();
orders.add(Order.NA);
if (Game.isInitialized(g)) {
GameMetadata gm = g.getMetadata();
Container<OrderMetadata> orderMetadata = gm.getOrders();
for (OrderMetadata om : orderMetadata) {
orders.add(om.getNumber() + " " + om.getCode());
}
}
SortedListModel slm = new SortedListModel(orders);
// ComboBox Editor for the order number
final JComboBox comboBox = new AutocompletionComboBox(new ComboBoxListModelAdapter(slm));
comboBox.setEditable(true);
comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
final ComboBoxCellEditor editor = new ComboBoxCellEditor(comboBox);
noAndCodeColumn.setCellEditor(editor);
editor.addCellEditorListener(new CellEditorListener() {
@Override
public void editingCanceled(ChangeEvent e1) {
OrderEditorListView.this.table.requestFocus();
}
@Override
public void editingStopped(ChangeEvent e1) {
OrderEditorListView.this.table.requestFocus();
}
});
comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == KeyEvent.VK_ESCAPE) {
editor.cancelCellEditing();
arg0.consume();
}
}
});
setItems();
} else if (e.getEventType().equals(LifecycleEventsEnum.OrderChangedEvent.toString())) {
// setItems();
} else if (e.getEventType().equals(LifecycleEventsEnum.RefreshMapItems.toString())) {
setItems();
} else if (e.getEventType().equals(LifecycleEventsEnum.RefreshOrders.toString())) {
setItems();
}
}
}
@Override
public JPopupMenu getPopupMenu(boolean hasSelectedItem) {
if (!hasSelectedItem)
return null;
CommandGroup group = Application.instance().getActiveWindow().getCommandManager().createCommandGroup("orderCommandGroup", new Object[] { this.editOrderAction, this.deleteOrderAction,
// sendOrderByChatAction,
"separator", new DrawAllOrdersAction(), new UnDrawAllOrdersAction(),
// new SendAllOrdersByChatAction()
});
return group.createPopupMenu();
}
/**
* Edit the selected order
*
* @author Marios Skounakis
*/
private class EditOrderAction extends ActionCommand {
@Override
protected void doExecuteCommand() {
int row = OrderEditorListView.this.table.getSelectedRow();
if (row >= 0) {
int idx = ((SortableTableModel) OrderEditorListView.this.table.getModel()).convertSortedIndexToDataIndex(row);
if (idx >= OrderEditorListView.this.tableModel.getRowCount())
return;
try {
Object obj = OrderEditorListView.this.tableModel.getRow(idx);
Order order = (Order) obj;
Application.instance().getApplicationContext().publishEvent(new JOverseerEvent(LifecycleEventsEnum.EditOrderEvent.toString(), order, this));
} catch (Exception exc) {
}
}
}
}
/**
* Delete the selected order
*
* @author Marios Skounakis
*/
private class DeleteOrderAction extends ActionCommand {
@Override
protected void doExecuteCommand() {
int row = OrderEditorListView.this.table.getSelectedRow();
if (row >= 0) {
int idx = ((SortableTableModel) OrderEditorListView.this.table.getModel()).convertSortedIndexToDataIndex(row);
if (idx >= OrderEditorListView.this.tableModel.getRowCount())
return;
try {
Object obj = OrderEditorListView.this.tableModel.getRow(idx);
Order order = (Order) obj;
order.clear();
((BeanTableModel) OrderEditorListView.this.table.getModel()).fireTableDataChanged();
Application.instance().getApplicationContext().publishEvent(new JOverseerEvent(LifecycleEventsEnum.OrderChangedEvent.toString(), order, this));
} catch (Exception exc) {
System.out.println(exc);
}
}
}
}
/**
* Set Draw = true for all orders in the list view
*
* @author Marios Skounakis
*/
private class DrawAllOrdersAction extends ActionCommand {
@Override
protected void doExecuteCommand() {
OrderVisualizationData ovd = (OrderVisualizationData) Application.instance().getApplicationContext().getBean("orderVisualizationData");
for (Object o : OrderEditorListView.this.tableModel.getRows()) {
Order order = (Order) o;
if (GraphicUtils.canRenderOrder(order)) {
ovd.addOrder(order);
}
}
Application.instance().getApplicationContext().publishEvent(new JOverseerEvent(LifecycleEventsEnum.RefreshMapItems.toString(), this, this));
}
}
/**
* Set Draw = false for all orders in the list view
*
* @author Marios Skounakis
*/
private class UnDrawAllOrdersAction extends ActionCommand {
@Override
protected void doExecuteCommand() {
OrderVisualizationData ovd = (OrderVisualizationData) Application.instance().getApplicationContext().getBean("orderVisualizationData");
ovd.clear();
Application.instance().getApplicationContext().publishEvent(new JOverseerEvent(LifecycleEventsEnum.RefreshMapItems.toString(), this, this));
}
}
/**
* Generic Order filter
*
* @author Marios Skounakis
*/
private abstract class OrderFilter extends AbstractListViewFilter {
public abstract boolean acceptCharacter(Character c);
// dummy, basically ignored
@Override
public boolean accept(Object o) {
return true;
}
public OrderFilter(String description) {
super(description);
}
}
public class OrderHexFilter extends OrderFilter {
String hexNo;
public OrderHexFilter(String description, String hexNo) {
super(description);
this.hexNo = hexNo;
}
@Override
public boolean acceptCharacter(Character c) {
for (Order o : c.getOrders()) {
if (o.isBlank())
continue;
for (int i = 0; i <= o.getLastParamIndex(); i++) {
if (o.getParameter(i).equals(this.hexNo))
return true;
}
}
return false;
}
}
public class OrderTextFilter extends OrderFilter {
String text;
public OrderTextFilter(String description, String text) {
super(description);
this.text = text;
}
@Override
public boolean acceptCharacter(Character c) {
for (Order o : c.getOrders()) {
if (o.isBlank())
continue;
for (int i = 0; i <= o.getLastParamIndex(); i++) {
if (o.getParameter(i).contains(this.text))
return true;
}
}
return false;
}
}
@Override
public ColumnToSort[] getDefaultSort() {
// set comparator to sort using the character ids
((SortableTableModel) this.table.getModel()).setComparator(1, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1 != null && o2 != null) {
return Character.getIdFromName(o1).compareTo(Character.getIdFromName(o2));
}
return 0;
}
});
return new ColumnToSort[] { new ColumnToSort(0, 0, SortOrder.ASCENDING), new ColumnToSort(0, 1, SortOrder.ASCENDING) };
}
/**
* Cell renderer for the order parameters - Changes the background to
* erroneous parameters - Shows a tooltip with the error message
*
* @author Marios Skounakis
*/
class OrderParameterCellRenderer extends DefaultTableCellRenderer {
int paramNo;
Color selectionBackground = (Color) UIManager.get("Table.selectionBackground");
Color normalBackground = (Color) UIManager.get("Table.background");
private OrderParameterCellRenderer(int paramNo) {
super();
this.paramNo = paramNo;
}
@Override
public Component getTableCellRendererComponent(JTable table1, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, value, isSelected, hasFocus, row, column);
int idx = ((SortableTableModel) table1.getModel()).convertSortedIndexToDataIndex(row);
Object obj = OrderEditorListView.this.tableModel.getRow(idx);
Order o = (Order) obj;
OrderValidationResult res = null;
// TODO handle larger paramNos
if (this.paramNo < 9) {
res = OrderEditorListView.this.validator.checkParam(o, this.paramNo);
}
if (res != null) {
if (isSelected) {
lbl.setBackground(this.selectionBackground);
} else if (res.getLevel() == OrderValidationResult.ERROR) {
lbl.setBackground(OrderEditorListView.this.paramErrorColor);
} else if (res.getLevel() == OrderValidationResult.WARNING) {
lbl.setBackground(OrderEditorListView.this.paramWarningColor);
} else if (res.getLevel() == OrderValidationResult.INFO) {
lbl.setBackground(OrderEditorListView.this.paramInfoColor);
}
lbl.setToolTipText(res.getMessage());
} else {
if (isSelected) {
lbl.setBackground(this.selectionBackground);
} else {
lbl.setBackground(this.normalBackground);
}
lbl.setToolTipText(null);
}
return lbl;
}
}
/**
* Renderer for the order number - Changes the background to erroneous
* orders - Shows a tooltip with the error message
*
* @author Marios Skounakis
*/
class OrderNumberCellRenderer extends DefaultTableCellRenderer {
Color selectionBackground = (Color) UIManager.get("Table.selectionBackground");
Color normalBackground = (Color) UIManager.get("Table.background");
private OrderNumberCellRenderer() {
super();
}
@Override
public Component getTableCellRendererComponent(JTable table1, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table1, value, isSelected, hasFocus, row, column);
int idx = ((SortableTableModel) table1.getModel()).convertSortedIndexToDataIndex(row);
Object obj = OrderEditorListView.this.tableModel.getRow(idx);
Order o = (Order) obj;
OrderValidationResult res = OrderEditorListView.this.validator.checkOrder(o);
if (res != null) {
if (isSelected) {
lbl.setBackground(this.selectionBackground);
} else if (res.getLevel() == OrderValidationResult.ERROR) {
lbl.setBackground(OrderEditorListView.this.paramErrorColor);
} else if (res.getLevel() == OrderValidationResult.WARNING) {
lbl.setBackground(OrderEditorListView.this.paramWarningColor);
} else if (res.getLevel() == OrderValidationResult.INFO) {
lbl.setBackground(OrderEditorListView.this.paramInfoColor);
}
lbl.setToolTipText(res.getMessage());
} else {
if (isSelected) {
lbl.setBackground(this.selectionBackground);
} else {
lbl.setBackground(this.normalBackground);
}
lbl.setToolTipText(null);
}
return lbl;
}
}
}
| second filter in lists improved
hopefully added command, agent, emissary, mage >0 and filter by nation
as an optional second filter
| joverseerjar/src/org/joverseer/ui/listviews/OrderEditorListView.java | second filter in lists improved |
|
Java | mit | ceee9886747cad053b45fecd0c7a456286d33e46 | 0 | Bipshark/TDA367,Bipshark/TDA367 | core/src/main/java/edu/chalmers/sankoss/core/SankossAI.java | /*
package edu.chalmers.sankoss.core;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import edu.chalmers.sankoss.core.exceptions.IllegalShipCoordinatesException;
import edu.chalmers.sankoss.core.protocol.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
*/
/**
* @author Fredrik Thune
*//*
public class SankossAI implements Runnable {
private Client client;
private Player player;
private List<BasePlayer> opponents = new ArrayList<BasePlayer>();
private Long gameID;
private Long roomID;
public SankossAI(Long roomID) {
this.roomID = roomID;
}
public void destroy() {
client.close();
}
@Override
public void run() {
client = new Client();
new Thread(client).start();
Network.register(client);
client.addListener(new Listener.ThreadedListener(new Listener() {
public void connected(Connection connection) {
System.out.println("AI: Connected to server: " + connection.getRemoteAddressTCP());
}
public void received(Connection connection, Object object) {
if (object instanceof Connected) {
Connected msg = (Connected) object;
// Create new local player with remote ID
player = new Player(msg.getID());
// Fetch remote rooms
client.sendTCP(new JoinRoom(roomID, "BOT-BERT")); // TODO fix name
return;
}
if (object instanceof StartedGame) {
if (player == null) return;
StartedGame msg = (StartedGame) object;
gameID = msg.getGameID();
System.out.println(String.format("AI: Placing ships! #%d", msg.getGameID()));
List<Ship> fleet = new ArrayList<Ship>();
try {
fleet.add(new Ship(new Coordinate(1, 5), new Coordinate(3, 5)));
fleet.add(new Ship(new Coordinate(3, 7), new Coordinate(4, 7)));
fleet.add(new Ship(new Coordinate(5, 2), new Coordinate(5, 5)));
fleet.add(new Ship(new Coordinate(9, 8), new Coordinate(9, 4)));
fleet.add(new Ship(new Coordinate(7, 2), new Coordinate(7, 3)));
}
catch (IllegalShipCoordinatesException ignore) {
//TODO Something something
}
client.sendTCP(new PlayerReady(msg.getGameID(), fleet));
return;
}
if (object instanceof GameReady) {
if (player == null) return;
System.out.println("AI: Game started!");
return;
}
if (object instanceof PlayerIsReady) {
if (player == null) return;
PlayerIsReady msg = (PlayerIsReady) object;
opponents.add(msg.getPlayer());
System.out.println(String.format("AI: #%d is ready!", msg.getPlayer().getID()));
return;
}
if (object instanceof Turn) {
Coordinate coordinate = null;
Random r = new Random();
BasePlayer opponent = opponents.get(0); // Change if more than 2 players
do {
coordinate = new Coordinate(r.nextInt(9) + 1, r.nextInt(9) + 1);
} while (player.getUsedCoordinates().contains(coordinate));
client.sendTCP(new Fire(gameID, opponent, coordinate));
return;
}
if (object instanceof Disconnect) {
destroy();
}
}
}));
try {
client.connect(5000, "127.0.0.1", Network.PORT);
} catch (IOException e) {
System.out.println("AI: Could not connect to remote server...");
}
client.sendTCP(new Connect());
}
}
*/
| Removed my dear AI </3
| core/src/main/java/edu/chalmers/sankoss/core/SankossAI.java | Removed my dear AI </3 |
||
Java | mit | 71a47d58aae682476edff6b5014acd1d0f79604b | 0 | nls-oskari/oskari-server,nls-oskari/oskari-server,nls-oskari/oskari-server | package org.oskari.admin;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import fi.nls.oskari.domain.map.DataProvider;
import fi.nls.oskari.domain.map.OskariLayer;
import fi.nls.oskari.map.layer.DataProviderService;
import fi.nls.oskari.service.OskariComponentManager;
import fi.nls.oskari.service.ServiceRuntimeException;
import fi.nls.oskari.util.JSONHelper;
import org.json.JSONObject;
import org.oskari.admin.model.MapLayer;
import org.oskari.admin.model.MapLayerAdminOutput;
public class LayerAdminJSONHelper {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public static MapLayer readJSON(String layerJSON) {
try {
return OBJECT_MAPPER.readValue(layerJSON, MapLayer.class);
} catch (Exception ex) {
throw new ServiceRuntimeException("Coudn't parse layer from: " + layerJSON, ex);
}
}
public static String writeJSON(MapLayer layer) {
try {
return OBJECT_MAPPER.writeValueAsString(layer);
} catch (Exception ex) {
throw new ServiceRuntimeException("Coudn't write layer to JSON", ex);
}
}
public static OskariLayer fromJSON(MapLayer model) {
OskariLayer layer = new OskariLayer();
Integer id = model.getId();
if (id != null) {
// unboxing null Integer to int causes NPE so not calling setId() with null value
layer.setId(model.getId());
}
layer.setType(model.getType());
layer.setUrl(model.getUrl());
layer.setUsername(model.getUsername());
layer.setPassword(model.getPassword());
layer.setVersion(model.getVersion());
layer.setName(model.getName());
layer.setLocale(new JSONObject(model.getLocale()));
layer.setSrs_name(model.getSrs());
layer.setOpacity(model.getOpacity());
layer.setStyle(model.getStyle());
layer.setMinScale(model.getMinscale());
layer.setMaxScale(model.getMaxscale());
layer.setLegendImage(model.getLegend_image());
layer.setMetadataId(model.getMetadataid());
if (model.getParams() != null) {
layer.setParams(new JSONObject(model.getParams()));
}
if (model.getAttributes() != null) {
layer.setAttributes(new JSONObject(model.getAttributes()));
}
if (model.getOptions() != null) {
layer.setOptions(new JSONObject(model.getOptions()));
}
layer.setGfiType(model.getGfi_type());
layer.setGfiXslt(model.getGfi_xslt());
layer.setGfiContent(model.getGfi_content());
layer.setBaseMap(model.isBase_map());
layer.setRealtime(model.isRealtime());
layer.setRefreshRate(model.getRefresh_rate());
layer.setCapabilitiesUpdateRateSec(model.getCapabilities_update_rate_sec());
layer.setDataproviderId(getDataProviderId(model));
layer.setInternal(model.isInternal());
// TODO: handle sublayers layer.getSublayers()
// TODO: handle groups -> MapLayerGroupsHelper.findGroupsForNames_dangerzone_() + setGroupsForLayer()
// TODO: role_permissions -> MapLayerPermissionsHelper.setLayerPermissions()
return layer;
}
public static MapLayerAdminOutput toJSON(OskariLayer layer) {
MapLayerAdminOutput out = new MapLayerAdminOutput();
out.setId(layer.getId());
out.setType(layer.getType());
out.setUrl(layer.getUrl());
out.setUsername(layer.getUsername());
out.setPassword(layer.getPassword());
out.setVersion(layer.getVersion());
out.setName(layer.getName());
out.setLocale(JSONHelper.getObjectAsMap(layer.getLocale()));
out.setSrs(layer.getSrs_name());
out.setOpacity(layer.getOpacity());
out.setStyle(layer.getStyle());
out.setMinscale(layer.getMinScale());
out.setMaxscale(layer.getMaxScale());
layer.setLegendImage(layer.getLegendImage());
layer.setMetadataId(layer.getMetadataId());
out.setParams(JSONHelper.getObjectAsMap(layer.getParams()));
out.setAttributes(JSONHelper.getObjectAsMap(layer.getAttributes()));
out.setOptions(JSONHelper.getObjectAsMap(layer.getOptions()));
out.setGfi_type(layer.getGfiType());
out.setGfi_xslt(layer.getGfiXslt());
out.setGfi_content(layer.getGfiContent());
out.setBase_map(layer.isBaseMap());
out.setRealtime(layer.getRealtime());
out.setRefresh_rate(layer.getRefreshRate());
out.setCapabilities_update_rate_sec(layer.getCapabilitiesUpdateRateSec());
out.setDataprovider_id(layer.getDataproviderId());
out.setInternal(layer.isInternal()); // we might not need to write this
out.setCapabilities(JSONHelper.getObjectAsMap(layer.getCapabilities()));
// TODO: handle sublayers layer.getSublayers()
// TODO: handle groups -> MapLayerGroupsHelper.findGroupsForNames_dangerzone_() + setGroupsForLayer()
// TODO: role_permissions -> MapLayerPermissionsHelper.setLayerPermissions()
return out;
}
private static int getDataProviderId(MapLayer model) {
DataProvider provider = null;
if (model.getDataprovider_id() > 0) {
provider = getDataProviderService().find(model.getDataprovider_id());
} else if (model.getDataprovider() != null) {
provider = getDataProviderService().findByName(model.getDataprovider());
}
if (provider == null) {
throw new ServiceRuntimeException("Couln't find data provider for layer (" + model.getDataprovider_id() + "/" + model.getDataprovider() + ")");
}
return provider.getId();
}
private static DataProviderService getDataProviderService() {
return OskariComponentManager.getComponentOfType(DataProviderService.class);
}
}
| service-admin/src/main/java/org/oskari/admin/LayerAdminJSONHelper.java | package org.oskari.admin;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import fi.nls.oskari.domain.map.DataProvider;
import fi.nls.oskari.domain.map.OskariLayer;
import fi.nls.oskari.map.layer.DataProviderService;
import fi.nls.oskari.service.OskariComponentManager;
import fi.nls.oskari.service.ServiceRuntimeException;
import fi.nls.oskari.util.JSONHelper;
import org.json.JSONObject;
import org.oskari.admin.model.MapLayer;
import org.oskari.admin.model.MapLayerAdminOutput;
public class LayerAdminJSONHelper {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public static MapLayer readJSON(String layerJSON) {
try {
return OBJECT_MAPPER.readValue(layerJSON, MapLayer.class);
} catch (Exception ex) {
throw new ServiceRuntimeException("Coudn't parse layer from: " + layerJSON, ex);
}
}
public static String writeJSON(MapLayer layer) {
try {
return OBJECT_MAPPER.writeValueAsString(layer);
} catch (Exception ex) {
throw new ServiceRuntimeException("Coudn't write layer to JSON", ex);
}
}
public static OskariLayer fromJSON(MapLayer model) {
OskariLayer layer = new OskariLayer();
layer.setId(model.getId());
layer.setType(model.getType());
layer.setUrl(model.getUrl());
layer.setUsername(model.getUsername());
layer.setPassword(model.getPassword());
layer.setVersion(model.getVersion());
layer.setName(model.getName());
layer.setLocale(new JSONObject(model.getLocale()));
layer.setSrs_name(model.getSrs());
layer.setOpacity(model.getOpacity());
layer.setStyle(model.getStyle());
layer.setMinScale(model.getMinscale());
layer.setMaxScale(model.getMaxscale());
layer.setLegendImage(model.getLegend_image());
layer.setMetadataId(model.getMetadataid());
if (model.getParams() != null) {
layer.setParams(new JSONObject(model.getParams()));
}
if (model.getAttributes() != null) {
layer.setAttributes(new JSONObject(model.getAttributes()));
}
if (model.getOptions() != null) {
layer.setOptions(new JSONObject(model.getOptions()));
}
layer.setGfiType(model.getGfi_type());
layer.setGfiXslt(model.getGfi_xslt());
layer.setGfiContent(model.getGfi_content());
layer.setBaseMap(model.isBase_map());
layer.setRealtime(model.isRealtime());
layer.setRefreshRate(model.getRefresh_rate());
layer.setCapabilitiesUpdateRateSec(model.getCapabilities_update_rate_sec());
layer.setDataproviderId(getDataProviderId(model));
layer.setInternal(model.isInternal());
// TODO: handle sublayers layer.getSublayers()
// TODO: handle groups -> MapLayerGroupsHelper.findGroupsForNames_dangerzone_() + setGroupsForLayer()
// TODO: role_permissions -> MapLayerPermissionsHelper.setLayerPermissions()
return layer;
}
public static MapLayerAdminOutput toJSON(OskariLayer layer) {
MapLayerAdminOutput out = new MapLayerAdminOutput();
out.setId(layer.getId());
out.setType(layer.getType());
out.setUrl(layer.getUrl());
out.setUsername(layer.getUsername());
out.setPassword(layer.getPassword());
out.setVersion(layer.getVersion());
out.setName(layer.getName());
out.setLocale(JSONHelper.getObjectAsMap(layer.getLocale()));
out.setSrs(layer.getSrs_name());
out.setOpacity(layer.getOpacity());
out.setStyle(layer.getStyle());
out.setMinscale(layer.getMinScale());
out.setMaxscale(layer.getMaxScale());
layer.setLegendImage(layer.getLegendImage());
layer.setMetadataId(layer.getMetadataId());
out.setParams(JSONHelper.getObjectAsMap(layer.getParams()));
out.setAttributes(JSONHelper.getObjectAsMap(layer.getAttributes()));
out.setOptions(JSONHelper.getObjectAsMap(layer.getOptions()));
out.setGfi_type(layer.getGfiType());
out.setGfi_xslt(layer.getGfiXslt());
out.setGfi_content(layer.getGfiContent());
out.setBase_map(layer.isBaseMap());
out.setRealtime(layer.getRealtime());
out.setRefresh_rate(layer.getRefreshRate());
out.setCapabilities_update_rate_sec(layer.getCapabilitiesUpdateRateSec());
out.setDataprovider_id(layer.getDataproviderId());
out.setInternal(layer.isInternal()); // we might not need to write this
out.setCapabilities(JSONHelper.getObjectAsMap(layer.getCapabilities()));
// TODO: handle sublayers layer.getSublayers()
// TODO: handle groups -> MapLayerGroupsHelper.findGroupsForNames_dangerzone_() + setGroupsForLayer()
// TODO: role_permissions -> MapLayerPermissionsHelper.setLayerPermissions()
return out;
}
private static int getDataProviderId(MapLayer model) {
DataProvider provider = null;
if (model.getDataprovider_id() > 0) {
provider = getDataProviderService().find(model.getDataprovider_id());
} else if (model.getDataprovider() != null) {
provider = getDataProviderService().find(model.getDataprovider_id());
}
if (provider == null) {
throw new ServiceRuntimeException("Couln't find data provider for layer");
}
return provider.getId();
}
private static DataProviderService getDataProviderService() {
return OskariComponentManager.getComponentOfType(DataProviderService.class);
}
}
| Fix id unboxing and data provider detection
| service-admin/src/main/java/org/oskari/admin/LayerAdminJSONHelper.java | Fix id unboxing and data provider detection |
|
Java | mit | 2552d7af27d482fa7e648c17e432245981bc3123 | 0 | yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods | package net.maizegenetics.gwas.imputation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import net.maizegenetics.baseplugins.ConvertSBitTBitPlugin;
import org.apache.log4j.Logger;
import net.maizegenetics.baseplugins.TreeDisplayPlugin;
import net.maizegenetics.pal.alignment.Alignment;
import net.maizegenetics.pal.alignment.AlignmentUtils;
import net.maizegenetics.pal.alignment.FilterAlignment;
import net.maizegenetics.pal.alignment.Locus;
import net.maizegenetics.pal.alignment.MutableNucleotideAlignment;
import net.maizegenetics.pal.alignment.NucleotideAlignmentConstants;
import net.maizegenetics.pal.alignment.BitAlignment;
import net.maizegenetics.pal.distance.DistanceMatrix;
import net.maizegenetics.pal.distance.IBSDistanceMatrix;
import net.maizegenetics.pal.ids.IdGroup;
import net.maizegenetics.pal.ids.IdGroupUtils;
import net.maizegenetics.pal.ids.SimpleIdGroup;
import net.maizegenetics.pal.math.GammaFunction;
import net.maizegenetics.pal.tree.Tree;
import net.maizegenetics.pal.tree.TreeClusters;
import net.maizegenetics.pal.tree.UPGMATree;
import net.maizegenetics.plugindef.DataSet;
import net.maizegenetics.plugindef.Datum;
import net.maizegenetics.util.BitSet;
import net.maizegenetics.util.BitUtil;
import net.maizegenetics.util.OpenBitSet;
public class NucleotideImputationUtils {
private static final Logger myLogger = Logger.getLogger(NucleotideImputationUtils.class);
static final byte AA = NucleotideAlignmentConstants.getNucleotideDiploidByte("AA");
static final byte CC = NucleotideAlignmentConstants.getNucleotideDiploidByte("CC");
static final byte GG = NucleotideAlignmentConstants.getNucleotideDiploidByte("GG");
static final byte TT = NucleotideAlignmentConstants.getNucleotideDiploidByte("TT");
static final byte AC = NucleotideAlignmentConstants.getNucleotideDiploidByte("AC");
static final byte AG = NucleotideAlignmentConstants.getNucleotideDiploidByte("AG");
static final byte AT = NucleotideAlignmentConstants.getNucleotideDiploidByte("AT");
static final byte CG = NucleotideAlignmentConstants.getNucleotideDiploidByte("CG");
static final byte CT = NucleotideAlignmentConstants.getNucleotideDiploidByte("CT");
static final byte GT = NucleotideAlignmentConstants.getNucleotideDiploidByte("GT");
static final byte NN = NucleotideAlignmentConstants.getNucleotideDiploidByte("NN");
static final byte CA = NucleotideAlignmentConstants.getNucleotideDiploidByte("CA");
static final byte[] byteval = new byte[] {AA,CC,GG,TT,AC};
final static HashMap<Byte, Integer> genotypeMap = new HashMap<Byte, Integer>();
static{
genotypeMap.put(AA, 0);
genotypeMap.put(CC, 1);
genotypeMap.put(GG, 2);
genotypeMap.put(TT, 3);
genotypeMap.put(AC, 4);
genotypeMap.put(CA, 4);
}
static final byte[][] genoval = new byte[][]{{AA,AC,AG,AT},{AC,CC,CG,CT},{AG,CG,GG,GT},{AT,CT,GT,TT}};
//prevents instantiation of this class
private NucleotideImputationUtils() {}
public static void callParentAlleles(PopulationData popdata, int minAlleleCount, int windowSize, int numberToTry, double cutHeightSnps, double minR) {
BitSet polybits = whichSitesArePolymorphic(popdata.original, minAlleleCount);
int[] coreSnps = findCoreSnps(popdata.original, polybits, windowSize, numberToTry, cutHeightSnps);
String parentA = popdata.parent1;
String parentC = popdata.parent2;
OpenBitSet ldbits = new OpenBitSet(popdata.original.getSiteCount());
int n = coreSnps.length;
for (int i = 0; i < n; i++) ldbits.fastSet(coreSnps[i]);
//debug
examineTaxaClusters(popdata.original, polybits);
IdGroup[] taxaGroup = findTaxaGroups(popdata.original, coreSnps);
//create an alignment for each cluster
IdGroup parentAGroup;
IdGroup parentCGroup;
if (taxaGroup[0].whichIdNumber(parentA) > -1) {
parentAGroup = taxaGroup[0];
parentCGroup = taxaGroup[1];
} else if (taxaGroup[1].whichIdNumber(parentA) > -1) {
parentAGroup = taxaGroup[1];
parentCGroup = taxaGroup[0];
} else if(taxaGroup[0].whichIdNumber(parentC) > -1) {
parentAGroup = taxaGroup[1];
parentCGroup = taxaGroup[0];
} else {
parentAGroup = taxaGroup[0];
parentCGroup = taxaGroup[1];
}
Alignment aAlignment = FilterAlignment.getInstance(popdata.original, parentAGroup);
Alignment cAlignment = FilterAlignment.getInstance(popdata.original, parentCGroup);
byte[] Asnp = new byte[popdata.original.getSiteCount()];
byte[] Csnp = new byte[popdata.original.getSiteCount()];
//set first parent to AA, second parent to CC for snps used to form taxa clusters
//SBitAlignment sbitPopAlignment = SBitAlignment.getInstance(popdata.original);
Alignment sbitPopAlignment = ConvertSBitTBitPlugin.convertAlignment(popdata.original, ConvertSBitTBitPlugin.CONVERT_TYPE.sbit, null);
MutableNucleotideAlignment parentAlignment = MutableNucleotideAlignment.getInstance(sbitPopAlignment);
myLogger.info("snps in parent Alignment = " + parentAlignment.getSiteCount());
int ntaxa = parentAlignment.getSequenceCount();
for (int i = 0; i < coreSnps.length; i++) {
int snp = coreSnps[i];
//debug
int[][] acounts = aAlignment.getAllelesSortedByFrequency(snp);
int[][] ccounts = cAlignment.getAllelesSortedByFrequency(snp);
byte alleleA = aAlignment.getMajorAllele(snp);
byte alleleC = cAlignment.getMajorAllele(snp);
Asnp[snp] = alleleA;
Csnp[snp] = alleleC;
for (int t = 0; t < ntaxa; t++) {
byte[] taxon = popdata.original.getBaseArray(t, snp);
if (taxon[0] == taxon[1]) {
if (taxon[0] == alleleA) parentAlignment.setBase(t, snp, AA);
else if (taxon[0] == alleleC) parentAlignment.setBase(t, snp, CC);
else parentAlignment.setBase(t, snp, NN);
} else if (taxon[0] == alleleA) {
if (taxon[1] == alleleC) parentAlignment.setBase(t, snp, AC);
else parentAlignment.setBase(t, snp, NN);
} else if (taxon[0] == alleleC) {
if (taxon[1] == alleleA) parentAlignment.setBase(t, snp, AC);
else parentAlignment.setBase(t, snp, NN);
} else {
parentAlignment.setBase(t, snp, NN);
}
}
}
//extend haplotypes
//add snps in ld
int testSize = 25;
//add snps from middle to start; test only polymorphic snps
LinkedList<Integer> testSnps = new LinkedList<Integer>();
for (int i = testSize - 1; i >= 0; i--) testSnps.add(coreSnps[i]);
for (int snp = coreSnps[0] - 1; snp >= 0; snp--) {
if (polybits.fastGet(snp)) {
byte[] ac = recodeParentalSnps(snp, testSnps, parentAlignment, minR);
if (ac != null) {
ldbits.fastSet(snp);
testSnps.add(snp);
testSnps.remove();
Asnp[snp] = ac[0];
Csnp[snp] = ac[1];
}
}
}
//add snps from middle to end
testSnps.clear();
n = coreSnps.length;
int nsites = parentAlignment.getSiteCount();
for (int i = n - testSize; i < n; i++) testSnps.add(coreSnps[i]);
for (int snp = coreSnps[n - 1] + 1; snp < nsites; snp++) {
if (polybits.fastGet(snp)) {
byte[] ac = recodeParentalSnps(snp, testSnps, parentAlignment, minR);
if (ac != null) {
ldbits.fastSet(snp);
testSnps.add(snp);
testSnps.remove();
Asnp[snp] = ac[0];
Csnp[snp] = ac[1];
}
}
}
parentAlignment.clean();
n = (int) ldbits.size();
int nRetained = (int) ldbits.cardinality();
popdata.alleleA = new byte[nRetained];
popdata.alleleC = new byte[nRetained];
int[] retainedSites = new int[nRetained];
int snpcount = 0;
for (int i = 0; i < n; i++) {
if (ldbits.fastGet(i)) {
popdata.alleleA[snpcount] = Asnp[i];
popdata.alleleC[snpcount] = Csnp[i];
retainedSites[snpcount++] = i;
}
}
FilterAlignment ldAlignment = FilterAlignment.getInstance(parentAlignment, retainedSites);
popdata.snpIndex = ldbits;
myLogger.info("number of original sites = " + popdata.original.getSiteCount() + ", number of polymorphic sites = " + polybits.cardinality() + ", number of ld sites = " + ldAlignment.getSiteCount());
//popdata.imputed = TBitAlignment.getInstance(ldAlignment);
popdata.imputed = ConvertSBitTBitPlugin.convertAlignment(ldAlignment, ConvertSBitTBitPlugin.CONVERT_TYPE.tbit, null);
}
public static void callParentAllelesByWindow(PopulationData popdata, double maxMissing, double minMaf, int windowSize, double minR) {
BitSet polybits;
double segratio = popdata.contribution1;
if (minMaf < 0 && (segratio == 0.5 || segratio == 0.25 || segratio == 0.75)) {
polybits = whichSitesSegregateCorrectly(popdata.original, maxMissing, segratio);
} else {
if (minMaf < 0) minMaf = 0;
polybits = whichSitesArePolymorphic(popdata.original, maxMissing, minMaf);
}
myLogger.info("polybits cardinality = " + polybits.cardinality());
OpenBitSet filteredBits = whichSnpsAreFromSameTag(popdata.original, polybits);
myLogger.info("filteredBits.cardinality = " + filteredBits.cardinality());
BitSet ldFilteredBits;
if (minR > 0) {
int halfWindow = windowSize / 2;
ldFilteredBits = ldfilter(popdata.original, halfWindow, minR, filteredBits);
} else {
ldFilteredBits = filteredBits;
}
myLogger.info("ldFilteredBits.cardinality = " + ldFilteredBits.cardinality());
int nsites = popdata.original.getSiteCount();
int ntaxa = popdata.original.getSequenceCount();
popdata.alleleA = new byte[nsites];
popdata.alleleC = new byte[nsites];
popdata.snpIndex = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
popdata.alleleA[s] = Alignment.UNKNOWN_ALLELE;
popdata.alleleC[s] = Alignment.UNKNOWN_ALLELE;
}
int[] parentIndex = new int[2];
parentIndex[0] = popdata.original.getIdGroup().whichIdNumber(popdata.parent1);
parentIndex[1] = popdata.original.getIdGroup().whichIdNumber(popdata.parent2);
//iterate through windows
Alignment[] prevAlignment = null;
int[][] snpIndices = getWindows(ldFilteredBits, windowSize);
boolean append = false;
int nWindows = snpIndices.length;
for (int w = 0; w < nWindows; w++) {
int[] snpIndex;
if (append) {
int n1 = snpIndices[w-1].length;
int n2 = snpIndices[w].length;
snpIndex = new int[n1 + n2];
System.arraycopy(snpIndices[w-1], 0, snpIndex, 0, n1);
System.arraycopy(snpIndices[w], 0, snpIndex, n1, n2);
append = false;
} else {
snpIndex = snpIndices[w];
}
//mask the hets
// MutableNucleotideAlignment mna = MutableNucleotideAlignment.getInstance(FilterAlignment.getInstance(popdata.original, snpIndex));
// int n = snpIndex.length;
// byte missing = NucleotideAlignmentConstants.getNucleotideDiploidByte('N');
// for (int i = 0; i < n; i++) {
// for (int t = 0; t < ntaxa; t++) {
// if (hetMask[t].fastGet(snpIndex[i])) mna.setBase(t, i, missing);
// }
// }
// mna.clean();
Alignment windowAlignment = FilterAlignment.getInstance(popdata.original, snpIndex);
LinkedList<Integer> snpList = new LinkedList<Integer>(); //snpList is a list of snps (indices) in this window
for (int s:snpIndex) snpList.add(s);
Alignment[] taxaAlignments = getTaxaGroupAlignments(windowAlignment, parentIndex, snpList);
if (taxaAlignments == null) {
append = true;
} else {
//are groups in this alignment correlated with groups in the previous alignment
double r = 0;
if (prevAlignment != null) {
r = getIdCorrelation(new IdGroup[][] {{prevAlignment[0].getIdGroup(), prevAlignment[1].getIdGroup()},{taxaAlignments[0].getIdGroup(), taxaAlignments[1].getIdGroup()}});
myLogger.info("For " + popdata.name + " the window starting at " + popdata.original.getSNPID(snpIndex[0]) + ", r = " + r + " , # of snps in alignment = " + snpList.size());
} else {
myLogger.info("For " + popdata.name + " the window starting at " + popdata.original.getSNPID(snpIndex[0]) + ", # of snps in alignment = " + snpList.size());
}
checkAlignmentOrderIgnoringParents(taxaAlignments, popdata, r); //if r is negative switch alignment order (which will result in a positive r)
//debug -check upgma tree
// int[] selectSnps = new int[snpList.size()];
// int cnt = 0;
// for (Integer s : snpList) selectSnps[cnt++] = s;
// SBitAlignment sba = SBitAlignment.getInstance(FilterAlignment.getInstance(popdata.original, selectSnps));
// IBSDistanceMatrix dm = new IBSDistanceMatrix(sba);
// estimateMissingDistances(dm);
// Tree myTree = new UPGMATree(dm);
// TreeDisplayPlugin tdp = new TreeDisplayPlugin(null, true);
// tdp.performFunction(new DataSet(new Datum("Snp Tree", myTree, "Snp Tree"), null));
prevAlignment = taxaAlignments;
callParentAllelesUsingTaxaGroups(popdata, taxaAlignments, snpList);
}
}
myLogger.info("number of called snps = " + popdata.snpIndex.cardinality());
//create the imputed array with A/C calls
int nsnps = (int) popdata.snpIndex.cardinality();
ntaxa = popdata.original.getSequenceCount();
nsites = popdata.original.getSiteCount();
int[] snpIndex = new int[nsnps];
int snpcount = 0;
for (int s = 0; s < nsites; s++) {
if (popdata.snpIndex.fastGet(s)) snpIndex[snpcount++] = s;
}
snpIndex = Arrays.copyOf(snpIndex, snpcount);
Alignment target = FilterAlignment.getInstance(popdata.original, snpIndex);
MutableNucleotideAlignment mna = MutableNucleotideAlignment.getInstance(target);
nsnps = snpIndex.length;
for (int s = 0; s < nsnps; s++) {
byte Aallele = popdata.alleleA[snpIndex[s]];
byte Callele = popdata.alleleC[snpIndex[s]];
byte genotypeA = (byte) (Aallele << 4 | Aallele);
byte genotypeC = (byte) (Callele << 4 | Callele);
byte het1 = (byte) (Aallele << 4 | Callele);
byte het2 = (byte) (Callele << 4 | Aallele);
for (int t = 0; t < ntaxa; t++) {
byte val = mna.getBase(t, s);
if (val == genotypeA) {
mna.setBase(t, s, AA);
} else if (val == genotypeC) {
mna.setBase(t, s, CC);
} else if (val == het1 || val == het2) {
mna.setBase(t, s, AC);
} else {
mna.setBase(t, s, NN);
}
}
}
mna.clean();
popdata.imputed = BitAlignment.getInstance(mna, true);
}
public static void callParentAllelesByWindowForBackcrosses(PopulationData popdata, double maxMissing, double minMaf, int windowSize, double minR) {
BitSet polybits = whichSitesSegregateCorrectly(popdata.original, maxMissing, .25);
myLogger.info("polybits cardinality = " + polybits.cardinality());
OpenBitSet filteredBits = whichSnpsAreFromSameTag(popdata.original, 0.8);
filteredBits.and(polybits);
System.out.println("filteredBits.cardinality = " + filteredBits.cardinality());
BitSet ldFilteredBits;
if (minR > 0) {
int halfWindow = windowSize / 2;
ldFilteredBits = ldfilter(popdata.original, halfWindow, minR, filteredBits);
} else {
ldFilteredBits = filteredBits;
}
myLogger.info("ldFilteredBits.cardinality = " + ldFilteredBits.cardinality());
int nsites = popdata.original.getSiteCount();
int ntaxa = popdata.original.getSequenceCount();
popdata.alleleA = new byte[nsites];
popdata.alleleC = new byte[nsites];
popdata.snpIndex = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
if(ldFilteredBits.fastGet(s)) {
popdata.alleleA[s] = popdata.original.getMajorAllele(s);
popdata.alleleC[s] = popdata.original.getMinorAllele(s);
popdata.snpIndex.fastSet(s);
}
}
myLogger.info("number of called snps = " + popdata.snpIndex.cardinality());
//create the imputed array with A/C calls
int nsnps = (int) popdata.snpIndex.cardinality();
ntaxa = popdata.original.getSequenceCount();
nsites = popdata.original.getSiteCount();
int[] snpIndex = new int[nsnps];
int snpcount = 0;
for (int s = 0; s < nsites; s++) {
if (popdata.snpIndex.fastGet(s)) snpIndex[snpcount++] = s;
}
snpIndex = Arrays.copyOf(snpIndex, snpcount);
Alignment target = FilterAlignment.getInstance(popdata.original, snpIndex);
myLogger.info("filtered on snps");
AlignmentUtils.optimizeForTaxa(target);
myLogger.info("optimized for taxa");
//remove taxa with low coverage
boolean[] goodCoverage = new boolean[ntaxa];
int minGametes = 200;
for (int t = 0; t < ntaxa; t++) {
if (target.getTotalGametesNotMissingForTaxon(t) > minGametes) goodCoverage[t] = true;
else goodCoverage[t] = false;
}
myLogger.info("identified low coverage taxa");
IdGroup targetids = IdGroupUtils.idGroupSubset(target.getIdGroup(), goodCoverage);
Alignment target2 = FilterAlignment.getInstance(target, targetids);
myLogger.info("Filtered on taxa.");
MutableNucleotideAlignment mna = MutableNucleotideAlignment.getInstance(target2);
myLogger.info("created mutable alignment.");
nsnps = snpIndex.length;
ntaxa = mna.getSequenceCount();
for (int s = 0; s < nsnps; s++) {
byte Aallele = popdata.alleleA[snpIndex[s]];
byte Callele = popdata.alleleC[snpIndex[s]];
byte genotypeA = (byte) (Aallele << 4 | Aallele);
byte genotypeC = (byte) (Callele << 4 | Callele);
byte het1 = (byte) (Aallele << 4 | Callele);
byte het2 = (byte) (Callele << 4 | Aallele);
for (int t = 0; t < ntaxa; t++) {
byte val = mna.getBase(t, s);
if (val == genotypeA) {
mna.setBase(t, s, AA);
} else if (val == genotypeC) {
mna.setBase(t, s, CC);
} else if (val == het1 || val == het2) {
mna.setBase(t, s, AC);
} else {
mna.setBase(t, s, NN);
}
}
}
myLogger.info("called alleles");
mna.clean();
myLogger.info("cleaned mna");
popdata.imputed = BitAlignment.getInstance(mna, true);
}
public static void callParentAllelesByWindowForMultipleBC(PopulationData popdata, double maxMissing, int minMinorAlleleCount, int windowSize) {
BitSet polybits = whichSitesArePolymorphic(popdata.original, maxMissing, minMinorAlleleCount);
myLogger.info("polybits cardinality = " + polybits.cardinality());
OpenBitSet filteredBits = whichSnpsAreFromSameTag(popdata.original, 0.8);
filteredBits.and(polybits);
System.out.println("filteredBits.cardinality = " + filteredBits.cardinality());
// BitSet ldFilteredBits;
// if (minR > 0) {
// int halfWindow = windowSize / 2;
// ldFilteredBits = ldfilter(popdata.original, halfWindow, minR, filteredBits);
// } else {
// ldFilteredBits = filteredBits;
// }
// myLogger.info("ldFilteredBits.cardinality = " + ldFilteredBits.cardinality());
int nsites = popdata.original.getSiteCount();
int ntaxa = popdata.original.getSequenceCount();
popdata.alleleA = new byte[nsites];
popdata.alleleC = new byte[nsites];
popdata.snpIndex = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
if(filteredBits.fastGet(s)) {
popdata.alleleA[s] = popdata.original.getMajorAllele(s);
popdata.alleleC[s] = popdata.original.getMinorAllele(s);
popdata.snpIndex.fastSet(s);
}
}
myLogger.info("number of called snps = " + popdata.snpIndex.cardinality());
//create the imputed array with A/C calls
int nsnps = (int) popdata.snpIndex.cardinality();
ntaxa = popdata.original.getSequenceCount();
nsites = popdata.original.getSiteCount();
int[] snpIndex = new int[nsnps];
int snpcount = 0;
for (int s = 0; s < nsites; s++) {
if (popdata.snpIndex.fastGet(s)) snpIndex[snpcount++] = s;
}
snpIndex = Arrays.copyOf(snpIndex, snpcount);
Alignment target = FilterAlignment.getInstance(popdata.original, snpIndex);
MutableNucleotideAlignment mna = MutableNucleotideAlignment.getInstance(target);
nsnps = snpIndex.length;
for (int s = 0; s < nsnps; s++) {
byte Aallele = popdata.alleleA[snpIndex[s]];
byte Callele = popdata.alleleC[snpIndex[s]];
byte genotypeA = (byte) (Aallele << 4 | Aallele);
byte genotypeC = (byte) (Callele << 4 | Callele);
byte het1 = (byte) (Aallele << 4 | Callele);
byte het2 = (byte) (Callele << 4 | Aallele);
for (int t = 0; t < ntaxa; t++) {
byte val = mna.getBase(t, s);
if (val == genotypeA) {
mna.setBase(t, s, AA);
} else if (val == genotypeC) {
mna.setBase(t, s, CC);
} else if (val == het1 || val == het2) {
mna.setBase(t, s, AC);
} else {
mna.setBase(t, s, NN);
}
}
}
mna.clean();
popdata.imputed = BitAlignment.getInstance(mna, true);
}
public static void checkAlignmentOrder(Alignment[] alignments, PopulationData family, double r) {
boolean swapAlignments = false;
boolean parentsInSameGroup = false;
boolean parentsInWrongGroups = false;
double minR = -0.05;
int p1group, p2group;
//if parent 1 is in alignment 0, p1group = 0
//if parent1 is in alignment 1, p1group = 1
//if parent 1 is not in either alignment p1group = -1
//likewise for parent 2
if (alignments[0].getIdGroup().whichIdNumber(family.parent1) > -1) p1group = 0;
else if (alignments[1].getIdGroup().whichIdNumber(family.parent1) > -1) p1group = 1;
else p1group = -1;
if (alignments[1].getIdGroup().whichIdNumber(family.parent2) > -1) p2group = 1;
else if (alignments[0].getIdGroup().whichIdNumber(family.parent2) > -1) p2group = 0;
else p2group = -1;
//find out if parents are either in the same group or if they are in groups opposite expected
//parent 1 is expected to be in group 0 since it was used to seed group 0
if (p1group == 0) {
if (p2group == 0) {
parentsInSameGroup = true;
} else if (p2group == 1) {
if (r < 0) parentsInWrongGroups = true;
} else {
if (r < 0) parentsInWrongGroups = true;
}
} else if (p1group == 1) {
if (p2group == 0) {
if (r > 0) parentsInWrongGroups = true;
} else if (p2group == 1) {
parentsInSameGroup = true;
} else {
if (r > 0) parentsInWrongGroups = true;
}
} else {
if (p2group == 0) {
if (r > 0) parentsInWrongGroups = true;
} else if (p2group == 1) {
if (r < 0) parentsInWrongGroups = true;
} else {
//do nothing
}
}
//r is the correlation between taxa assignments in this window and the previous one
//if r is negative then parental assignments should be swapped, which will make it positive
//this can happen when the parents are not in the data set and the assignment of parents to group is arbitrary
if (r < minR) swapAlignments = true;
if (swapAlignments) {
Alignment temp = alignments[0];
alignments[0] = alignments[1];
alignments[1] = temp;
}
if (parentsInSameGroup) {
myLogger.warn("Both parents in the same group for family " + family.name + " at " + alignments[0].getSNPID(0));
}
if (parentsInWrongGroups) {
myLogger.warn("Parents in unexpected group for family " + family.name + " at " + alignments[0].getSNPID(0));
}
}
public static void checkAlignmentOrderIgnoringParents(Alignment[] alignments, PopulationData family, double r) {
boolean swapAlignments = false;
double minR = -0.05;
int p1group, p2group;
//r is the correlation between taxa assignments in this window and the previous one
//if r is negative then parental assignments should be swapped, which will make it positive
//this can happen when the parents are not in the data set and the assignment of parents to group is arbitrary
if (r < minR) swapAlignments = true;
if (swapAlignments) {
Alignment temp = alignments[0];
alignments[0] = alignments[1];
alignments[1] = temp;
}
}
public static int[][] getWindows(BitSet ispoly, int windowSize) {
int npoly = (int) ispoly.cardinality();
int nsnps = (int) ispoly.size();
int nwindows = npoly/windowSize;
int remainder = npoly % windowSize;
if (remainder > windowSize/2) nwindows++; //round up
int[][] windows = new int[nwindows][];
int setsize = npoly/nwindows;
int windowCount = 0;
int snpCount = 0;
int polyCount = 0;
while (snpCount < nsnps && windowCount < nwindows) {
int numberLeft = npoly - polyCount;
if (numberLeft < setsize * 2) setsize = numberLeft;
int[] set = new int[setsize];
int setcount = 0;
while (setcount < setsize && snpCount < nsnps) {
if (ispoly.fastGet(snpCount)) {
set[setcount++] = snpCount;
polyCount++;
}
snpCount++;
}
windows[windowCount++] = set;
}
return windows;
}
/**
* @param family a PopulationData object containing information for this family
* @param taxaGroups an array of two alignments corresponding to two clusters of taxa
* @param snpList the list of snps to be called
*/
public static void callParentAllelesUsingTaxaGroups(PopulationData family, Alignment[] taxaGroups, LinkedList<Integer> snpList) {
int nsnps = taxaGroups[0].getSiteCount();
Iterator<Integer> snpit = snpList.iterator();
for ( int s = 0; s < nsnps; s++) {
byte[] major = new byte[2];
major[0] = taxaGroups[0].getMajorAllele(s);
major[1] = taxaGroups[1].getMajorAllele(s);
Integer snpIndex = snpit.next();
if(major[0] != Alignment.UNKNOWN_ALLELE && major[1] != Alignment.UNKNOWN_ALLELE && major[0] != major[1]) {
family.alleleA[snpIndex] = major[0];
family.alleleC[snpIndex] = major[1];
family.snpIndex.fastSet(snpIndex);
}
}
}
public static double getIdCorrelation(IdGroup[][] id) {
double[][] counts = new double[2][2];
counts[0][0] = IdGroupUtils.getCommonIds(id[0][0], id[1][0]).getIdCount();
counts[0][1] = IdGroupUtils.getCommonIds(id[0][0], id[1][1]).getIdCount();
counts[1][0] = IdGroupUtils.getCommonIds(id[0][1], id[1][0]).getIdCount();
counts[1][1] = IdGroupUtils.getCommonIds(id[0][1], id[1][1]).getIdCount();
double num = counts[0][0] * counts[1][1] - counts[0][1] * counts[1][0];
double p1 = counts[0][0] + counts[0][1];
double q1 = counts[1][0] + counts[1][1];
double p2 = counts[0][0] + counts[1][0];
double q2 = counts[0][1] + counts[1][1];
return num / Math.sqrt(p1 * q1 * p2 * q2);
}
public static BitSet whichSitesArePolymorphic(Alignment a, int minAlleleCount) {
//which sites are polymorphic? minor allele count > 2 and exceed the minimum allele count
int nsites = a.getSiteCount();
OpenBitSet polybits = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
int[][] freq = a.getAllelesSortedByFrequency(s);
if (freq[1].length > 1 && freq[1][1] > 2) {
int alleleCount = freq[1][0] + freq[1][1];
if (alleleCount >= minAlleleCount) polybits.fastSet(s);
}
}
return polybits;
}
public static BitSet whichSitesArePolymorphic(Alignment a, double maxMissing, int minMinorAlleleCount) {
//which sites are polymorphic? minor allele count > 2 and exceed the minimum allele count
int nsites = a.getSiteCount();
int ngametes = 2 * nsites;
int minNotMissingGametes = (int) Math.floor(ngametes * (1 - maxMissing));
OpenBitSet polybits = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
int gametesNotMissing = a.getTotalGametesNotMissing(s);
int minorAlleleCount = a.getMinorAlleleCount(s);
if (gametesNotMissing >= minNotMissingGametes && minorAlleleCount >= minMinorAlleleCount) polybits.fastSet(s);
}
return polybits;
}
public static BitSet whichSitesArePolymorphic(Alignment a, double maxMissing, double minMaf) {
//which sites are polymorphic? minor allele count > 2 and exceed the minimum allele count
int nsites = a.getSiteCount();
int ntaxa = a.getSequenceCount();
double totalgametes = 2 * ntaxa;
OpenBitSet polybits = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
int[][] freq = a.getAllelesSortedByFrequency(s);
int ngametes = a.getTotalGametesNotMissing(s);
double pMissing = (totalgametes - ngametes) / totalgametes;
if (freq[1].length > 1 && freq[1][1] > 2 && pMissing <= maxMissing && a.getMinorAlleleFrequency(s) > minMaf) {
polybits.fastSet(s);
}
}
return polybits;
}
public static BitSet whichSitesSegregateCorrectly(Alignment a, double maxMissing, double ratio) {
int nsites = a.getSiteCount();
int ntaxa = a.getSequenceCount();
double totalgametes = 2 * ntaxa;
OpenBitSet polybits = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
int[][] freq = a.getAllelesSortedByFrequency(s);
int ngametes = a.getTotalGametesNotMissing(s);
double pMissing = (totalgametes - ngametes) / totalgametes;
if (freq[1].length > 1 && pMissing <= maxMissing) {
int Mj = freq[1][0];
int Mn = freq[1][1];
double pmono = binomialProbability(Mj + Mn, Mn, 0.002);
double pquarter = binomialProbability(Mj + Mn, Mn, 0.25);
double phalf = binomialProbability(Mj + Mn, Mn, 0.5);
if (ratio == 0.25 || ratio == 0.75) {
// if (pquarter / (pmono + phalf) > 2) polybits.fastSet(s);
// double poneseven = binomialProbability(Mj + Mn, Mn, .125);
// double pthreefive = binomialProbability(Mj + Mn, Mn, .375);
// if (pquarter > poneseven && pquarter > pthreefive) polybits.fastSet(s);
if (pquarter > phalf && pquarter > pmono) polybits.fastSet(s);
} else {
if (phalf / (pmono + pquarter) > 2) polybits.fastSet(s);
}
}
}
return polybits;
}
private static double binomialProbability(int trials, int successes, double pSuccess) {
double n = trials;
double k = successes;
double logprob = GammaFunction.lnGamma(n + 1.0) -
GammaFunction.lnGamma(k + 1.0) - GammaFunction.lnGamma(n - k + 1.0) + k * Math.log(pSuccess) + (n - k) * Math.log(1 - pSuccess);
return Math.exp(logprob);
}
//returns a byte array containing the A allele as element 0 and the C allele as element 1, or null if the snp is not in LD
public static byte[] recodeParentalSnps(int snp, LinkedList<Integer> testSnps, MutableNucleotideAlignment snpAlignment, double minr) {
int ntaxa = snpAlignment.getSequenceCount();
byte[] snpvals = new byte[ntaxa];
for (int t = 0; t < ntaxa; t++) {
snpvals[t] = snpAlignment.getBase(t, snp);
}
int[] acount = new int[5];
int[] ccount = new int[5];
for (int t = 0; t < ntaxa; t++) {
Integer ndx = genotypeMap.get(snpvals[t]);
if (ndx != null) {
int indx = ndx.intValue();
for (Integer testsnp:testSnps) {
byte testval = snpAlignment.getBase(t, testsnp);
if (testval == AA) acount[ndx]++;
else if (testval == CC) ccount[ndx]++;
}
}
}
//calculate r
int maxa = 0;
int maxc = 0;
for (int i = 1; i < 4; i++) {
if (acount[i] > acount[maxa]) maxa = i;
if (ccount[i] > ccount[maxc]) maxc = i;
}
int[][] counts = new int[2][2];
int N = 0;
N += acount[maxa];
N += acount[maxc];
N += ccount[maxa];
N += ccount[maxc];
double sumx = acount[maxa] + acount[maxc];
double sumy = acount[maxa] + ccount[maxa];
double sumxy = acount[maxa];
double r = (sumxy - sumx * sumy / N) / Math.sqrt( (sumx - sumx * sumx / N) * (sumy - sumy * sumy / N) );
r = Math.abs(r);
//if abs(r) > minr, recode the snp
if ( maxa != maxc && r >= minr) {
byte hetval = genoval[maxa][maxc];
for (int t = 0; t < ntaxa; t++) {
byte val = snpvals[t];
if (val == byteval[maxa]) snpAlignment.setBase(t, snp, AA);
else if (val == byteval[maxc]) snpAlignment.setBase(t, snp, CC);
else if (val == hetval) snpAlignment.setBase(t, snp, AC);
else snpAlignment.setBase(t, snp, NN);
}
return new byte[]{(byte) maxa, (byte) maxc};
}
return null;
}
/**
* This function finds a set of snps within a window of the specified size (100) that are in LD with each other. It trys multiple windows and uses the
* window that yields the largest number of snps.
* @param a the input alignment
* @param polybits a BitSet corresponding to SNPs in a, set if a snp is polymorphic. Only polymorphic SNPs will be considered.
* @param numberToTry the number of windows to try. The function will use the window returning the largest set of SNPs.
* @return indices of the core snps.
*/
public static int[] findCoreSnps(Alignment a, BitSet polybits, int windowSize, int numberToTry, double cutHeightForSnpClusters) {
//define a window
int totalpoly = (int) polybits.cardinality();
int[][] snpSets = new int[numberToTry][];
//find windowSize polymorphic snps centered on the midpoint
int snpInterval = totalpoly / (numberToTry + 1);
int start = - windowSize / 2;
int snpCount = 0;
int polyCount = 0;
int nsites = a.getSiteCount();
for (int setnum = 0; setnum < numberToTry; setnum++) {
start += snpInterval;
if (start < 0) start = 0;
while (polyCount < start) {
if (polybits.fastGet(snpCount)) polyCount++;
snpCount++;
}
int[] snpIds = new int[windowSize];
int windowCount = 0;
while (windowCount < windowSize && snpCount < nsites) {
if (polybits.fastGet(snpCount)) {
snpIds[windowCount++] = snpCount;
polyCount++;
}
snpCount++;
}
//adjust the size of the array if all the snps were used before the array was filled
if (windowCount < windowSize) snpIds = Arrays.copyOf(snpIds, windowCount);
//create a filtered alignment containing only the test snps
FilterAlignment filteredPopAlignment = FilterAlignment.getInstance(a, snpIds);
//cluster polymorphic snps within the window by creating a UPGMA tree (cluster on snps)
Alignment haplotypeAlignment = BitAlignment.getInstance(filteredPopAlignment, true);
UPGMATree myTree = new UPGMATree(snpDistance(haplotypeAlignment));
//debug - display the tree
// TreeDisplayPlugin tdp = new TreeDisplayPlugin(null, true);
// tdp.performFunction(new DataSet(new Datum("Snp Tree", myTree, "Snp Tree"), null));
//cut the tree to create two parent groups
TreeClusters clusterMaker = new TreeClusters(myTree);
int[] groups = clusterMaker.getGroups(cutHeightForSnpClusters);
//find the biggest group
int maxGroup = 0;
for (int grp:groups) maxGroup = Math.max(maxGroup, grp);
int ngroups = maxGroup + 1;
int[] groupCount = new int[ngroups];
for (int grp:groups) groupCount[grp]++;
int[]groupIndex = ImputationUtils.reverseOrder(groupCount);
snpSets[setnum] = new int[ groupCount[groupIndex[0]] ];
int count = 0;
for (int i = 0; i < snpIds.length; i++) {
if (groups[i] == groupIndex[0]) {
int snpIndex = Integer.parseInt(myTree.getIdentifier(i).getFullName());
snpSets[setnum][count++] = snpIds[snpIndex];
}
}
Arrays.sort(snpSets[setnum]);
}
int bestSet = 0;
for (int i = 1; i < numberToTry; i++) {
if (snpSets[i].length > snpSets[bestSet].length) bestSet = i;
}
return snpSets[bestSet];
}
public static IdGroup[] findTaxaGroups(Alignment a, int[] coreSnps) {
//cluster taxa for these snps to find parental haplotypes (cluster on taxa)
//IBSDistanceMatrix dm = new IBSDistanceMatrix(SBitAlignment.getInstance(FilterAlignment.getInstance(a, coreSnps)));
IBSDistanceMatrix dm = new IBSDistanceMatrix(ConvertSBitTBitPlugin.convertAlignment(FilterAlignment.getInstance(a, coreSnps), ConvertSBitTBitPlugin.CONVERT_TYPE.sbit, null));
estimateMissingDistances(dm);
Tree myTree = new UPGMATree(dm);
TreeClusters clusterMaker = new TreeClusters(myTree);
int ntaxa = a.getSequenceCount();
int majorCount = ntaxa;
int minorCount = 0;
int ngroups = 1;
int[] groups = new int[0];
int[] groupCount = null;
int majorGroup = 0;
int minorGroup = 1;
while (majorCount > ntaxa / 2 && minorCount < 10) {
ngroups++;
groups = clusterMaker.getGroups(ngroups);
groupCount = new int[ngroups];
for (int gr : groups) groupCount[gr]++;
for (int i = 1; i < ngroups; i++) {
if (groupCount[i] > groupCount[majorGroup]) {
minorGroup = majorGroup;
majorGroup = i;
} else if (groupCount[i] > groupCount[minorGroup]) minorGroup = i;
}
majorCount = groupCount[majorGroup];
minorCount = groupCount[minorGroup];
}
//debug - display the tree
TreeDisplayPlugin tdp = new TreeDisplayPlugin(null, true);
tdp.performFunction(new DataSet(new Datum("Snp Tree", myTree, "Snp Tree"), null));
//List groups
for (int i = 0; i < ngroups; i++) {
if (groupCount[i] > 5) myLogger.info("Taxa group " + i + " has " + groupCount[i] + " members.");
}
//create major and minor id groups
String[] majorids = new String[groupCount[majorGroup]];
String[] minorids = new String[groupCount[minorGroup]];
majorCount = 0;
minorCount = 0;
for (int i = 0; i < groups.length; i++) {
if (groups[i] == majorGroup) majorids[majorCount++] = myTree.getIdentifier(i).getFullName();
else if (groups[i] == minorGroup) minorids[minorCount++] = myTree.getIdentifier(i).getFullName();
}
IdGroup majorTaxa = new SimpleIdGroup(majorids);
IdGroup minorTaxa = new SimpleIdGroup(minorids);
return new IdGroup[]{majorTaxa,minorTaxa};
}
public static Alignment[] getTaxaGroupAlignments(Alignment a, int[] parentIndex, LinkedList<Integer> snpIndices) {
//cluster taxa for these snps to find parental haplotypes (cluster on taxa)
Alignment[] taxaClusters = ImputationUtils.getTwoClusters(a, 20);
LinkedList<Integer> originalList = new LinkedList<Integer>(snpIndices);
int nsites = a.getSiteCount();
boolean[] include = new boolean[nsites];
int[] includedSnps = new int[nsites];
int snpcount = 0;
for (int s = 0; s < nsites; s++) {
Integer snpIndex = snpIndices.remove();
if ( taxaClusters[0].getMajorAllele(s) != taxaClusters[1].getMajorAllele(s) ) {
// if ( taxaClusters[0].getMajorAllele(s) != Alignment.UNKNOWN_ALLELE && taxaClusters[1].getMajorAllele(s) != Alignment.UNKNOWN_ALLELE &&
// taxaClusters[0].getMajorAlleleFrequency(s) > .6 && taxaClusters[1].getMajorAlleleFrequency(s) > .6) {
// include[s] = true;
// includedSnps[snpcount++] = s;
// snpIndices.add(snpIndex);
// } else include[s] = false;
include[s] = true;
includedSnps[snpcount++] = s;
snpIndices.add(snpIndex);
} else {
// System.out.println("alleles equal at " + s);
// include[s] = false;
include[s] = false;
}
}
if (snpcount > 5) {
includedSnps = Arrays.copyOf(includedSnps, snpcount);
if (snpcount == nsites) return taxaClusters;
else return ImputationUtils.getTwoClusters(FilterAlignment.getInstance(a, includedSnps), 20);
} else {
snpIndices.clear();
snpIndices.addAll(originalList);
return taxaClusters;
}
}
public static void estimateMissingDistances(DistanceMatrix dm) {
int nsize = dm.getSize();
//average distance
double totalDistance = 0;
int count = 0;
for (int i = 0; i < nsize; i++) {
for (int j = i + 1; j < nsize; j++) {
double distance = dm.getDistance(i, j);
if (!Double.isNaN(distance)) {
totalDistance += dm.getDistance(i, j);
count++;
}
}
}
double avgDist = totalDistance / count;
for (int i = 0; i < nsize; i++) {
if ( Double.isNaN(dm.getDistance(i,i)) ) dm.setDistance(i, i, 0);
for (int j = i + 1; j < nsize; j++) {
if ( Double.isNaN(dm.getDistance(i,j)) ) {
dm.setDistance(i, j, avgDist);
}
}
}
}
public static DistanceMatrix snpDistance(Alignment a) {
int nsnps = a.getSiteCount();
SimpleIdGroup snpIds = new SimpleIdGroup(nsnps, true);
double[][] distance = new double[nsnps][nsnps];
double sum = 0;
int count = 0;
for (int i = 0; i < nsnps; i++) {
for (int j = i; j < nsnps; j++) {
double r = computeGenotypeR(i, j, a);
distance[i][j] = distance[j][i] = 1 - r*r;
if (!Double.isNaN(distance[i][j])) {
sum += distance[i][j];
count++;
}
}
}
//set missing to average
double avg = sum/count;
for (int i = 0; i < nsnps; i++) {
for (int j = i; j < nsnps; j++) {
if (Double.isNaN(distance[i][j])) {
distance[i][j] = distance[j][i] = avg;
}
}
}
return new DistanceMatrix(distance, snpIds);
}
public static double computeRForAlleles(int site1, int site2, Alignment a) {
int s1Count = 0;
int s2Count = 0;
int prodCount = 0;
int totalCount = 0;
long[] m11 = a.getAllelePresenceForAllTaxa(site1, 0).getBits();
long[] m12 = a.getAllelePresenceForAllTaxa(site1, 1).getBits();
long[] m21 = a.getAllelePresenceForAllTaxa(site2, 0).getBits();
long[] m22 = a.getAllelePresenceForAllTaxa(site2, 1).getBits();
int n = m11.length;
for (int i = 0; i < n; i++) {
long valid = (m11[i] ^ m12[i]) & (m21[i] ^ m22[i]); //only count non-het & non-missing
long s1major = m11[i] & valid;
long s2major = m21[i] & valid;
long s1s2major = s1major & s2major & valid;
s1Count += BitUtil.pop(s1major);
s2Count += BitUtil.pop(s2major);
prodCount += BitUtil.pop(s1s2major);
totalCount += BitUtil.pop(valid);
}
if (totalCount < 2) return Double.NaN;
//Explanation of method:
// if major site one is x=1, minor site one is x = 0 and for site 2 y = 1 or 0
// r = [sum(xy) - sum(x)sum(y)/N] / sqrt[(sum(x) - sum(x)*sum(x)/N) * ((sum(y) - sum(y)*sum(y)/N)]
// and sum(x) - sum(x)*sum(x)/N = sum(x)(N - sum(x))/N
// because sum(x^2) = sum(x)
double num = ((double) prodCount - ((double) s1Count * s2Count) / ((double) totalCount));
double denom = ((double) (s1Count * (totalCount - s1Count))) / ((double) totalCount);
denom *= ((double) (s2Count * (totalCount - s2Count))) / ((double) totalCount);
if (denom == 0) return Double.NaN;
return num / Math.sqrt(denom);
}
public static double computeRForMissingness(int site1, int site2, Alignment a) {
// int s1Count = 0;
// int s2Count = 0;
// int prodCount = 0;
int totalCount = a.getSequenceCount();
BitSet m11 = a.getAllelePresenceForAllTaxa(site1, 0);
BitSet m12 = a.getAllelePresenceForAllTaxa(site1, 1);
BitSet m21 = a.getAllelePresenceForAllTaxa(site2, 0);
BitSet m22 = a.getAllelePresenceForAllTaxa(site2, 1);
OpenBitSet s1present = new OpenBitSet(m11.getBits(), m11.getNumWords());
s1present.union(m12);
OpenBitSet s2present = new OpenBitSet(m21.getBits(), m21.getNumWords());
s2present.union(m22);
long s1Count = s1present.cardinality();
long s2Count = s2present.cardinality();
long prodCount = OpenBitSet.intersectionCount(s1present, s2present);
//Explanation of method:
// if major site one is x=1, minor site one is x = 0 and for site 2 y = 1 or 0
// r = [sum(xy) - sum(x)sum(y)/N] / sqrt[(sum(x) - sum(x)*sum(x)/N) * ((sum(y) - sum(y)*sum(y)/N)]
// and sum(x) - sum(x)*sum(x)/N = sum(x)(N - sum(x))/N
// because sum(x^2) = sum(x)
double num = ((double) prodCount - ((double) s1Count * s2Count) / ((double) totalCount));
double denom = ((double) (s1Count * (totalCount - s1Count))) / ((double) totalCount);
denom *= ((double) (s2Count * (totalCount - s2Count))) / ((double) totalCount);
if (denom == 0) return Double.NaN;
return num / Math.sqrt(denom);
}
public static double computeGenotypeR(int site1, int site2, Alignment a) throws IllegalStateException {
BitSet s1mj = a.getAllelePresenceForAllTaxa(site1, 0);
BitSet s1mn = a.getAllelePresenceForAllTaxa(site1, 1);
BitSet s2mj = a.getAllelePresenceForAllTaxa(site2, 0);
BitSet s2mn = a.getAllelePresenceForAllTaxa(site2, 1);
OpenBitSet bothpresent = new OpenBitSet(s1mj.getBits(), s1mj.getNumWords());
bothpresent.union(s1mn);
OpenBitSet s2present = new OpenBitSet(s2mj.getBits(), s2mj.getNumWords());
s2present.union(s2mn);
bothpresent.intersect(s2present);
long nsites = s1mj.capacity();
double sum1 = 0;
double sum2 = 0;
double sumsq1 = 0;
double sumsq2 = 0;
double sumprod = 0;
double count = 0;
for (long i = 0; i < nsites; i++) {
if (bothpresent.fastGet(i)) {
double val1 = 0;
double val2 = 0;
if (s1mj.fastGet(i)) {
if (s1mn.fastGet(i)) {
val1++;
} else {
val1 += 2;
}
}
if (s2mj.fastGet(i)) {
if (s2mn.fastGet(i)) {
val2++;
} else {
val2 += 2;
}
}
sum1 += val1;
sumsq1 += val1*val1;
sum2 += val2;
sumsq2 += val2*val2;
sumprod += val1*val2;
count++;
}
}
//r = sum(xy)/sqrt[sum(x2)*sum(y2)], where x = X - Xbar and y = Y - Ybar
//num.r = sum(XY) - 1/n * sum(X)sum(y)
//denom.r = sqrt[ (sum(XX) - 1/n*sum(X)sum(X)) * (sum(YY) - 1/n*sum(Y)sum(Y)) ]
double num = sumprod - sum1 / count * sum2;
double denom = Math.sqrt( (sumsq1 - sum1 / count * sum1) * (sumsq2 - sum2 / count * sum2) );
if (denom == 0) return Double.NaN;
return num / denom;
}
public static MutableNucleotideAlignment imputeUsingViterbiFiveState(Alignment a, double probHeterozygous, String familyName) {
return imputeUsingViterbiFiveState(a, probHeterozygous, familyName, false);
}
public static MutableNucleotideAlignment imputeUsingViterbiFiveState(Alignment a, double probHeterozygous, String familyName, boolean useVariableRecombitionRates) {
a = ConvertSBitTBitPlugin.convertAlignment(a, ConvertSBitTBitPlugin.CONVERT_TYPE.tbit, null);
//states are in {all A; 3A:1C; 1A:1C, 1A:3C; all C}
//obs are in {A, C, M}, where M is heterozygote A/C
int maxIterations = 50;
HashMap<Byte, Byte> obsMap = new HashMap<Byte, Byte>();
obsMap.put(AA, (byte) 0);
obsMap.put(AC, (byte) 1);
obsMap.put(CA, (byte) 1);
obsMap.put(CC, (byte) 2);
int ntaxa = a.getSequenceCount();
int nsites = a.getSiteCount();
//initialize the transition matrix
double[][] transition = new double[][] {
{.999,.0001,.0003,.0001,.0005},
{.0002,.999,.00005,.00005,.0002},
{.0002,.00005,.999,.00005,.0002},
{.0002,.00005,.00005,.999,.0002},
{.0005,.0001,.0003,.0001,.999}
};
TransitionProbability tp;
if (useVariableRecombitionRates) {
tp = new TransitionProbabilityWithVariableRecombination(a.getLocusName(0));
} else {
tp = new TransitionProbability();
}
tp.setTransitionProbability(transition);
int chrlength = a.getPositionInLocus(nsites - 1) - a.getPositionInLocus(0);
tp.setAverageSegmentLength( chrlength / nsites );
//initialize the emission matrix, states (5) in rows, observations (3) in columns
double[][] emission = new double[][] {
{.998,.001,.001},
{.6,.2,.2},
{.4,.2,.4},
{.2,.2,.6},
{.001,.001,.998}
};
EmissionProbability ep = new EmissionProbability();
ep.setEmissionProbability(emission);
//set up indices to non-missing data
ArrayList<BitSet> notMissingIndex = new ArrayList<BitSet>();
int[] notMissingCount = new int[ntaxa];
ArrayList<byte[]> nonMissingObs = new ArrayList<byte[]>();
ArrayList<int[]> snpPositions = new ArrayList<int[]>();
for (int t = 0; t < ntaxa; t++) {
long[] bits = a.getAllelePresenceForAllSites(t, 0).getBits();
BitSet notMiss = new OpenBitSet(bits, bits.length);
notMiss.or(a.getAllelePresenceForAllSites(t, 1));
notMissingIndex.add(notMiss);
notMissingCount[t] = (int) notMiss.cardinality();
}
for (int t = 0; t < ntaxa; t++) {
byte[] obs = new byte[notMissingCount[t]];
int[] pos = new int[notMissingCount[t]];
nonMissingObs.add(obs);
snpPositions.add(pos);
BitSet isNotMissing = notMissingIndex.get(t);
int nmcount = 0;
for (int s = 0; s < nsites; s++) {
byte base = a.getBase(t, s);
if (isNotMissing.fastGet(s) && obsMap.get(a.getBase(t, s)) == null) {
myLogger.info("null from " + Byte.toString(base));
}
if (isNotMissing.fastGet(s)) {
obs[nmcount] = obsMap.get(a.getBase(t, s));
pos[nmcount++] = a.getPositionInLocus(s);
}
}
}
double phom = (1 - probHeterozygous) / 2;
double[] pTrue = new double[]{phom, .25*probHeterozygous ,.5 * probHeterozygous, .25*probHeterozygous, phom};
//iterate
ArrayList<byte[]> bestStates = new ArrayList<byte[]>();
int[][] previousStateCount = new int[5][3];
int iter = 0;
boolean hasNotConverged = true;
while (iter < maxIterations && hasNotConverged) {
//apply Viterbi
myLogger.info("Iteration " + iter++ + " for " + familyName);
bestStates.clear();
for (int t = 0; t < ntaxa; t++) {
tp.setPositions(snpPositions.get(t));
int nobs = notMissingCount[t];
if (nobs >= 20) {
ViterbiAlgorithm va = new ViterbiAlgorithm(nonMissingObs.get(t), tp, ep, pTrue);
va.calculate();
bestStates.add(va.getMostProbableStateSequence());
} else { //do not impute if obs < 20
myLogger.info("Fewer then 20 observations for " + a.getTaxaName(t));
byte[] states = new byte[nobs];
byte[] obs = nonMissingObs.get(t);
for (int i = 0; i < nobs; i++) {
if (obs[i] == AA) states[i] = 0;
else if (obs[i] == CC) states[i] = 4;
else states[i] = 2;
}
bestStates.add(states);
}
}
//re-estimate transition probabilities
int[][] transitionCounts = new int[5][5];
double[][] transitionProb = new double[5][5];
for (int t = 0; t < ntaxa; t++) {
byte[] states = bestStates.get(t);
for (int s = 1; s < notMissingCount[t]; s++) {
transitionCounts[states[s-1]][states[s]]++;
}
}
//transition is prob(state2 | state1) = count(cell)/count(row)
for (int row = 0; row < 5; row++) {
double rowsum = 0;
for (int col = 0; col < 5; col++) rowsum += transitionCounts[row][col];
for (int col = 0; col < 5; col++) transitionProb[row][col] = ((double) transitionCounts[row][col]) / rowsum;
}
tp.setTransitionCounts(transitionCounts, chrlength, ntaxa);
//re-estimate emission probabilities
int[][] emissionCounts = new int[5][3];
double[][] emissionProb = new double[5][3];
for (int t = 0; t < ntaxa; t++) {
byte[] obs = nonMissingObs.get(t);
byte[] states = bestStates.get(t);
for (int s = 0; s < notMissingCount[t]; s++) {
emissionCounts[states[s]][obs[s]]++;
}
}
//debug - print observation/state counts
// StringBuilder strb = new StringBuilder("Imputation counts, rows=states, columns=observations:\n");
// for (int[] row:emissionCounts) {
// for (int cell:row) {
// strb.append(cell).append("\t");
// }
// strb.append("\n");
// }
// strb.append("\n");
// myLogger.info(strb.toString());
//check to see if there is a change in the observation/state counts
hasNotConverged = false;
for (int r = 0; r < 5; r++) {
for (int c = 0; c < 3; c++) {
if (previousStateCount[r][c] != emissionCounts[r][c]) {
hasNotConverged = true;
previousStateCount[r][c] = emissionCounts[r][c];
}
}
}
//emission is prob(obs | state) = count(cell)/count(row)
double[] rowSums = new double[5];
double total = 0;
for (int row = 0; row < 5; row++) {
double rowsum = 0;
for (int col = 0; col < 3; col++) rowsum += emissionCounts[row][col];
for (int col = 0; col < 3; col++) emissionProb[row][col] = ((double) emissionCounts[row][col]) / rowsum;
rowSums[row] = rowsum;
total += rowsum;
}
ep.setEmissionProbability(emissionProb);
//re-estimate pTrue
for (int i = 0; i < 5; i++) {
pTrue[i
] = rowSums[i] / total;
}
//if the model has converged or if the max iterations has been reached print tables
if (!hasNotConverged || iter == maxIterations) {
StringBuilder sb = new StringBuilder("Family ");
sb.append(familyName).append(", chromosome ").append(a.getLocusName(0));
if (iter < maxIterations) {
sb.append(": EM algorithm converged at iteration ").append(iter).append(".\n");
} else {
sb.append(": EM algorithm failed to converge after ").append(iter).append(" iterations.\n");
}
//print transition counts
sb = new StringBuilder("Transition counts from row to column:\n");
for (int[] row:transitionCounts) {
for (int cell:row) {
sb.append(cell).append("\t");
}
sb.append("\n");
}
sb.append("\n");
myLogger.info(sb.toString());
//print transition probabilities
sb = new StringBuilder("Transition probabilities:\n");
for (double[] row:transitionProb) {
for (double cell:row) {
sb.append(cell).append("\t");
}
sb.append("\n");
}
sb.append("\n");
myLogger.info(sb.toString());
//print observation/state counts
sb = new StringBuilder("Imputation counts, rows=states, columns=observations:\n");
for (int[] row:emissionCounts) {
for (int cell:row) {
sb.append(cell).append("\t");
}
sb.append("\n");
}
sb.append("\n");
myLogger.info(sb.toString());
//print emission probabilities
sb = new StringBuilder("Emission probabilities:\n");
for (double[] row:emissionProb) {
for (double cell:row) {
sb.append(cell).append("\t");
}
sb.append("\n");
}
sb.append("\n");
myLogger.info(sb.toString());
}
}
MutableNucleotideAlignment result = MutableNucleotideAlignment.getInstance(a);
nsites = result.getSiteCount();
for (int t = 0; t < ntaxa; t++) {
BitSet hasData = notMissingIndex.get(t);
byte[] states = bestStates.get(t);
int stateCount = 0;
for (int s = 0; s < nsites; s++) {
if (hasData.fastGet(s)) {
if (states[stateCount] == 0) result.setBase(t, s, AA);
else if (states[stateCount] < 4) result.setBase(t, s, AC);
else if (states[stateCount] == 4) result.setBase(t, s, CC);
stateCount++;
}
}
}
result.clean();
return result;
}
public static void fillGapsInAlignment(PopulationData popdata) {
MutableNucleotideAlignment a;
if (popdata.imputed instanceof MutableNucleotideAlignment) {
a = (MutableNucleotideAlignment) popdata.imputed;
} else {
a = MutableNucleotideAlignment.getInstance(popdata.imputed);
popdata.imputed = a;
}
int ntaxa = a.getSequenceCount();
int nsites = a.getSiteCount();
for (int t = 0; t < ntaxa; t++) {
int prevsite = -1;
byte prevValue = -1;
for (int s = 0; s < nsites; s++) {
byte val = a.getBase(t, s);
if (val != NN) {
if (prevsite == -1) {
prevsite = s;
prevValue = val;
} else if(val == prevValue) {
for (int site = prevsite + 1; site < s; site++) {
a.setBase(t, site, prevValue);
prevsite = s;
}
} else {
prevsite = s;
prevValue = val;
}
}
}
}
a.clean();
popdata.imputed = a;
}
public static Alignment convertParentCallsToNucleotides(PopulationData popdata) {
//set monomorphic sites to major (or only allele) (or not)
//set polymorphic sites consistent with flanking markers if equal, unchanged otherwise
//do not change sites that are not clearly monomorhpic or polymorphic
MutableNucleotideAlignment mna = MutableNucleotideAlignment.getInstance(popdata.imputed);
BitSet isPopSnp = popdata.snpIndex;
if (isPopSnp.cardinality() != mna.getSiteCount()) myLogger.info("size of imputed snps not equal to snpIndex cardinality in convertParentCallsToNucleotides.");
int nsites = (int) isPopSnp.capacity();
double ngametes = nsites * 2;
int ntaxa = mna.getSequenceCount();
int imputedSnpCount = 0;
for (int s = 0; s < nsites; s++) {
if (isPopSnp.fastGet(s)) {
int Acall = popdata.alleleA[s];
int Ccall = popdata.alleleC[s];
byte AAcall = (byte) ((Acall << 4) | Acall);
byte CCcall = (byte) ((Ccall << 4) | Ccall);
byte ACcall = (byte) ((Acall << 4) | Ccall);
for (int t = 0; t < ntaxa; t++) {
byte parentCall = popdata.imputed.getBase(t, imputedSnpCount);
if (parentCall == AA) {
mna.setBase(t, imputedSnpCount, AAcall);
} else if (parentCall == CC) {
mna.setBase(t, imputedSnpCount, CCcall);
} else if (parentCall == AC || parentCall == CA) {
mna.setBase(t, imputedSnpCount, ACcall);
} else {
mna.setBase(t, imputedSnpCount, NN);
}
}
imputedSnpCount++;
}
}
mna.clean();
myLogger.info("Original alignment updated for family " + popdata.name + " chromosome " + popdata.original.getLocusName(0) + ".\n");
return mna;
}
public static void examineTaxaClusters(Alignment a, BitSet polybits) {
int nsnps = a.getSiteCount();
int ntaxa = a.getSequenceCount();
int sitecount = 500;
int window = 200;
while (sitecount < nsnps) {
int[] snpndx = new int[window];
int snpcount = 0;
while (snpcount < window && sitecount < nsnps) {
if (polybits.fastGet(sitecount)) snpndx[snpcount++] = sitecount;
sitecount++;
}
if (sitecount < nsnps) {
Alignment subAlignment = BitAlignment.getInstance(FilterAlignment.getInstance(a, snpndx), true);
IBSDistanceMatrix dm = new IBSDistanceMatrix(subAlignment);
estimateMissingDistances(dm);
Tree myTree = new UPGMATree(dm);
TreeClusters tc = new TreeClusters(myTree);
int[] groups = null;
int[] order = null;
int ngrp = 2;
while (true) {
groups = tc.getGroups(ngrp);
int[] grpSize = new int[ngrp];
for (int g:groups) grpSize[g]++;
order = ImputationUtils.reverseOrder(grpSize);
if (((double) grpSize[order[0]]) / ((double) grpSize[order[1]]) < 2.0) {
String[] taxaA = new String[grpSize[order[0]]];
String[] taxaB = new String[grpSize[order[1]]];
int cntA = 0;
int cntB = 0;
for (int t = 0; t < ntaxa; t++) {
String taxon = myTree.getIdentifier(t).getFullName();
if (groups[t] == order[0]) taxaA[cntA++] = taxon;
else if (groups[t] == order[1]) taxaB[cntB++] = taxon;
}
Alignment alignA = FilterAlignment.getInstance(subAlignment, new SimpleIdGroup(taxaA));
Alignment alignB = FilterAlignment.getInstance(subAlignment, new SimpleIdGroup(taxaB));
boolean[] include = new boolean[window];
for (int s = 0; s < window; s++) {
if (alignA.getMajorAllele(s) != alignB.getMajorAllele(s)) {
if ( ((double) alignA.getMajorAlleleCount(s))/((double) alignA.getMinorAlleleCount(s)) > 2.0 && ((double) alignB.getMajorAlleleCount(s))/((double) alignB.getMinorAlleleCount(s)) > 2.0) {
include[s] = true;
} else include[s] = false;
} else {
System.out.println("alleles equal at " + s);
include[s] = false;
}
}
int ngoodsnps = 0;
for (boolean b:include) if (b) ngoodsnps++;
int[] goodSnpIndex = new int[ngoodsnps];
int cnt = 0;
for (int s = 0; s < window; s++) {
if (include[s]) goodSnpIndex[cnt++] = s;
}
IBSDistanceMatrix dm2 = new IBSDistanceMatrix(BitAlignment.getInstance(FilterAlignment.getInstance(subAlignment, goodSnpIndex), true));
estimateMissingDistances(dm2);
Tree thisTree = new UPGMATree(dm2);
//display the tree
TreeDisplayPlugin tdp = new TreeDisplayPlugin(null, true);
tdp.performFunction(new DataSet(new Datum("Snp Tree", thisTree, "Snp Tree"), null));
System.out.println("n good snps = " + ngoodsnps);
break;
}
// else if (ngrp > 2) {
// if (((double) grpSize[order[0]]) / ((double) (grpSize[order[1]] + grpSize[order[2]])) < 1.5) {
//
// }
// }
ngrp++;
if (ngrp > 20) break;
}
//display the tree
TreeDisplayPlugin tdp = new TreeDisplayPlugin(null, true);
tdp.performFunction(new DataSet(new Datum("Snp Tree", myTree, "Snp Tree"), null));
}
}
}
/**
* SNPs on the same tag will have correlated errors. While alignments do not have information about which SNPs come from the same tag, SNPs from one tag will be <64 bp distant.
* They will also be highly correlated. This function tests removes the second of any pair of SNPs that could come from the same tag.
* @param alignIn the input Alignment
* @return an alignment with the one of any correlated pairs of SNPs removed
*/
public static Alignment removeSNPsFromSameTag(Alignment alignIn, double minRsq) {
Alignment sba = ConvertSBitTBitPlugin.convertAlignment(alignIn, ConvertSBitTBitPlugin.CONVERT_TYPE.sbit, null);
//if (alignIn instanceof SBitAlignment) sba = (SBitAlignment) alignIn;
//else sba = SBitAlignment.getInstance(alignIn);
int nsites = sba.getSiteCount();
int ntaxa = sba.getSequenceCount();
int firstSite = 0;
int[] sitesSelected = new int[nsites];
int selectCount = 0;
sitesSelected[selectCount++] = 0;
String firstSnpLocus = sba.getLocus(0).getName();
int firstSnpPos = sba.getPositionInLocus(0);
while (firstSite < nsites - 1) {
int nextSite = firstSite + 1;
int nextSnpPos = sba.getPositionInLocus(nextSite);
String nextSnpLocus = sba.getLocus(nextSite).getName();
while (firstSnpLocus.equals(nextSnpLocus) && nextSnpPos - firstSnpPos < 64) {
//calculate r^2 between snps
BitSet rMj = sba.getAllelePresenceForAllTaxa(firstSite, 0);
BitSet rMn = sba.getAllelePresenceForAllTaxa(firstSite, 1);
BitSet cMj = sba.getAllelePresenceForAllTaxa(nextSite, 0);
BitSet cMn = sba.getAllelePresenceForAllTaxa(nextSite, 1);
int n = 0;
int[][] contig = new int[2][2];
n += contig[0][0] = (int) OpenBitSet.intersectionCount(rMj, cMj);
n += contig[1][0] = (int) OpenBitSet.intersectionCount(rMn, cMj);
n += contig[0][1] = (int) OpenBitSet.intersectionCount(rMj, cMn);
n += contig[1][1] = (int) OpenBitSet.intersectionCount(rMn, cMn);
double rsq = calculateRSqr(contig[0][0], contig[0][1], contig[1][0], contig[1][1], 2);
if (Double.isNaN(rsq) || rsq >= minRsq) sitesSelected[selectCount++] = nextSite;
nextSite++;
nextSnpPos = sba.getPositionInLocus(nextSite);
nextSnpLocus = sba.getLocus(nextSite).getName();
}
firstSite = nextSite;
firstSnpLocus = nextSnpLocus;
firstSnpPos = nextSnpPos;
sitesSelected[selectCount++] = firstSite;
}
return FilterAlignment.getInstance(sba, sitesSelected);
}
public static OpenBitSet whichSnpsAreFromSameTag(Alignment alignIn, double minRsq) {
Alignment sba = ConvertSBitTBitPlugin.convertAlignment(alignIn, ConvertSBitTBitPlugin.CONVERT_TYPE.sbit, null);
//if (alignIn instanceof SBitAlignment) sba = (SBitAlignment) alignIn;
//else sba = SBitAlignment.getInstance(alignIn);
int nsites = sba.getSiteCount();
int firstSite = 0;
OpenBitSet isSelected = new OpenBitSet(nsites);
isSelected.fastSet(0);
Locus firstSnpLocus = sba.getLocus(0);
int firstSnpPos = sba.getPositionInLocus(0);
while (firstSite < nsites - 1) {
int nextSite = firstSite + 1;
int nextSnpPos = sba.getPositionInLocus(nextSite);
Locus nextSnpLocus = sba.getLocus(nextSite);
while (firstSnpLocus.equals(nextSnpLocus) && nextSnpPos - firstSnpPos < 64) {
//calculate r^2 between snps
BitSet rMj = sba.getAllelePresenceForAllTaxa(firstSite, 0);
BitSet rMn = sba.getAllelePresenceForAllTaxa(firstSite, 1);
BitSet cMj = sba.getAllelePresenceForAllTaxa(nextSite, 0);
BitSet cMn = sba.getAllelePresenceForAllTaxa(nextSite, 1);
int[][] contig = new int[2][2];
contig[0][0] = (int) OpenBitSet.intersectionCount(rMj, cMj);
contig[1][0] = (int) OpenBitSet.intersectionCount(rMn, cMj);
contig[0][1] = (int) OpenBitSet.intersectionCount(rMj, cMn);
contig[1][1] = (int) OpenBitSet.intersectionCount(rMn, cMn);
double rsq = calculateRSqr(contig[0][0], contig[0][1], contig[1][0], contig[1][1], 2);
//if rsq cannot be calculated or rsq is less than the minimum rsq for a snp to be considered highly correlated, select this snp
if (Double.isNaN(rsq) || rsq < minRsq) {
isSelected.fastSet(nextSite);
break;
}
nextSite++;
if (nextSite >= nsites) break;
nextSnpPos = sba.getPositionInLocus(nextSite);
nextSnpLocus = sba.getLocus(nextSite);
}
firstSite = nextSite;
if (firstSite < nsites) {
firstSnpLocus = nextSnpLocus;
firstSnpPos = nextSnpPos;
isSelected.fastSet(firstSite);
}
}
return isSelected;
}
public static OpenBitSet whichSnpsAreFromSameTag(Alignment alignIn) {
Alignment sba = ConvertSBitTBitPlugin.convertAlignment(alignIn, ConvertSBitTBitPlugin.CONVERT_TYPE.sbit, null);
//if (alignIn instanceof SBitAlignment) sba = (SBitAlignment) alignIn;
//else sba = SBitAlignment.getInstance(alignIn);
int nsites = sba.getSiteCount();
int firstSite = 0;
OpenBitSet isSelected = new OpenBitSet(nsites);
isSelected.fastSet(0);
Locus firstSnpLocus = sba.getLocus(0);
int firstSnpPos = sba.getPositionInLocus(0);
while (firstSite < nsites - 1) {
int nextSite = firstSite + 1;
int nextSnpPos = sba.getPositionInLocus(nextSite);
Locus nextSnpLocus = sba.getLocus(nextSite);
while (firstSnpLocus.equals(nextSnpLocus) && nextSnpPos - firstSnpPos < 64) {
nextSite++;
if (nextSite >= nsites) break;
nextSnpPos = sba.getPositionInLocus(nextSite);
nextSnpLocus = sba.getLocus(nextSite);
}
firstSite = nextSite;
if (firstSite < nsites) {
firstSnpLocus = nextSnpLocus;
firstSnpPos = nextSnpPos;
isSelected.fastSet(firstSite);
}
}
return isSelected;
}
public static OpenBitSet whichSnpsAreFromSameTag(Alignment alignIn, BitSet polybits) {
if (polybits.cardinality() == 0) {
if (polybits instanceof OpenBitSet) return (OpenBitSet) polybits;
else return new OpenBitSet(polybits.getBits(), polybits.getNumWords());
}
Alignment sba = ConvertSBitTBitPlugin.convertAlignment(alignIn, ConvertSBitTBitPlugin.CONVERT_TYPE.sbit, null);
//if (alignIn instanceof SBitAlignment) sba = (SBitAlignment) alignIn;
//else sba = SBitAlignment.getInstance(alignIn);
int nsites = sba.getSiteCount();
int firstSite = 0;
while (!polybits.fastGet(firstSite)) firstSite++;
OpenBitSet isSelected = new OpenBitSet(nsites);
isSelected.fastSet(firstSite);
Locus firstSnpLocus = sba.getLocus(firstSite);
int firstSnpPos = sba.getPositionInLocus(firstSite);
while (firstSite < nsites - 1) {
int nextSite = firstSite + 1;
int nextSnpPos = sba.getPositionInLocus(nextSite);
Locus nextSnpLocus = sba.getLocus(nextSite);
boolean skip = !polybits.fastGet(nextSite) || ( firstSnpLocus.equals(nextSnpLocus) && nextSnpPos - firstSnpPos < 64 && computeRForMissingness(firstSite, nextSite, sba) > 0.8) ;
while (skip) {
boolean validSite = nextSite < nsites;
while (validSite && !polybits.fastGet(nextSite)) {
nextSite++;
validSite = nextSite < nsites;
}
if (validSite) {
nextSnpPos = sba.getPositionInLocus(nextSite);
nextSnpLocus = sba.getLocus(nextSite);
int dist = nextSnpPos - firstSnpPos;
boolean nearbySite = firstSnpLocus.equals(nextSnpLocus) && dist < 64;
double r = computeRForMissingness(firstSite, nextSite, sba);
boolean correlatedSite = r > 0.7;
if (nearbySite && correlatedSite) {
skip = true;
nextSite++;
validSite = nextSite < nsites;
} else skip = false;
//debug
// System.out.println("first site = " + firstSnpPos + ", dist = " + dist + ", r = " + r);
} else skip = false;
}
firstSite = nextSite;
if (firstSite < nsites) {
firstSnpLocus = nextSnpLocus;
firstSnpPos = nextSnpPos;
isSelected.fastSet(firstSite);
}
}
return isSelected;
}
static double calculateRSqr(int countAB, int countAb, int countaB, int countab, int minTaxaForEstimate) {
//this is the Hill & Robertson measure as used in Awadella Science 1999 286:2524
double freqA, freqB, rsqr, nonmissingSampleSize;
nonmissingSampleSize = countAB + countAb + countaB + countab;
if (nonmissingSampleSize < minTaxaForEstimate) {
return Double.NaN;
}
freqA = (double) (countAB + countAb) / nonmissingSampleSize;
freqB = (double) (countAB + countaB) / nonmissingSampleSize;
//Through missing data & incomplete datasets some alleles can be fixed this returns missing value
if ((freqA == 0) || (freqB == 0) || (freqA == 1) || (freqB == 1)) {
return Double.NaN;
}
rsqr = ((double) countAB / nonmissingSampleSize) * ((double) countab / nonmissingSampleSize);
rsqr -= ((double) countaB / nonmissingSampleSize) * ((double) countAb / nonmissingSampleSize);
rsqr *= rsqr;
rsqr /= freqA * (1 - freqA) * freqB * (1 - freqB);
return rsqr;
}
public static OpenBitSet filterSnpsOnLDandDistance(Alignment alignIn) {
return null;
}
public static BitSet[] hetMasker(Alignment a, double estimatedHetFraction) {
//set up Viterbi algorithm
//states in hom, het
//observations = hom, het, missing
TransitionProbability tp = new TransitionProbability();
int nsites = a.getSiteCount();
int ntaxa = a.getSequenceCount();
int chrlen = a.getPositionInLocus(nsites - 1) - a.getPositionInLocus(0);
double phet = estimatedHetFraction;
int totalTransitions = (nsites - 1) * ntaxa /10;
int hetHet = (int) Math.floor(phet*totalTransitions);
int hetHom = 2 * ntaxa;
int[][] transCount = new int[][]{{totalTransitions - hetHet - 2*hetHom, hetHom},{hetHom, hetHet}};
tp.setTransitionCounts(transCount, chrlen, ntaxa);
tp.setPositions(a.getPhysicalPositions());
//count number of het loci
int hetCount = 0;
int nonMissingCount = 0;
for (int s = 0; s < nsites; s++) {
hetCount += a.getHeterozygousCount(s);
nonMissingCount += a.getTotalGametesNotMissing(s) / 2;
}
double estimatedPhet = ((double) hetCount) / ((double) nonMissingCount);
double expectedPhet = 0.08;
double hetGivenHet = Math.min(.9, estimatedPhet/expectedPhet);
double[] initialProb = new double[]{1 - expectedPhet, expectedPhet};
try {
a.optimizeForTaxa(null);
} catch (Exception e) {
a = BitAlignment.getInstance(a, false);
}
BitSet[] taxaStates = new BitSet[ntaxa];
for (int t = 0; t < ntaxa; t++) {
BitSet major = a.getAllelePresenceForAllSites(t, 0);
BitSet minor = a.getAllelePresenceForAllSites(t, 1);
OpenBitSet notMissing = new OpenBitSet(major.getBits(), major.getNumWords());
notMissing.union(minor);
OpenBitSet het = new OpenBitSet(major.getBits(), major.getNumWords());
het.intersect(minor);
double nNotMissing = notMissing.cardinality();
byte[] obs = new byte[nsites];
for (int s = 0; s < nsites; s++) {
if (notMissing.fastGet(s)) {
if (het.fastGet(s)) obs[s] = 1;
else obs[s] = 0;
} else {
obs[s] = 2;
}
}
EmissionProbability ep = new EmissionProbability();
//states rows, observations columns
double[][] probMatrix = new double[2][3];
// homozygous state
probMatrix[0][2] = (nsites - nNotMissing) / ((double) nsites); //observe missing
probMatrix[0][0] = .998 * (1 - probMatrix[0][2]); //observe hom
probMatrix[0][1] = .002 * (1 - probMatrix[0][2]);//observe het
//heterozygous state
probMatrix[1][2] = probMatrix[0][2]; //observe missing
probMatrix[1][0] = (1 - hetGivenHet) * (1 - probMatrix[0][2]); //observe hom
probMatrix[1][1] = hetGivenHet * (1 - probMatrix[0][2]);//observe het
ep.setEmissionProbability(probMatrix);
ViterbiAlgorithm va = new ViterbiAlgorithm(obs, tp, ep, initialProb);
va.calculate();
byte[] states = va.getMostProbableStateSequence();
OpenBitSet bitStates = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) if (states[s] == 1) bitStates.fastSet(s);
taxaStates[t] = bitStates;
}
return taxaStates;
}
public static BitSet ldfilter(Alignment a, int window, double minR, BitSet filterBits) {
try {
a.optimizeForSites(null);
} catch(Exception e) {
a = BitAlignment.getInstance(a, true);
}
int nsites = a.getSiteCount();
OpenBitSet ldbits = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
if (filterBits.fastGet(s)) {
double avgr = neighborLD(a, s, window, filterBits);
if (avgr >= minR) {
ldbits.fastSet(s);
}
}
}
return ldbits;
}
public static double neighborLD(Alignment a, int snp, int window, BitSet filterBits) {
double sumr = 0;
int nsites = a.getSiteCount();
//test next <window> sites or to the end of the chromosome
int site = snp + 10;
int siteCount = 0;
int sitesTestedCount = 0;
while (siteCount < window && site < nsites) {
if (filterBits.fastGet(site)) {
double r = computeGenotypeR(snp, site, a);
if (!Double.isNaN(r)) {
sumr += Math.abs(computeGenotypeR(snp, site, a));
siteCount++;
sitesTestedCount++;
}
}
site++;
}
//test previous <window> sites or to the beginning of the chromosome
site = snp - 10;
siteCount = 0;
while (siteCount < window && site >= 0) {
if (filterBits.fastGet(site)) {
sumr += Math.abs(computeGenotypeR(snp, site, a));
siteCount++;
sitesTestedCount++;
}
site--;
}
return sumr / sitesTestedCount;
}
public MutableNucleotideAlignment imputeUsingPhasedViterbi(PopulationData family, double probHeterozygous, String familyName) {
//call parent alleles by window first for intial estimate
//impute haplotypes using Viterbi without iteration
PhasedEmissionProbability pep = new PhasedEmissionProbability();
//calculate parent allele probability given data
//P(A=N1|y) = P(y|A=N1)/[P(y|A=N1) + P(y|A=N2)]
int nsites = family.imputed.getSiteCount();
int ntaxa = family.imputed.getSequenceCount();
double[][][] alleleProb = new double[nsites][4][4]; //1st dim is site (node), 2nd dim is haplotype, 3rd dim is nucleotide (A,C,G,T)
for (int s = 0; s < nsites; s++) {
family.imputed.getSNPID(s);
for (int t = 0; t < ntaxa; t++) {
}
}
return null;
}
}
| src/net/maizegenetics/gwas/imputation/NucleotideImputationUtils.java | package net.maizegenetics.gwas.imputation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import net.maizegenetics.baseplugins.ConvertSBitTBitPlugin;
import org.apache.log4j.Logger;
import net.maizegenetics.baseplugins.TreeDisplayPlugin;
import net.maizegenetics.pal.alignment.Alignment;
import net.maizegenetics.pal.alignment.AlignmentUtils;
import net.maizegenetics.pal.alignment.FilterAlignment;
import net.maizegenetics.pal.alignment.Locus;
import net.maizegenetics.pal.alignment.MutableNucleotideAlignment;
import net.maizegenetics.pal.alignment.NucleotideAlignmentConstants;
import net.maizegenetics.pal.alignment.BitAlignment;
import net.maizegenetics.pal.distance.DistanceMatrix;
import net.maizegenetics.pal.distance.IBSDistanceMatrix;
import net.maizegenetics.pal.ids.IdGroup;
import net.maizegenetics.pal.ids.IdGroupUtils;
import net.maizegenetics.pal.ids.SimpleIdGroup;
import net.maizegenetics.pal.math.GammaFunction;
import net.maizegenetics.pal.tree.Tree;
import net.maizegenetics.pal.tree.TreeClusters;
import net.maizegenetics.pal.tree.UPGMATree;
import net.maizegenetics.plugindef.DataSet;
import net.maizegenetics.plugindef.Datum;
import net.maizegenetics.util.BitSet;
import net.maizegenetics.util.BitUtil;
import net.maizegenetics.util.OpenBitSet;
public class NucleotideImputationUtils {
private static final Logger myLogger = Logger.getLogger(NucleotideImputationUtils.class);
static final byte AA = NucleotideAlignmentConstants.getNucleotideDiploidByte("AA");
static final byte CC = NucleotideAlignmentConstants.getNucleotideDiploidByte("CC");
static final byte GG = NucleotideAlignmentConstants.getNucleotideDiploidByte("GG");
static final byte TT = NucleotideAlignmentConstants.getNucleotideDiploidByte("TT");
static final byte AC = NucleotideAlignmentConstants.getNucleotideDiploidByte("AC");
static final byte AG = NucleotideAlignmentConstants.getNucleotideDiploidByte("AG");
static final byte AT = NucleotideAlignmentConstants.getNucleotideDiploidByte("AT");
static final byte CG = NucleotideAlignmentConstants.getNucleotideDiploidByte("CG");
static final byte CT = NucleotideAlignmentConstants.getNucleotideDiploidByte("CT");
static final byte GT = NucleotideAlignmentConstants.getNucleotideDiploidByte("GT");
static final byte NN = NucleotideAlignmentConstants.getNucleotideDiploidByte("NN");
static final byte CA = NucleotideAlignmentConstants.getNucleotideDiploidByte("CA");
static final byte[] byteval = new byte[] {AA,CC,GG,TT,AC};
final static HashMap<Byte, Integer> genotypeMap = new HashMap<Byte, Integer>();
static{
genotypeMap.put(AA, 0);
genotypeMap.put(CC, 1);
genotypeMap.put(GG, 2);
genotypeMap.put(TT, 3);
genotypeMap.put(AC, 4);
genotypeMap.put(CA, 4);
}
static final byte[][] genoval = new byte[][]{{AA,AC,AG,AT},{AC,CC,CG,CT},{AG,CG,GG,GT},{AT,CT,GT,TT}};
//prevents instantiation of this class
private NucleotideImputationUtils() {}
public static void callParentAlleles(PopulationData popdata, int minAlleleCount, int windowSize, int numberToTry, double cutHeightSnps, double minR) {
BitSet polybits = whichSitesArePolymorphic(popdata.original, minAlleleCount);
int[] coreSnps = findCoreSnps(popdata.original, polybits, windowSize, numberToTry, cutHeightSnps);
String parentA = popdata.parent1;
String parentC = popdata.parent2;
OpenBitSet ldbits = new OpenBitSet(popdata.original.getSiteCount());
int n = coreSnps.length;
for (int i = 0; i < n; i++) ldbits.fastSet(coreSnps[i]);
//debug
examineTaxaClusters(popdata.original, polybits);
IdGroup[] taxaGroup = findTaxaGroups(popdata.original, coreSnps);
//create an alignment for each cluster
IdGroup parentAGroup;
IdGroup parentCGroup;
if (taxaGroup[0].whichIdNumber(parentA) > -1) {
parentAGroup = taxaGroup[0];
parentCGroup = taxaGroup[1];
} else if (taxaGroup[1].whichIdNumber(parentA) > -1) {
parentAGroup = taxaGroup[1];
parentCGroup = taxaGroup[0];
} else if(taxaGroup[0].whichIdNumber(parentC) > -1) {
parentAGroup = taxaGroup[1];
parentCGroup = taxaGroup[0];
} else {
parentAGroup = taxaGroup[0];
parentCGroup = taxaGroup[1];
}
Alignment aAlignment = FilterAlignment.getInstance(popdata.original, parentAGroup);
Alignment cAlignment = FilterAlignment.getInstance(popdata.original, parentCGroup);
byte[] Asnp = new byte[popdata.original.getSiteCount()];
byte[] Csnp = new byte[popdata.original.getSiteCount()];
//set first parent to AA, second parent to CC for snps used to form taxa clusters
//SBitAlignment sbitPopAlignment = SBitAlignment.getInstance(popdata.original);
Alignment sbitPopAlignment = ConvertSBitTBitPlugin.convertAlignment(popdata.original, ConvertSBitTBitPlugin.CONVERT_TYPE.sbit, null);
MutableNucleotideAlignment parentAlignment = MutableNucleotideAlignment.getInstance(sbitPopAlignment);
myLogger.info("snps in parent Alignment = " + parentAlignment.getSiteCount());
int ntaxa = parentAlignment.getSequenceCount();
for (int i = 0; i < coreSnps.length; i++) {
int snp = coreSnps[i];
//debug
int[][] acounts = aAlignment.getAllelesSortedByFrequency(snp);
int[][] ccounts = cAlignment.getAllelesSortedByFrequency(snp);
byte alleleA = aAlignment.getMajorAllele(snp);
byte alleleC = cAlignment.getMajorAllele(snp);
Asnp[snp] = alleleA;
Csnp[snp] = alleleC;
for (int t = 0; t < ntaxa; t++) {
byte[] taxon = popdata.original.getBaseArray(t, snp);
if (taxon[0] == taxon[1]) {
if (taxon[0] == alleleA) parentAlignment.setBase(t, snp, AA);
else if (taxon[0] == alleleC) parentAlignment.setBase(t, snp, CC);
else parentAlignment.setBase(t, snp, NN);
} else if (taxon[0] == alleleA) {
if (taxon[1] == alleleC) parentAlignment.setBase(t, snp, AC);
else parentAlignment.setBase(t, snp, NN);
} else if (taxon[0] == alleleC) {
if (taxon[1] == alleleA) parentAlignment.setBase(t, snp, AC);
else parentAlignment.setBase(t, snp, NN);
} else {
parentAlignment.setBase(t, snp, NN);
}
}
}
//extend haplotypes
//add snps in ld
int testSize = 25;
//add snps from middle to start; test only polymorphic snps
LinkedList<Integer> testSnps = new LinkedList<Integer>();
for (int i = testSize - 1; i >= 0; i--) testSnps.add(coreSnps[i]);
for (int snp = coreSnps[0] - 1; snp >= 0; snp--) {
if (polybits.fastGet(snp)) {
byte[] ac = recodeParentalSnps(snp, testSnps, parentAlignment, minR);
if (ac != null) {
ldbits.fastSet(snp);
testSnps.add(snp);
testSnps.remove();
Asnp[snp] = ac[0];
Csnp[snp] = ac[1];
}
}
}
//add snps from middle to end
testSnps.clear();
n = coreSnps.length;
int nsites = parentAlignment.getSiteCount();
for (int i = n - testSize; i < n; i++) testSnps.add(coreSnps[i]);
for (int snp = coreSnps[n - 1] + 1; snp < nsites; snp++) {
if (polybits.fastGet(snp)) {
byte[] ac = recodeParentalSnps(snp, testSnps, parentAlignment, minR);
if (ac != null) {
ldbits.fastSet(snp);
testSnps.add(snp);
testSnps.remove();
Asnp[snp] = ac[0];
Csnp[snp] = ac[1];
}
}
}
parentAlignment.clean();
n = (int) ldbits.size();
int nRetained = (int) ldbits.cardinality();
popdata.alleleA = new byte[nRetained];
popdata.alleleC = new byte[nRetained];
int[] retainedSites = new int[nRetained];
int snpcount = 0;
for (int i = 0; i < n; i++) {
if (ldbits.fastGet(i)) {
popdata.alleleA[snpcount] = Asnp[i];
popdata.alleleC[snpcount] = Csnp[i];
retainedSites[snpcount++] = i;
}
}
FilterAlignment ldAlignment = FilterAlignment.getInstance(parentAlignment, retainedSites);
popdata.snpIndex = ldbits;
myLogger.info("number of original sites = " + popdata.original.getSiteCount() + ", number of polymorphic sites = " + polybits.cardinality() + ", number of ld sites = " + ldAlignment.getSiteCount());
//popdata.imputed = TBitAlignment.getInstance(ldAlignment);
popdata.imputed = ConvertSBitTBitPlugin.convertAlignment(ldAlignment, ConvertSBitTBitPlugin.CONVERT_TYPE.tbit, null);
}
public static void callParentAllelesByWindow(PopulationData popdata, double maxMissing, double minMaf, int windowSize, double minR) {
BitSet polybits;
double segratio = popdata.contribution1;
if (minMaf < 0 && (segratio == 0.5 || segratio == 0.25 || segratio == 0.75)) {
polybits = whichSitesSegregateCorrectly(popdata.original, maxMissing, segratio);
} else {
if (minMaf < 0) minMaf = 0;
polybits = whichSitesArePolymorphic(popdata.original, maxMissing, minMaf);
}
myLogger.info("polybits cardinality = " + polybits.cardinality());
OpenBitSet filteredBits = whichSnpsAreFromSameTag(popdata.original, polybits);
myLogger.info("filteredBits.cardinality = " + filteredBits.cardinality());
BitSet ldFilteredBits;
if (minR > 0) {
int halfWindow = windowSize / 2;
ldFilteredBits = ldfilter(popdata.original, halfWindow, minR, filteredBits);
} else {
ldFilteredBits = filteredBits;
}
myLogger.info("ldFilteredBits.cardinality = " + ldFilteredBits.cardinality());
int nsites = popdata.original.getSiteCount();
int ntaxa = popdata.original.getSequenceCount();
popdata.alleleA = new byte[nsites];
popdata.alleleC = new byte[nsites];
popdata.snpIndex = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
popdata.alleleA[s] = Alignment.UNKNOWN_ALLELE;
popdata.alleleC[s] = Alignment.UNKNOWN_ALLELE;
}
int[] parentIndex = new int[2];
parentIndex[0] = popdata.original.getIdGroup().whichIdNumber(popdata.parent1);
parentIndex[1] = popdata.original.getIdGroup().whichIdNumber(popdata.parent2);
//iterate through windows
Alignment[] prevAlignment = null;
int[][] snpIndices = getWindows(ldFilteredBits, windowSize);
boolean append = false;
int nWindows = snpIndices.length;
for (int w = 0; w < nWindows; w++) {
int[] snpIndex;
if (append) {
int n1 = snpIndices[w-1].length;
int n2 = snpIndices[w].length;
snpIndex = new int[n1 + n2];
System.arraycopy(snpIndices[w-1], 0, snpIndex, 0, n1);
System.arraycopy(snpIndices[w], 0, snpIndex, n1, n2);
append = false;
} else {
snpIndex = snpIndices[w];
}
//mask the hets
// MutableNucleotideAlignment mna = MutableNucleotideAlignment.getInstance(FilterAlignment.getInstance(popdata.original, snpIndex));
// int n = snpIndex.length;
// byte missing = NucleotideAlignmentConstants.getNucleotideDiploidByte('N');
// for (int i = 0; i < n; i++) {
// for (int t = 0; t < ntaxa; t++) {
// if (hetMask[t].fastGet(snpIndex[i])) mna.setBase(t, i, missing);
// }
// }
// mna.clean();
Alignment windowAlignment = FilterAlignment.getInstance(popdata.original, snpIndex);
LinkedList<Integer> snpList = new LinkedList<Integer>(); //snpList is a list of snps (indices) in this window
for (int s:snpIndex) snpList.add(s);
Alignment[] taxaAlignments = getTaxaGroupAlignments(windowAlignment, parentIndex, snpList);
if (taxaAlignments == null) {
append = true;
} else {
//are groups in this alignment correlated with groups in the previous alignment
double r = 0;
if (prevAlignment != null) {
r = getIdCorrelation(new IdGroup[][] {{prevAlignment[0].getIdGroup(), prevAlignment[1].getIdGroup()},{taxaAlignments[0].getIdGroup(), taxaAlignments[1].getIdGroup()}});
myLogger.info("For " + popdata.name + " the window starting at " + popdata.original.getSNPID(snpIndex[0]) + ", r = " + r + " , # of snps in alignment = " + snpList.size());
} else {
myLogger.info("For " + popdata.name + " the window starting at " + popdata.original.getSNPID(snpIndex[0]) + ", # of snps in alignment = " + snpList.size());
}
checkAlignmentOrderIgnoringParents(taxaAlignments, popdata, r); //if r is negative switch alignment order (which will result in a positive r)
//debug -check upgma tree
// int[] selectSnps = new int[snpList.size()];
// int cnt = 0;
// for (Integer s : snpList) selectSnps[cnt++] = s;
// SBitAlignment sba = SBitAlignment.getInstance(FilterAlignment.getInstance(popdata.original, selectSnps));
// IBSDistanceMatrix dm = new IBSDistanceMatrix(sba);
// estimateMissingDistances(dm);
// Tree myTree = new UPGMATree(dm);
// TreeDisplayPlugin tdp = new TreeDisplayPlugin(null, true);
// tdp.performFunction(new DataSet(new Datum("Snp Tree", myTree, "Snp Tree"), null));
prevAlignment = taxaAlignments;
callParentAllelesUsingTaxaGroups(popdata, taxaAlignments, snpList);
}
}
myLogger.info("number of called snps = " + popdata.snpIndex.cardinality());
//create the imputed array with A/C calls
int nsnps = (int) popdata.snpIndex.cardinality();
ntaxa = popdata.original.getSequenceCount();
nsites = popdata.original.getSiteCount();
int[] snpIndex = new int[nsnps];
int snpcount = 0;
for (int s = 0; s < nsites; s++) {
if (popdata.snpIndex.fastGet(s)) snpIndex[snpcount++] = s;
}
snpIndex = Arrays.copyOf(snpIndex, snpcount);
Alignment target = FilterAlignment.getInstance(popdata.original, snpIndex);
MutableNucleotideAlignment mna = MutableNucleotideAlignment.getInstance(target);
nsnps = snpIndex.length;
for (int s = 0; s < nsnps; s++) {
byte Aallele = popdata.alleleA[snpIndex[s]];
byte Callele = popdata.alleleC[snpIndex[s]];
byte genotypeA = (byte) (Aallele << 4 | Aallele);
byte genotypeC = (byte) (Callele << 4 | Callele);
byte het1 = (byte) (Aallele << 4 | Callele);
byte het2 = (byte) (Callele << 4 | Aallele);
for (int t = 0; t < ntaxa; t++) {
byte val = mna.getBase(t, s);
if (val == genotypeA) {
mna.setBase(t, s, AA);
} else if (val == genotypeC) {
mna.setBase(t, s, CC);
} else if (val == het1 || val == het2) {
mna.setBase(t, s, AC);
} else {
mna.setBase(t, s, NN);
}
}
}
mna.clean();
popdata.imputed = BitAlignment.getInstance(mna, true);
}
public static void callParentAllelesByWindowForBackcrosses(PopulationData popdata, double maxMissing, double minMaf, int windowSize, double minR) {
BitSet polybits = whichSitesSegregateCorrectly(popdata.original, maxMissing, .25);
myLogger.info("polybits cardinality = " + polybits.cardinality());
OpenBitSet filteredBits = whichSnpsAreFromSameTag(popdata.original, 0.8);
filteredBits.and(polybits);
System.out.println("filteredBits.cardinality = " + filteredBits.cardinality());
BitSet ldFilteredBits;
if (minR > 0) {
int halfWindow = windowSize / 2;
ldFilteredBits = ldfilter(popdata.original, halfWindow, minR, filteredBits);
} else {
ldFilteredBits = filteredBits;
}
myLogger.info("ldFilteredBits.cardinality = " + ldFilteredBits.cardinality());
int nsites = popdata.original.getSiteCount();
int ntaxa = popdata.original.getSequenceCount();
popdata.alleleA = new byte[nsites];
popdata.alleleC = new byte[nsites];
popdata.snpIndex = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
if(ldFilteredBits.fastGet(s)) {
popdata.alleleA[s] = popdata.original.getMajorAllele(s);
popdata.alleleC[s] = popdata.original.getMinorAllele(s);
popdata.snpIndex.fastSet(s);
}
}
myLogger.info("number of called snps = " + popdata.snpIndex.cardinality());
//create the imputed array with A/C calls
int nsnps = (int) popdata.snpIndex.cardinality();
ntaxa = popdata.original.getSequenceCount();
nsites = popdata.original.getSiteCount();
int[] snpIndex = new int[nsnps];
int snpcount = 0;
for (int s = 0; s < nsites; s++) {
if (popdata.snpIndex.fastGet(s)) snpIndex[snpcount++] = s;
}
snpIndex = Arrays.copyOf(snpIndex, snpcount);
Alignment target = FilterAlignment.getInstance(popdata.original, snpIndex);
myLogger.info("filtered on snps");
AlignmentUtils.optimizeForTaxa(target);
myLogger.info("optimized for taxa");
//remove taxa with low coverage
boolean[] goodCoverage = new boolean[ntaxa];
int minGametes = 200;
for (int t = 0; t < ntaxa; t++) {
if (target.getTotalGametesNotMissingForTaxon(t) > minGametes) goodCoverage[t] = true;
else goodCoverage[t] = false;
}
myLogger.info("identified low coverage taxa");
IdGroup targetids = IdGroupUtils.idGroupSubset(target.getIdGroup(), goodCoverage);
Alignment target2 = FilterAlignment.getInstance(target, targetids);
myLogger.info("Filtered on taxa.");
MutableNucleotideAlignment mna = MutableNucleotideAlignment.getInstance(target2);
myLogger.info("created mutable alignment.");
nsnps = snpIndex.length;
ntaxa = mna.getSequenceCount();
for (int s = 0; s < nsnps; s++) {
byte Aallele = popdata.alleleA[snpIndex[s]];
byte Callele = popdata.alleleC[snpIndex[s]];
byte genotypeA = (byte) (Aallele << 4 | Aallele);
byte genotypeC = (byte) (Callele << 4 | Callele);
byte het1 = (byte) (Aallele << 4 | Callele);
byte het2 = (byte) (Callele << 4 | Aallele);
for (int t = 0; t < ntaxa; t++) {
byte val = mna.getBase(t, s);
if (val == genotypeA) {
mna.setBase(t, s, AA);
} else if (val == genotypeC) {
mna.setBase(t, s, CC);
} else if (val == het1 || val == het2) {
mna.setBase(t, s, AC);
} else {
mna.setBase(t, s, NN);
}
}
}
myLogger.info("called alleles");
mna.clean();
myLogger.info("cleaned mna");
popdata.imputed = BitAlignment.getInstance(mna, true);
}
public static void callParentAllelesByWindowForMultipleBC(PopulationData popdata, double maxMissing, int minMinorAlleleCount, int windowSize) {
BitSet polybits = whichSitesArePolymorphic(popdata.original, maxMissing, minMinorAlleleCount);
myLogger.info("polybits cardinality = " + polybits.cardinality());
OpenBitSet filteredBits = whichSnpsAreFromSameTag(popdata.original, 0.8);
filteredBits.and(polybits);
System.out.println("filteredBits.cardinality = " + filteredBits.cardinality());
// BitSet ldFilteredBits;
// if (minR > 0) {
// int halfWindow = windowSize / 2;
// ldFilteredBits = ldfilter(popdata.original, halfWindow, minR, filteredBits);
// } else {
// ldFilteredBits = filteredBits;
// }
// myLogger.info("ldFilteredBits.cardinality = " + ldFilteredBits.cardinality());
int nsites = popdata.original.getSiteCount();
int ntaxa = popdata.original.getSequenceCount();
popdata.alleleA = new byte[nsites];
popdata.alleleC = new byte[nsites];
popdata.snpIndex = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
if(filteredBits.fastGet(s)) {
popdata.alleleA[s] = popdata.original.getMajorAllele(s);
popdata.alleleC[s] = popdata.original.getMinorAllele(s);
popdata.snpIndex.fastSet(s);
}
}
myLogger.info("number of called snps = " + popdata.snpIndex.cardinality());
//create the imputed array with A/C calls
int nsnps = (int) popdata.snpIndex.cardinality();
ntaxa = popdata.original.getSequenceCount();
nsites = popdata.original.getSiteCount();
int[] snpIndex = new int[nsnps];
int snpcount = 0;
for (int s = 0; s < nsites; s++) {
if (popdata.snpIndex.fastGet(s)) snpIndex[snpcount++] = s;
}
snpIndex = Arrays.copyOf(snpIndex, snpcount);
Alignment target = FilterAlignment.getInstance(popdata.original, snpIndex);
MutableNucleotideAlignment mna = MutableNucleotideAlignment.getInstance(target);
nsnps = snpIndex.length;
for (int s = 0; s < nsnps; s++) {
byte Aallele = popdata.alleleA[snpIndex[s]];
byte Callele = popdata.alleleC[snpIndex[s]];
byte genotypeA = (byte) (Aallele << 4 | Aallele);
byte genotypeC = (byte) (Callele << 4 | Callele);
byte het1 = (byte) (Aallele << 4 | Callele);
byte het2 = (byte) (Callele << 4 | Aallele);
for (int t = 0; t < ntaxa; t++) {
byte val = mna.getBase(t, s);
if (val == genotypeA) {
mna.setBase(t, s, AA);
} else if (val == genotypeC) {
mna.setBase(t, s, CC);
} else if (val == het1 || val == het2) {
mna.setBase(t, s, AC);
} else {
mna.setBase(t, s, NN);
}
}
}
mna.clean();
popdata.imputed = BitAlignment.getInstance(mna, true);
}
public static void checkAlignmentOrder(Alignment[] alignments, PopulationData family, double r) {
boolean swapAlignments = false;
boolean parentsInSameGroup = false;
boolean parentsInWrongGroups = false;
double minR = -0.05;
int p1group, p2group;
//if parent 1 is in alignment 0, p1group = 0
//if parent1 is in alignment 1, p1group = 1
//if parent 1 is not in either alignment p1group = -1
//likewise for parent 2
if (alignments[0].getIdGroup().whichIdNumber(family.parent1) > -1) p1group = 0;
else if (alignments[1].getIdGroup().whichIdNumber(family.parent1) > -1) p1group = 1;
else p1group = -1;
if (alignments[1].getIdGroup().whichIdNumber(family.parent2) > -1) p2group = 1;
else if (alignments[0].getIdGroup().whichIdNumber(family.parent2) > -1) p2group = 0;
else p2group = -1;
//find out if parents are either in the same group or if they are in groups opposite expected
//parent 1 is expected to be in group 0 since it was used to seed group 0
if (p1group == 0) {
if (p2group == 0) {
parentsInSameGroup = true;
} else if (p2group == 1) {
if (r < 0) parentsInWrongGroups = true;
} else {
if (r < 0) parentsInWrongGroups = true;
}
} else if (p1group == 1) {
if (p2group == 0) {
if (r > 0) parentsInWrongGroups = true;
} else if (p2group == 1) {
parentsInSameGroup = true;
} else {
if (r > 0) parentsInWrongGroups = true;
}
} else {
if (p2group == 0) {
if (r > 0) parentsInWrongGroups = true;
} else if (p2group == 1) {
if (r < 0) parentsInWrongGroups = true;
} else {
//do nothing
}
}
//r is the correlation between taxa assignments in this window and the previous one
//if r is negative then parental assignments should be swapped, which will make it positive
//this can happen when the parents are not in the data set and the assignment of parents to group is arbitrary
if (r < minR) swapAlignments = true;
if (swapAlignments) {
Alignment temp = alignments[0];
alignments[0] = alignments[1];
alignments[1] = temp;
}
if (parentsInSameGroup) {
myLogger.warn("Both parents in the same group for family " + family.name + " at " + alignments[0].getSNPID(0));
}
if (parentsInWrongGroups) {
myLogger.warn("Parents in unexpected group for family " + family.name + " at " + alignments[0].getSNPID(0));
}
}
public static void checkAlignmentOrderIgnoringParents(Alignment[] alignments, PopulationData family, double r) {
boolean swapAlignments = false;
double minR = -0.05;
int p1group, p2group;
//r is the correlation between taxa assignments in this window and the previous one
//if r is negative then parental assignments should be swapped, which will make it positive
//this can happen when the parents are not in the data set and the assignment of parents to group is arbitrary
if (r < minR) swapAlignments = true;
if (swapAlignments) {
Alignment temp = alignments[0];
alignments[0] = alignments[1];
alignments[1] = temp;
}
}
public static int[][] getWindows(BitSet ispoly, int windowSize) {
int npoly = (int) ispoly.cardinality();
int nsnps = (int) ispoly.size();
int nwindows = npoly/windowSize;
int remainder = npoly % windowSize;
if (remainder > windowSize/2) nwindows++; //round up
int[][] windows = new int[nwindows][];
int setsize = npoly/nwindows;
int windowCount = 0;
int snpCount = 0;
int polyCount = 0;
while (snpCount < nsnps && windowCount < nwindows) {
int numberLeft = npoly - polyCount;
if (numberLeft < setsize * 2) setsize = numberLeft;
int[] set = new int[setsize];
int setcount = 0;
while (setcount < setsize && snpCount < nsnps) {
if (ispoly.fastGet(snpCount)) {
set[setcount++] = snpCount;
polyCount++;
}
snpCount++;
}
windows[windowCount++] = set;
}
return windows;
}
/**
* @param family a PopulationData object containing information for this family
* @param taxaGroups an array of two alignments corresponding to two clusters of taxa
* @param snpList the list of snps to be called
*/
public static void callParentAllelesUsingTaxaGroups(PopulationData family, Alignment[] taxaGroups, LinkedList<Integer> snpList) {
int nsnps = taxaGroups[0].getSiteCount();
Iterator<Integer> snpit = snpList.iterator();
for ( int s = 0; s < nsnps; s++) {
byte[] major = new byte[2];
major[0] = taxaGroups[0].getMajorAllele(s);
major[1] = taxaGroups[1].getMajorAllele(s);
Integer snpIndex = snpit.next();
if(major[0] != Alignment.UNKNOWN_ALLELE && major[1] != Alignment.UNKNOWN_ALLELE && major[0] != major[1]) {
family.alleleA[snpIndex] = major[0];
family.alleleC[snpIndex] = major[1];
family.snpIndex.fastSet(snpIndex);
}
}
}
public static double getIdCorrelation(IdGroup[][] id) {
double[][] counts = new double[2][2];
counts[0][0] = IdGroupUtils.getCommonIds(id[0][0], id[1][0]).getIdCount();
counts[0][1] = IdGroupUtils.getCommonIds(id[0][0], id[1][1]).getIdCount();
counts[1][0] = IdGroupUtils.getCommonIds(id[0][1], id[1][0]).getIdCount();
counts[1][1] = IdGroupUtils.getCommonIds(id[0][1], id[1][1]).getIdCount();
double num = counts[0][0] * counts[1][1] - counts[0][1] * counts[1][0];
double p1 = counts[0][0] + counts[0][1];
double q1 = counts[1][0] + counts[1][1];
double p2 = counts[0][0] + counts[1][0];
double q2 = counts[0][1] + counts[1][1];
return num / Math.sqrt(p1 * q1 * p2 * q2);
}
public static BitSet whichSitesArePolymorphic(Alignment a, int minAlleleCount) {
//which sites are polymorphic? minor allele count > 2 and exceed the minimum allele count
int nsites = a.getSiteCount();
OpenBitSet polybits = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
int[][] freq = a.getAllelesSortedByFrequency(s);
if (freq[1].length > 1 && freq[1][1] > 2) {
int alleleCount = freq[1][0] + freq[1][1];
if (alleleCount >= minAlleleCount) polybits.fastSet(s);
}
}
return polybits;
}
public static BitSet whichSitesArePolymorphic(Alignment a, double maxMissing, int minMinorAlleleCount) {
//which sites are polymorphic? minor allele count > 2 and exceed the minimum allele count
int nsites = a.getSiteCount();
int ngametes = 2 * nsites;
int minNotMissingGametes = (int) Math.floor(ngametes * (1 - maxMissing));
OpenBitSet polybits = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
int gametesNotMissing = a.getTotalGametesNotMissing(s);
int minorAlleleCount = a.getMinorAlleleCount(s);
if (gametesNotMissing >= minNotMissingGametes && minorAlleleCount >= minMinorAlleleCount) polybits.fastSet(s);
}
return polybits;
}
public static BitSet whichSitesArePolymorphic(Alignment a, double maxMissing, double minMaf) {
//which sites are polymorphic? minor allele count > 2 and exceed the minimum allele count
int nsites = a.getSiteCount();
int ntaxa = a.getSequenceCount();
double totalgametes = 2 * ntaxa;
OpenBitSet polybits = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
int[][] freq = a.getAllelesSortedByFrequency(s);
int ngametes = a.getTotalGametesNotMissing(s);
double pMissing = (totalgametes - ngametes) / totalgametes;
if (freq[1].length > 1 && freq[1][1] > 2 && pMissing <= maxMissing && a.getMinorAlleleFrequency(s) > minMaf) {
polybits.fastSet(s);
}
}
return polybits;
}
public static BitSet whichSitesSegregateCorrectly(Alignment a, double maxMissing, double ratio) {
int nsites = a.getSiteCount();
int ntaxa = a.getSequenceCount();
double totalgametes = 2 * ntaxa;
OpenBitSet polybits = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
int[][] freq = a.getAllelesSortedByFrequency(s);
int ngametes = a.getTotalGametesNotMissing(s);
double pMissing = (totalgametes - ngametes) / totalgametes;
if (freq[1].length > 1 && pMissing <= maxMissing) {
int Mj = freq[1][0];
int Mn = freq[1][1];
double pmono = binomialProbability(Mj + Mn, Mn, 0.002);
double pquarter = binomialProbability(Mj + Mn, Mn, 0.25);
double phalf = binomialProbability(Mj + Mn, Mn, 0.5);
if (ratio == 0.25 || ratio == 0.75) {
// if (pquarter / (pmono + phalf) > 2) polybits.fastSet(s);
// double poneseven = binomialProbability(Mj + Mn, Mn, .125);
// double pthreefive = binomialProbability(Mj + Mn, Mn, .375);
// if (pquarter > poneseven && pquarter > pthreefive) polybits.fastSet(s);
if (pquarter > phalf && pquarter > pmono) polybits.fastSet(s);
} else {
if (phalf / (pmono + pquarter) > 2) polybits.fastSet(s);
}
}
}
return polybits;
}
private static double binomialProbability(int trials, int successes, double pSuccess) {
double n = trials;
double k = successes;
double logprob = GammaFunction.lnGamma(n + 1.0) -
GammaFunction.lnGamma(k + 1.0) - GammaFunction.lnGamma(n - k + 1.0) + k * Math.log(pSuccess) + (n - k) * Math.log(1 - pSuccess);
return Math.exp(logprob);
}
//returns a byte array containing the A allele as element 0 and the C allele as element 1, or null if the snp is not in LD
public static byte[] recodeParentalSnps(int snp, LinkedList<Integer> testSnps, MutableNucleotideAlignment snpAlignment, double minr) {
int ntaxa = snpAlignment.getSequenceCount();
byte[] snpvals = new byte[ntaxa];
for (int t = 0; t < ntaxa; t++) {
snpvals[t] = snpAlignment.getBase(t, snp);
}
int[] acount = new int[5];
int[] ccount = new int[5];
for (int t = 0; t < ntaxa; t++) {
Integer ndx = genotypeMap.get(snpvals[t]);
if (ndx != null) {
int indx = ndx.intValue();
for (Integer testsnp:testSnps) {
byte testval = snpAlignment.getBase(t, testsnp);
if (testval == AA) acount[ndx]++;
else if (testval == CC) ccount[ndx]++;
}
}
}
//calculate r
int maxa = 0;
int maxc = 0;
for (int i = 1; i < 4; i++) {
if (acount[i] > acount[maxa]) maxa = i;
if (ccount[i] > ccount[maxc]) maxc = i;
}
int[][] counts = new int[2][2];
int N = 0;
N += acount[maxa];
N += acount[maxc];
N += ccount[maxa];
N += ccount[maxc];
double sumx = acount[maxa] + acount[maxc];
double sumy = acount[maxa] + ccount[maxa];
double sumxy = acount[maxa];
double r = (sumxy - sumx * sumy / N) / Math.sqrt( (sumx - sumx * sumx / N) * (sumy - sumy * sumy / N) );
r = Math.abs(r);
//if abs(r) > minr, recode the snp
if ( maxa != maxc && r >= minr) {
byte hetval = genoval[maxa][maxc];
for (int t = 0; t < ntaxa; t++) {
byte val = snpvals[t];
if (val == byteval[maxa]) snpAlignment.setBase(t, snp, AA);
else if (val == byteval[maxc]) snpAlignment.setBase(t, snp, CC);
else if (val == hetval) snpAlignment.setBase(t, snp, AC);
else snpAlignment.setBase(t, snp, NN);
}
return new byte[]{(byte) maxa, (byte) maxc};
}
return null;
}
/**
* This function finds a set of snps within a window of the specified size (100) that are in LD with each other. It trys multiple windows and uses the
* window that yields the largest number of snps.
* @param a the input alignment
* @param polybits a BitSet corresponding to SNPs in a, set if a snp is polymorphic. Only polymorphic SNPs will be considered.
* @param numberToTry the number of windows to try. The function will use the window returning the largest set of SNPs.
* @return indices of the core snps.
*/
public static int[] findCoreSnps(Alignment a, BitSet polybits, int windowSize, int numberToTry, double cutHeightForSnpClusters) {
//define a window
int totalpoly = (int) polybits.cardinality();
int[][] snpSets = new int[numberToTry][];
//find windowSize polymorphic snps centered on the midpoint
int snpInterval = totalpoly / (numberToTry + 1);
int start = - windowSize / 2;
int snpCount = 0;
int polyCount = 0;
int nsites = a.getSiteCount();
for (int setnum = 0; setnum < numberToTry; setnum++) {
start += snpInterval;
if (start < 0) start = 0;
while (polyCount < start) {
if (polybits.fastGet(snpCount)) polyCount++;
snpCount++;
}
int[] snpIds = new int[windowSize];
int windowCount = 0;
while (windowCount < windowSize && snpCount < nsites) {
if (polybits.fastGet(snpCount)) {
snpIds[windowCount++] = snpCount;
polyCount++;
}
snpCount++;
}
//adjust the size of the array if all the snps were used before the array was filled
if (windowCount < windowSize) snpIds = Arrays.copyOf(snpIds, windowCount);
//create a filtered alignment containing only the test snps
FilterAlignment filteredPopAlignment = FilterAlignment.getInstance(a, snpIds);
//cluster polymorphic snps within the window by creating a UPGMA tree (cluster on snps)
Alignment haplotypeAlignment = BitAlignment.getInstance(filteredPopAlignment, true);
UPGMATree myTree = new UPGMATree(snpDistance(haplotypeAlignment));
//debug - display the tree
// TreeDisplayPlugin tdp = new TreeDisplayPlugin(null, true);
// tdp.performFunction(new DataSet(new Datum("Snp Tree", myTree, "Snp Tree"), null));
//cut the tree to create two parent groups
TreeClusters clusterMaker = new TreeClusters(myTree);
int[] groups = clusterMaker.getGroups(cutHeightForSnpClusters);
//find the biggest group
int maxGroup = 0;
for (int grp:groups) maxGroup = Math.max(maxGroup, grp);
int ngroups = maxGroup + 1;
int[] groupCount = new int[ngroups];
for (int grp:groups) groupCount[grp]++;
int[]groupIndex = ImputationUtils.reverseOrder(groupCount);
snpSets[setnum] = new int[ groupCount[groupIndex[0]] ];
int count = 0;
for (int i = 0; i < snpIds.length; i++) {
if (groups[i] == groupIndex[0]) {
int snpIndex = Integer.parseInt(myTree.getIdentifier(i).getFullName());
snpSets[setnum][count++] = snpIds[snpIndex];
}
}
Arrays.sort(snpSets[setnum]);
}
int bestSet = 0;
for (int i = 1; i < numberToTry; i++) {
if (snpSets[i].length > snpSets[bestSet].length) bestSet = i;
}
return snpSets[bestSet];
}
public static IdGroup[] findTaxaGroups(Alignment a, int[] coreSnps) {
//cluster taxa for these snps to find parental haplotypes (cluster on taxa)
//IBSDistanceMatrix dm = new IBSDistanceMatrix(SBitAlignment.getInstance(FilterAlignment.getInstance(a, coreSnps)));
IBSDistanceMatrix dm = new IBSDistanceMatrix(ConvertSBitTBitPlugin.convertAlignment(FilterAlignment.getInstance(a, coreSnps), ConvertSBitTBitPlugin.CONVERT_TYPE.sbit, null));
estimateMissingDistances(dm);
Tree myTree = new UPGMATree(dm);
TreeClusters clusterMaker = new TreeClusters(myTree);
int ntaxa = a.getSequenceCount();
int majorCount = ntaxa;
int minorCount = 0;
int ngroups = 1;
int[] groups = new int[0];
int[] groupCount = null;
int majorGroup = 0;
int minorGroup = 1;
while (majorCount > ntaxa / 2 && minorCount < 10) {
ngroups++;
groups = clusterMaker.getGroups(ngroups);
groupCount = new int[ngroups];
for (int gr : groups) groupCount[gr]++;
for (int i = 1; i < ngroups; i++) {
if (groupCount[i] > groupCount[majorGroup]) {
minorGroup = majorGroup;
majorGroup = i;
} else if (groupCount[i] > groupCount[minorGroup]) minorGroup = i;
}
majorCount = groupCount[majorGroup];
minorCount = groupCount[minorGroup];
}
//debug - display the tree
TreeDisplayPlugin tdp = new TreeDisplayPlugin(null, true);
tdp.performFunction(new DataSet(new Datum("Snp Tree", myTree, "Snp Tree"), null));
//List groups
for (int i = 0; i < ngroups; i++) {
if (groupCount[i] > 5) myLogger.info("Taxa group " + i + " has " + groupCount[i] + " members.");
}
//create major and minor id groups
String[] majorids = new String[groupCount[majorGroup]];
String[] minorids = new String[groupCount[minorGroup]];
majorCount = 0;
minorCount = 0;
for (int i = 0; i < groups.length; i++) {
if (groups[i] == majorGroup) majorids[majorCount++] = myTree.getIdentifier(i).getFullName();
else if (groups[i] == minorGroup) minorids[minorCount++] = myTree.getIdentifier(i).getFullName();
}
IdGroup majorTaxa = new SimpleIdGroup(majorids);
IdGroup minorTaxa = new SimpleIdGroup(minorids);
return new IdGroup[]{majorTaxa,minorTaxa};
}
public static Alignment[] getTaxaGroupAlignments(Alignment a, int[] parentIndex, LinkedList<Integer> snpIndices) {
//cluster taxa for these snps to find parental haplotypes (cluster on taxa)
Alignment[] taxaClusters = ImputationUtils.getTwoClusters(a, 20);
LinkedList<Integer> originalList = new LinkedList<Integer>(snpIndices);
int nsites = a.getSiteCount();
boolean[] include = new boolean[nsites];
int[] includedSnps = new int[nsites];
int snpcount = 0;
for (int s = 0; s < nsites; s++) {
Integer snpIndex = snpIndices.remove();
if ( taxaClusters[0].getMajorAllele(s) != taxaClusters[1].getMajorAllele(s) ) {
// if ( taxaClusters[0].getMajorAllele(s) != Alignment.UNKNOWN_ALLELE && taxaClusters[1].getMajorAllele(s) != Alignment.UNKNOWN_ALLELE &&
// taxaClusters[0].getMajorAlleleFrequency(s) > .6 && taxaClusters[1].getMajorAlleleFrequency(s) > .6) {
// include[s] = true;
// includedSnps[snpcount++] = s;
// snpIndices.add(snpIndex);
// } else include[s] = false;
include[s] = true;
includedSnps[snpcount++] = s;
snpIndices.add(snpIndex);
} else {
// System.out.println("alleles equal at " + s);
// include[s] = false;
include[s] = false;
}
}
if (snpcount > 5) {
includedSnps = Arrays.copyOf(includedSnps, snpcount);
if (snpcount == nsites) return taxaClusters;
else return ImputationUtils.getTwoClusters(FilterAlignment.getInstance(a, includedSnps), 20);
} else {
snpIndices.clear();
snpIndices.addAll(originalList);
return taxaClusters;
}
}
public static void estimateMissingDistances(DistanceMatrix dm) {
int nsize = dm.getSize();
//average distance
double totalDistance = 0;
int count = 0;
for (int i = 0; i < nsize; i++) {
for (int j = i + 1; j < nsize; j++) {
double distance = dm.getDistance(i, j);
if (!Double.isNaN(distance)) {
totalDistance += dm.getDistance(i, j);
count++;
}
}
}
double avgDist = totalDistance / count;
for (int i = 0; i < nsize; i++) {
if ( Double.isNaN(dm.getDistance(i,i)) ) dm.setDistance(i, i, 0);
for (int j = i + 1; j < nsize; j++) {
if ( Double.isNaN(dm.getDistance(i,j)) ) {
dm.setDistance(i, j, avgDist);
}
}
}
}
public static DistanceMatrix snpDistance(Alignment a) {
int nsnps = a.getSiteCount();
SimpleIdGroup snpIds = new SimpleIdGroup(nsnps, true);
double[][] distance = new double[nsnps][nsnps];
double sum = 0;
int count = 0;
for (int i = 0; i < nsnps; i++) {
for (int j = i; j < nsnps; j++) {
double r = computeGenotypeR(i, j, a);
distance[i][j] = distance[j][i] = 1 - r*r;
if (!Double.isNaN(distance[i][j])) {
sum += distance[i][j];
count++;
}
}
}
//set missing to average
double avg = sum/count;
for (int i = 0; i < nsnps; i++) {
for (int j = i; j < nsnps; j++) {
if (Double.isNaN(distance[i][j])) {
distance[i][j] = distance[j][i] = avg;
}
}
}
return new DistanceMatrix(distance, snpIds);
}
public static double computeRForAlleles(int site1, int site2, Alignment a) {
int s1Count = 0;
int s2Count = 0;
int prodCount = 0;
int totalCount = 0;
long[] m11 = a.getAllelePresenceForAllTaxa(site1, 0).getBits();
long[] m12 = a.getAllelePresenceForAllTaxa(site1, 1).getBits();
long[] m21 = a.getAllelePresenceForAllTaxa(site2, 0).getBits();
long[] m22 = a.getAllelePresenceForAllTaxa(site2, 1).getBits();
int n = m11.length;
for (int i = 0; i < n; i++) {
long valid = (m11[i] ^ m12[i]) & (m21[i] ^ m22[i]); //only count non-het & non-missing
long s1major = m11[i] & valid;
long s2major = m21[i] & valid;
long s1s2major = s1major & s2major & valid;
s1Count += BitUtil.pop(s1major);
s2Count += BitUtil.pop(s2major);
prodCount += BitUtil.pop(s1s2major);
totalCount += BitUtil.pop(valid);
}
if (totalCount < 2) return Double.NaN;
//Explanation of method:
// if major site one is x=1, minor site one is x = 0 and for site 2 y = 1 or 0
// r = [sum(xy) - sum(x)sum(y)/N] / sqrt[(sum(x) - sum(x)*sum(x)/N) * ((sum(y) - sum(y)*sum(y)/N)]
// and sum(x) - sum(x)*sum(x)/N = sum(x)(N - sum(x))/N
// because sum(x^2) = sum(x)
double num = ((double) prodCount - ((double) s1Count * s2Count) / ((double) totalCount));
double denom = ((double) (s1Count * (totalCount - s1Count))) / ((double) totalCount);
denom *= ((double) (s2Count * (totalCount - s2Count))) / ((double) totalCount);
if (denom == 0) return Double.NaN;
return num / Math.sqrt(denom);
}
public static double computeRForMissingness(int site1, int site2, Alignment a) {
// int s1Count = 0;
// int s2Count = 0;
// int prodCount = 0;
int totalCount = a.getSequenceCount();
BitSet m11 = a.getAllelePresenceForAllTaxa(site1, 0);
BitSet m12 = a.getAllelePresenceForAllTaxa(site1, 1);
BitSet m21 = a.getAllelePresenceForAllTaxa(site2, 0);
BitSet m22 = a.getAllelePresenceForAllTaxa(site2, 1);
OpenBitSet s1present = new OpenBitSet(m11.getBits(), m11.getNumWords());
s1present.union(m12);
OpenBitSet s2present = new OpenBitSet(m21.getBits(), m21.getNumWords());
s2present.union(m22);
long s1Count = s1present.cardinality();
long s2Count = s2present.cardinality();
long prodCount = OpenBitSet.intersectionCount(s1present, s2present);
//Explanation of method:
// if major site one is x=1, minor site one is x = 0 and for site 2 y = 1 or 0
// r = [sum(xy) - sum(x)sum(y)/N] / sqrt[(sum(x) - sum(x)*sum(x)/N) * ((sum(y) - sum(y)*sum(y)/N)]
// and sum(x) - sum(x)*sum(x)/N = sum(x)(N - sum(x))/N
// because sum(x^2) = sum(x)
double num = ((double) prodCount - ((double) s1Count * s2Count) / ((double) totalCount));
double denom = ((double) (s1Count * (totalCount - s1Count))) / ((double) totalCount);
denom *= ((double) (s2Count * (totalCount - s2Count))) / ((double) totalCount);
if (denom == 0) return Double.NaN;
return num / Math.sqrt(denom);
}
public static double computeGenotypeR(int site1, int site2, Alignment a) throws IllegalStateException {
BitSet s1mj = a.getAllelePresenceForAllTaxa(site1, 0);
BitSet s1mn = a.getAllelePresenceForAllTaxa(site1, 1);
BitSet s2mj = a.getAllelePresenceForAllTaxa(site2, 0);
BitSet s2mn = a.getAllelePresenceForAllTaxa(site2, 1);
OpenBitSet bothpresent = new OpenBitSet(s1mj.getBits(), s1mj.getNumWords());
bothpresent.union(s1mn);
OpenBitSet s2present = new OpenBitSet(s2mj.getBits(), s2mj.getNumWords());
s2present.union(s2mn);
bothpresent.intersect(s2present);
long nsites = s1mj.capacity();
double sum1 = 0;
double sum2 = 0;
double sumsq1 = 0;
double sumsq2 = 0;
double sumprod = 0;
double count = 0;
for (long i = 0; i < nsites; i++) {
if (bothpresent.fastGet(i)) {
double val1 = 0;
double val2 = 0;
if (s1mj.fastGet(i)) {
if (s1mn.fastGet(i)) {
val1++;
} else {
val1 += 2;
}
}
if (s2mj.fastGet(i)) {
if (s2mn.fastGet(i)) {
val2++;
} else {
val2 += 2;
}
}
sum1 += val1;
sumsq1 += val1*val1;
sum2 += val2;
sumsq2 += val2*val2;
sumprod += val1*val2;
count++;
}
}
//r = sum(xy)/sqrt[sum(x2)*sum(y2)], where x = X - Xbar and y = Y - Ybar
//num.r = sum(XY) - 1/n * sum(X)sum(y)
//denom.r = sqrt[ (sum(XX) - 1/n*sum(X)sum(X)) * (sum(YY) - 1/n*sum(Y)sum(Y)) ]
double num = sumprod - sum1 / count * sum2;
double denom = Math.sqrt( (sumsq1 - sum1 / count * sum1) * (sumsq2 - sum2 / count * sum2) );
if (denom == 0) return Double.NaN;
return num / denom;
}
public static MutableNucleotideAlignment imputeUsingViterbiFiveState(Alignment a, double probHeterozygous, String familyName) {
return imputeUsingViterbiFiveState(a, probHeterozygous, familyName, false);
}
public static MutableNucleotideAlignment imputeUsingViterbiFiveState(Alignment a, double probHeterozygous, String familyName, boolean useVariableRecombitionRates) {
a = ConvertSBitTBitPlugin.convertAlignment(a, ConvertSBitTBitPlugin.CONVERT_TYPE.tbit, null);
//states are in {all A; 3A:1C; 1A:1C, 1A:3C; all C}
//obs are in {A, C, M}, where M is heterozygote A/C
int maxIterations = 50;
HashMap<Byte, Byte> obsMap = new HashMap<Byte, Byte>();
obsMap.put(AA, (byte) 0);
obsMap.put(AC, (byte) 1);
obsMap.put(CA, (byte) 1);
obsMap.put(CC, (byte) 2);
int ntaxa = a.getSequenceCount();
int nsites = a.getSiteCount();
//initialize the transition matrix
double[][] transition = new double[][] {
{.999,.0001,.0003,.0001,.0005},
{.0002,.999,.00005,.00005,.0002},
{.0002,.00005,.999,.00005,.0002},
{.0002,.00005,.00005,.999,.0002},
{.0005,.0001,.0003,.0001,.999}
};
TransitionProbability tp;
if (useVariableRecombitionRates) {
tp = new TransitionProbabilityWithVariableRecombination(a.getLocusName(0));
} else {
tp = new TransitionProbability();
}
tp.setTransitionProbability(transition);
int chrlength = a.getPositionInLocus(nsites - 1) - a.getPositionInLocus(0);
tp.setAverageSegmentLength( chrlength / nsites );
//initialize the emission matrix, states (5) in rows, observations (3) in columns
double[][] emission = new double[][] {
{.998,.001,.001},
{.6,.2,.2},
{.4,.2,.4},
{.2,.2,.6},
{.001,.001,.998}
};
EmissionProbability ep = new EmissionProbability();
ep.setEmissionProbability(emission);
//set up indices to non-missing data
ArrayList<BitSet> notMissingIndex = new ArrayList<BitSet>();
int[] notMissingCount = new int[ntaxa];
ArrayList<byte[]> nonMissingObs = new ArrayList<byte[]>();
ArrayList<int[]> snpPositions = new ArrayList<int[]>();
for (int t = 0; t < ntaxa; t++) {
long[] bits = a.getAllelePresenceForAllSites(t, 0).getBits();
BitSet notMiss = new OpenBitSet(bits, bits.length);
notMiss.or(a.getAllelePresenceForAllSites(t, 1));
notMissingIndex.add(notMiss);
notMissingCount[t] = (int) notMiss.cardinality();
}
for (int t = 0; t < ntaxa; t++) {
byte[] obs = new byte[notMissingCount[t]];
int[] pos = new int[notMissingCount[t]];
nonMissingObs.add(obs);
snpPositions.add(pos);
BitSet isNotMissing = notMissingIndex.get(t);
int nmcount = 0;
for (int s = 0; s < nsites; s++) {
byte base = a.getBase(t, s);
if (isNotMissing.fastGet(s) && obsMap.get(a.getBase(t, s)) == null) {
myLogger.info("null from " + Byte.toString(base));
}
if (isNotMissing.fastGet(s)) {
obs[nmcount] = obsMap.get(a.getBase(t, s));
pos[nmcount++] = a.getPositionInLocus(s);
}
}
}
double phom = (1 - probHeterozygous) / 2;
double[] pTrue = new double[]{phom, .25*probHeterozygous ,.5 * probHeterozygous, .25*probHeterozygous, phom};
//iterate
ArrayList<byte[]> bestStates = new ArrayList<byte[]>();
int[][] previousStateCount = new int[5][3];
int iter = 0;
boolean hasNotConverged = true;
while (iter < maxIterations && hasNotConverged) {
//apply Viterbi
myLogger.info("Iteration " + iter++ + " for " + familyName);
bestStates.clear();
for (int t = 0; t < ntaxa; t++) {
tp.setPositions(snpPositions.get(t));
int nobs = notMissingCount[t];
if (nobs >= 20) {
ViterbiAlgorithm va = new ViterbiAlgorithm(nonMissingObs.get(t), tp, ep, pTrue);
va.calculate();
bestStates.add(va.getMostProbableStateSequence());
} else { //do not impute if obs < 20
myLogger.info("Fewer then 20 observations for " + a.getTaxaName(t));
byte[] states = new byte[nobs];
byte[] obs = nonMissingObs.get(t);
for (int i = 0; i < nobs; i++) {
if (obs[i] == AA) states[i] = 0;
else if (obs[i] == CC) states[i] = 4;
else states[i] = 2;
}
bestStates.add(states);
}
}
//re-estimate transition probabilities
int[][] transitionCounts = new int[5][5];
double[][] transitionProb = new double[5][5];
for (int t = 0; t < ntaxa; t++) {
byte[] states = bestStates.get(t);
for (int s = 1; s < notMissingCount[t]; s++) {
transitionCounts[states[s-1]][states[s]]++;
}
}
//transition is prob(state2 | state1) = count(cell)/count(row)
for (int row = 0; row < 5; row++) {
double rowsum = 0;
for (int col = 0; col < 5; col++) rowsum += transitionCounts[row][col];
for (int col = 0; col < 5; col++) transitionProb[row][col] = ((double) transitionCounts[row][col]) / rowsum;
}
tp.setTransitionCounts(transitionCounts, chrlength, ntaxa);
//re-estimate emission probabilities
int[][] emissionCounts = new int[5][3];
double[][] emissionProb = new double[5][3];
for (int t = 0; t < ntaxa; t++) {
byte[] obs = nonMissingObs.get(t);
byte[] states = bestStates.get(t);
for (int s = 0; s < notMissingCount[t]; s++) {
emissionCounts[states[s]][obs[s]]++;
}
}
//debug - print observation/state counts
// StringBuilder strb = new StringBuilder("Imputation counts, rows=states, columns=observations:\n");
// for (int[] row:emissionCounts) {
// for (int cell:row) {
// strb.append(cell).append("\t");
// }
// strb.append("\n");
// }
// strb.append("\n");
// myLogger.info(strb.toString());
//check to see if there is a change in the observation/state counts
hasNotConverged = false;
for (int r = 0; r < 5; r++) {
for (int c = 0; c < 3; c++) {
if (previousStateCount[r][c] != emissionCounts[r][c]) {
hasNotConverged = true;
previousStateCount[r][c] = emissionCounts[r][c];
}
}
}
//emission is prob(obs | state) = count(cell)/count(row)
double[] rowSums = new double[5];
double total = 0;
for (int row = 0; row < 5; row++) {
double rowsum = 0;
for (int col = 0; col < 3; col++) rowsum += emissionCounts[row][col];
for (int col = 0; col < 3; col++) emissionProb[row][col] = ((double) emissionCounts[row][col]) / rowsum;
rowSums[row] = rowsum;
total += rowsum;
}
ep.setEmissionProbability(emissionProb);
//re-estimate pTrue
for (int i = 0; i < 5; i++) {
pTrue[i
] = rowSums[i] / total;
}
//if the model has converged or if the max iterations has been reached print tables
if (!hasNotConverged || iter == maxIterations) {
StringBuilder sb = new StringBuilder("Family ");
sb.append(familyName).append(", chromosome ").append(a.getLocusName(0));
if (iter < maxIterations) {
sb.append(": EM algorithm converged at iteration ").append(iter).append(".\n");
} else {
sb.append(": EM algorithm failed to converge after ").append(iter).append(" iterations.\n");
}
//print transition counts
sb = new StringBuilder("Transition counts from row to column:\n");
for (int[] row:transitionCounts) {
for (int cell:row) {
sb.append(cell).append("\t");
}
sb.append("\n");
}
sb.append("\n");
myLogger.info(sb.toString());
//print transition probabilities
sb = new StringBuilder("Transition probabilities:\n");
for (double[] row:transitionProb) {
for (double cell:row) {
sb.append(cell).append("\t");
}
sb.append("\n");
}
sb.append("\n");
myLogger.info(sb.toString());
//print observation/state counts
sb = new StringBuilder("Imputation counts, rows=states, columns=observations:\n");
for (int[] row:emissionCounts) {
for (int cell:row) {
sb.append(cell).append("\t");
}
sb.append("\n");
}
sb.append("\n");
myLogger.info(sb.toString());
//print emission probabilities
sb = new StringBuilder("Emission probabilities:\n");
for (double[] row:emissionProb) {
for (double cell:row) {
sb.append(cell).append("\t");
}
sb.append("\n");
}
sb.append("\n");
myLogger.info(sb.toString());
}
}
MutableNucleotideAlignment result = MutableNucleotideAlignment.getInstance(a);
nsites = result.getSiteCount();
for (int t = 0; t < ntaxa; t++) {
BitSet hasData = notMissingIndex.get(t);
byte[] states = bestStates.get(t);
int stateCount = 0;
for (int s = 0; s < nsites; s++) {
if (hasData.fastGet(s)) {
if (states[stateCount] == 0) result.setBase(t, s, AA);
else if (states[stateCount] < 4) result.setBase(t, s, AC);
else if (states[stateCount] == 4) result.setBase(t, s, CC);
stateCount++;
}
}
}
result.clean();
return result;
}
public static void fillGapsInAlignment(PopulationData popdata) {
MutableNucleotideAlignment a;
if (popdata.imputed instanceof MutableNucleotideAlignment) {
a = (MutableNucleotideAlignment) popdata.imputed;
} else {
a = MutableNucleotideAlignment.getInstance(popdata.imputed);
popdata.imputed = a;
}
int ntaxa = a.getSequenceCount();
int nsites = a.getSiteCount();
for (int t = 0; t < ntaxa; t++) {
int prevsite = -1;
byte prevValue = -1;
for (int s = 0; s < nsites; s++) {
byte val = a.getBase(t, s);
if (val != NN) {
if (prevsite == -1) {
prevsite = s;
prevValue = val;
} else if(val == prevValue) {
for (int site = prevsite + 1; site < s; site++) {
a.setBase(t, site, prevValue);
prevsite = s;
}
} else {
prevsite = s;
prevValue = val;
}
}
}
}
a.clean();
popdata.imputed = a;
}
public static Alignment convertParentCallsToNucleotides(PopulationData popdata) {
//set monomorphic sites to major (or only allele) (or not)
//set polymorphic sites consistent with flanking markers if equal, unchanged otherwise
//do not change sites that are not clearly monomorhpic or polymorphic
MutableNucleotideAlignment mna = MutableNucleotideAlignment.getInstance(popdata.imputed);
BitSet isPopSnp = popdata.snpIndex;
if (isPopSnp.cardinality() != mna.getSiteCount()) myLogger.info("size of imputed snps not equal to snpIndex cardinality in convertParentCallsToNucleotides.");
int nsites = (int) isPopSnp.capacity();
double ngametes = nsites * 2;
int ntaxa = mna.getSequenceCount();
int imputedSnpCount = 0;
for (int s = 0; s < nsites; s++) {
if (isPopSnp.fastGet(s)) {
int Acall = popdata.alleleA[s];
int Ccall = popdata.alleleC[s];
byte AAcall = (byte) ((Acall << 4) | Acall);
byte CCcall = (byte) ((Ccall << 4) | Ccall);
byte ACcall = (byte) ((Acall << 4) | Ccall);
for (int t = 0; t < ntaxa; t++) {
byte parentCall = popdata.imputed.getBase(t, imputedSnpCount);
if (parentCall == AA) {
mna.setBase(t, imputedSnpCount, AAcall);
} else if (parentCall == CC) {
mna.setBase(t, imputedSnpCount, CCcall);
} else if (parentCall == AC || parentCall == CA) {
mna.setBase(t, imputedSnpCount, ACcall);
} else {
mna.setBase(t, imputedSnpCount, NN);
}
}
imputedSnpCount++;
}
}
mna.clean();
myLogger.info("Original alignment updated for family " + popdata.name + " chromosome " + popdata.original.getLocusName(0) + ".\n");
return mna;
}
public static void examineTaxaClusters(Alignment a, BitSet polybits) {
int nsnps = a.getSiteCount();
int ntaxa = a.getSequenceCount();
int sitecount = 500;
int window = 200;
while (sitecount < nsnps) {
int[] snpndx = new int[window];
int snpcount = 0;
while (snpcount < window && sitecount < nsnps) {
if (polybits.fastGet(sitecount)) snpndx[snpcount++] = sitecount;
sitecount++;
}
if (sitecount < nsnps) {
Alignment subAlignment = BitAlignment.getInstance(FilterAlignment.getInstance(a, snpndx), true);
IBSDistanceMatrix dm = new IBSDistanceMatrix(subAlignment);
estimateMissingDistances(dm);
Tree myTree = new UPGMATree(dm);
TreeClusters tc = new TreeClusters(myTree);
int[] groups = null;
int[] order = null;
int ngrp = 2;
while (true) {
groups = tc.getGroups(ngrp);
int[] grpSize = new int[ngrp];
for (int g:groups) grpSize[g]++;
order = ImputationUtils.reverseOrder(grpSize);
if (((double) grpSize[order[0]]) / ((double) grpSize[order[1]]) < 2.0) {
String[] taxaA = new String[grpSize[order[0]]];
String[] taxaB = new String[grpSize[order[1]]];
int cntA = 0;
int cntB = 0;
for (int t = 0; t < ntaxa; t++) {
String taxon = myTree.getIdentifier(t).getFullName();
if (groups[t] == order[0]) taxaA[cntA++] = taxon;
else if (groups[t] == order[1]) taxaB[cntB++] = taxon;
}
Alignment alignA = FilterAlignment.getInstance(subAlignment, new SimpleIdGroup(taxaA));
Alignment alignB = FilterAlignment.getInstance(subAlignment, new SimpleIdGroup(taxaB));
boolean[] include = new boolean[window];
for (int s = 0; s < window; s++) {
if (alignA.getMajorAllele(s) != alignB.getMajorAllele(s)) {
if ( ((double) alignA.getMajorAlleleCount(s))/((double) alignA.getMinorAlleleCount(s)) > 2.0 && ((double) alignB.getMajorAlleleCount(s))/((double) alignB.getMinorAlleleCount(s)) > 2.0) {
include[s] = true;
} else include[s] = false;
} else {
System.out.println("alleles equal at " + s);
include[s] = false;
}
}
int ngoodsnps = 0;
for (boolean b:include) if (b) ngoodsnps++;
int[] goodSnpIndex = new int[ngoodsnps];
int cnt = 0;
for (int s = 0; s < window; s++) {
if (include[s]) goodSnpIndex[cnt++] = s;
}
IBSDistanceMatrix dm2 = new IBSDistanceMatrix(BitAlignment.getInstance(FilterAlignment.getInstance(subAlignment, goodSnpIndex), true));
estimateMissingDistances(dm2);
Tree thisTree = new UPGMATree(dm2);
//display the tree
TreeDisplayPlugin tdp = new TreeDisplayPlugin(null, true);
tdp.performFunction(new DataSet(new Datum("Snp Tree", thisTree, "Snp Tree"), null));
System.out.println("n good snps = " + ngoodsnps);
break;
}
// else if (ngrp > 2) {
// if (((double) grpSize[order[0]]) / ((double) (grpSize[order[1]] + grpSize[order[2]])) < 1.5) {
//
// }
// }
ngrp++;
if (ngrp > 20) break;
}
//display the tree
TreeDisplayPlugin tdp = new TreeDisplayPlugin(null, true);
tdp.performFunction(new DataSet(new Datum("Snp Tree", myTree, "Snp Tree"), null));
}
}
}
/**
* SNPs on the same tag will have correlated errors. While alignments do not have information about which SNPs come from the same tag, SNPs from one tag will be <64 bp distant.
* They will also be highly correlated. This function tests removes the second of any pair of SNPs that could come from the same tag.
* @param alignIn the input Alignment
* @return an alignment with the one of any correlated pairs of SNPs removed
*/
public static Alignment removeSNPsFromSameTag(Alignment alignIn, double minRsq) {
Alignment sba = ConvertSBitTBitPlugin.convertAlignment(alignIn, ConvertSBitTBitPlugin.CONVERT_TYPE.sbit, null);
//if (alignIn instanceof SBitAlignment) sba = (SBitAlignment) alignIn;
//else sba = SBitAlignment.getInstance(alignIn);
int nsites = sba.getSiteCount();
int ntaxa = sba.getSequenceCount();
int firstSite = 0;
int[] sitesSelected = new int[nsites];
int selectCount = 0;
sitesSelected[selectCount++] = 0;
String firstSnpLocus = sba.getLocus(0).getName();
int firstSnpPos = sba.getPositionInLocus(0);
while (firstSite < nsites - 1) {
int nextSite = firstSite + 1;
int nextSnpPos = sba.getPositionInLocus(nextSite);
String nextSnpLocus = sba.getLocus(nextSite).getName();
while (firstSnpLocus.equals(nextSnpLocus) && nextSnpPos - firstSnpPos < 64) {
//calculate r^2 between snps
BitSet rMj = sba.getAllelePresenceForAllTaxa(firstSite, 0);
BitSet rMn = sba.getAllelePresenceForAllTaxa(firstSite, 1);
BitSet cMj = sba.getAllelePresenceForAllTaxa(nextSite, 0);
BitSet cMn = sba.getAllelePresenceForAllTaxa(nextSite, 1);
int n = 0;
int[][] contig = new int[2][2];
n += contig[0][0] = (int) OpenBitSet.intersectionCount(rMj, cMj);
n += contig[1][0] = (int) OpenBitSet.intersectionCount(rMn, cMj);
n += contig[0][1] = (int) OpenBitSet.intersectionCount(rMj, cMn);
n += contig[1][1] = (int) OpenBitSet.intersectionCount(rMn, cMn);
double rsq = calculateRSqr(contig[0][0], contig[0][1], contig[1][0], contig[1][1], 2);
if (Double.isNaN(rsq) || rsq >= minRsq) sitesSelected[selectCount++] = nextSite;
nextSite++;
nextSnpPos = sba.getPositionInLocus(nextSite);
nextSnpLocus = sba.getLocus(nextSite).getName();
}
firstSite = nextSite;
firstSnpLocus = nextSnpLocus;
firstSnpPos = nextSnpPos;
sitesSelected[selectCount++] = firstSite;
}
return FilterAlignment.getInstance(sba, sitesSelected);
}
public static OpenBitSet whichSnpsAreFromSameTag(Alignment alignIn, double minRsq) {
Alignment sba = ConvertSBitTBitPlugin.convertAlignment(alignIn, ConvertSBitTBitPlugin.CONVERT_TYPE.sbit, null);
//if (alignIn instanceof SBitAlignment) sba = (SBitAlignment) alignIn;
//else sba = SBitAlignment.getInstance(alignIn);
int nsites = sba.getSiteCount();
int firstSite = 0;
OpenBitSet isSelected = new OpenBitSet(nsites);
isSelected.fastSet(0);
Locus firstSnpLocus = sba.getLocus(0);
int firstSnpPos = sba.getPositionInLocus(0);
while (firstSite < nsites - 1) {
int nextSite = firstSite + 1;
int nextSnpPos = sba.getPositionInLocus(nextSite);
Locus nextSnpLocus = sba.getLocus(nextSite);
while (firstSnpLocus.equals(nextSnpLocus) && nextSnpPos - firstSnpPos < 64) {
//calculate r^2 between snps
BitSet rMj = sba.getAllelePresenceForAllTaxa(firstSite, 0);
BitSet rMn = sba.getAllelePresenceForAllTaxa(firstSite, 1);
BitSet cMj = sba.getAllelePresenceForAllTaxa(nextSite, 0);
BitSet cMn = sba.getAllelePresenceForAllTaxa(nextSite, 1);
int[][] contig = new int[2][2];
contig[0][0] = (int) OpenBitSet.intersectionCount(rMj, cMj);
contig[1][0] = (int) OpenBitSet.intersectionCount(rMn, cMj);
contig[0][1] = (int) OpenBitSet.intersectionCount(rMj, cMn);
contig[1][1] = (int) OpenBitSet.intersectionCount(rMn, cMn);
double rsq = calculateRSqr(contig[0][0], contig[0][1], contig[1][0], contig[1][1], 2);
//if rsq cannot be calculated or rsq is less than the minimum rsq for a snp to be considered highly correlated, select this snp
if (Double.isNaN(rsq) || rsq < minRsq) {
isSelected.fastSet(nextSite);
break;
}
nextSite++;
if (nextSite >= nsites) break;
nextSnpPos = sba.getPositionInLocus(nextSite);
nextSnpLocus = sba.getLocus(nextSite);
}
firstSite = nextSite;
if (firstSite < nsites) {
firstSnpLocus = nextSnpLocus;
firstSnpPos = nextSnpPos;
isSelected.fastSet(firstSite);
}
}
return isSelected;
}
public static OpenBitSet whichSnpsAreFromSameTag(Alignment alignIn) {
Alignment sba = ConvertSBitTBitPlugin.convertAlignment(alignIn, ConvertSBitTBitPlugin.CONVERT_TYPE.sbit, null);
//if (alignIn instanceof SBitAlignment) sba = (SBitAlignment) alignIn;
//else sba = SBitAlignment.getInstance(alignIn);
int nsites = sba.getSiteCount();
int firstSite = 0;
OpenBitSet isSelected = new OpenBitSet(nsites);
isSelected.fastSet(0);
Locus firstSnpLocus = sba.getLocus(0);
int firstSnpPos = sba.getPositionInLocus(0);
while (firstSite < nsites - 1) {
int nextSite = firstSite + 1;
int nextSnpPos = sba.getPositionInLocus(nextSite);
Locus nextSnpLocus = sba.getLocus(nextSite);
while (firstSnpLocus.equals(nextSnpLocus) && nextSnpPos - firstSnpPos < 64) {
nextSite++;
if (nextSite >= nsites) break;
nextSnpPos = sba.getPositionInLocus(nextSite);
nextSnpLocus = sba.getLocus(nextSite);
}
firstSite = nextSite;
if (firstSite < nsites) {
firstSnpLocus = nextSnpLocus;
firstSnpPos = nextSnpPos;
isSelected.fastSet(firstSite);
}
}
return isSelected;
}
public static OpenBitSet whichSnpsAreFromSameTag(Alignment alignIn, BitSet polybits) {
if (polybits.cardinality() == 0) {
if (polybits instanceof OpenBitSet) return (OpenBitSet) polybits;
else return new OpenBitSet(polybits.getBits(), polybits.getNumWords());
}
Alignment sba = ConvertSBitTBitPlugin.convertAlignment(alignIn, ConvertSBitTBitPlugin.CONVERT_TYPE.sbit, null);
//if (alignIn instanceof SBitAlignment) sba = (SBitAlignment) alignIn;
//else sba = SBitAlignment.getInstance(alignIn);
int nsites = sba.getSiteCount();
int firstSite = 0;
while (!polybits.fastGet(firstSite)) firstSite++;
OpenBitSet isSelected = new OpenBitSet(nsites);
isSelected.fastSet(firstSite);
Locus firstSnpLocus = sba.getLocus(firstSite);
int firstSnpPos = sba.getPositionInLocus(firstSite);
while (firstSite < nsites - 1) {
int nextSite = firstSite + 1;
int nextSnpPos = sba.getPositionInLocus(nextSite);
Locus nextSnpLocus = sba.getLocus(nextSite);
boolean skip = !polybits.fastGet(nextSite) || ( firstSnpLocus.equals(nextSnpLocus) && nextSnpPos - firstSnpPos < 64 && computeRForMissingness(firstSite, nextSite, sba) > 0.8) ;
while (skip) {
boolean validSite = true;
while (validSite && !polybits.fastGet(nextSite)) {
nextSite++;
validSite = nextSite < nsites;
}
if (validSite) {
nextSnpPos = sba.getPositionInLocus(nextSite);
nextSnpLocus = sba.getLocus(nextSite);
int dist = nextSnpPos - firstSnpPos;
boolean nearbySite = firstSnpLocus.equals(nextSnpLocus) && dist < 64;
double r = computeRForMissingness(firstSite, nextSite, sba);
boolean correlatedSite = r > 0.7;
if (nearbySite && correlatedSite) {
skip = true;
nextSite++;
validSite = nextSite < nsites;
} else skip = false;
//debug
// System.out.println("first site = " + firstSnpPos + ", dist = " + dist + ", r = " + r);
} else skip = false;
}
firstSite = nextSite;
if (firstSite < nsites) {
firstSnpLocus = nextSnpLocus;
firstSnpPos = nextSnpPos;
isSelected.fastSet(firstSite);
}
}
return isSelected;
}
static double calculateRSqr(int countAB, int countAb, int countaB, int countab, int minTaxaForEstimate) {
//this is the Hill & Robertson measure as used in Awadella Science 1999 286:2524
double freqA, freqB, rsqr, nonmissingSampleSize;
nonmissingSampleSize = countAB + countAb + countaB + countab;
if (nonmissingSampleSize < minTaxaForEstimate) {
return Double.NaN;
}
freqA = (double) (countAB + countAb) / nonmissingSampleSize;
freqB = (double) (countAB + countaB) / nonmissingSampleSize;
//Through missing data & incomplete datasets some alleles can be fixed this returns missing value
if ((freqA == 0) || (freqB == 0) || (freqA == 1) || (freqB == 1)) {
return Double.NaN;
}
rsqr = ((double) countAB / nonmissingSampleSize) * ((double) countab / nonmissingSampleSize);
rsqr -= ((double) countaB / nonmissingSampleSize) * ((double) countAb / nonmissingSampleSize);
rsqr *= rsqr;
rsqr /= freqA * (1 - freqA) * freqB * (1 - freqB);
return rsqr;
}
public static OpenBitSet filterSnpsOnLDandDistance(Alignment alignIn) {
return null;
}
public static BitSet[] hetMasker(Alignment a, double estimatedHetFraction) {
//set up Viterbi algorithm
//states in hom, het
//observations = hom, het, missing
TransitionProbability tp = new TransitionProbability();
int nsites = a.getSiteCount();
int ntaxa = a.getSequenceCount();
int chrlen = a.getPositionInLocus(nsites - 1) - a.getPositionInLocus(0);
double phet = estimatedHetFraction;
int totalTransitions = (nsites - 1) * ntaxa /10;
int hetHet = (int) Math.floor(phet*totalTransitions);
int hetHom = 2 * ntaxa;
int[][] transCount = new int[][]{{totalTransitions - hetHet - 2*hetHom, hetHom},{hetHom, hetHet}};
tp.setTransitionCounts(transCount, chrlen, ntaxa);
tp.setPositions(a.getPhysicalPositions());
//count number of het loci
int hetCount = 0;
int nonMissingCount = 0;
for (int s = 0; s < nsites; s++) {
hetCount += a.getHeterozygousCount(s);
nonMissingCount += a.getTotalGametesNotMissing(s) / 2;
}
double estimatedPhet = ((double) hetCount) / ((double) nonMissingCount);
double expectedPhet = 0.08;
double hetGivenHet = Math.min(.9, estimatedPhet/expectedPhet);
double[] initialProb = new double[]{1 - expectedPhet, expectedPhet};
try {
a.optimizeForTaxa(null);
} catch (Exception e) {
a = BitAlignment.getInstance(a, false);
}
BitSet[] taxaStates = new BitSet[ntaxa];
for (int t = 0; t < ntaxa; t++) {
BitSet major = a.getAllelePresenceForAllSites(t, 0);
BitSet minor = a.getAllelePresenceForAllSites(t, 1);
OpenBitSet notMissing = new OpenBitSet(major.getBits(), major.getNumWords());
notMissing.union(minor);
OpenBitSet het = new OpenBitSet(major.getBits(), major.getNumWords());
het.intersect(minor);
double nNotMissing = notMissing.cardinality();
byte[] obs = new byte[nsites];
for (int s = 0; s < nsites; s++) {
if (notMissing.fastGet(s)) {
if (het.fastGet(s)) obs[s] = 1;
else obs[s] = 0;
} else {
obs[s] = 2;
}
}
EmissionProbability ep = new EmissionProbability();
//states rows, observations columns
double[][] probMatrix = new double[2][3];
// homozygous state
probMatrix[0][2] = (nsites - nNotMissing) / ((double) nsites); //observe missing
probMatrix[0][0] = .998 * (1 - probMatrix[0][2]); //observe hom
probMatrix[0][1] = .002 * (1 - probMatrix[0][2]);//observe het
//heterozygous state
probMatrix[1][2] = probMatrix[0][2]; //observe missing
probMatrix[1][0] = (1 - hetGivenHet) * (1 - probMatrix[0][2]); //observe hom
probMatrix[1][1] = hetGivenHet * (1 - probMatrix[0][2]);//observe het
ep.setEmissionProbability(probMatrix);
ViterbiAlgorithm va = new ViterbiAlgorithm(obs, tp, ep, initialProb);
va.calculate();
byte[] states = va.getMostProbableStateSequence();
OpenBitSet bitStates = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) if (states[s] == 1) bitStates.fastSet(s);
taxaStates[t] = bitStates;
}
return taxaStates;
}
public static BitSet ldfilter(Alignment a, int window, double minR, BitSet filterBits) {
try {
a.optimizeForSites(null);
} catch(Exception e) {
a = BitAlignment.getInstance(a, true);
}
int nsites = a.getSiteCount();
OpenBitSet ldbits = new OpenBitSet(nsites);
for (int s = 0; s < nsites; s++) {
if (filterBits.fastGet(s)) {
double avgr = neighborLD(a, s, window, filterBits);
if (avgr >= minR) {
ldbits.fastSet(s);
}
}
}
return ldbits;
}
public static double neighborLD(Alignment a, int snp, int window, BitSet filterBits) {
double sumr = 0;
int nsites = a.getSiteCount();
//test next <window> sites or to the end of the chromosome
int site = snp + 10;
int siteCount = 0;
int sitesTestedCount = 0;
while (siteCount < window && site < nsites) {
if (filterBits.fastGet(site)) {
double r = computeGenotypeR(snp, site, a);
if (!Double.isNaN(r)) {
sumr += Math.abs(computeGenotypeR(snp, site, a));
siteCount++;
sitesTestedCount++;
}
}
site++;
}
//test previous <window> sites or to the beginning of the chromosome
site = snp - 10;
siteCount = 0;
while (siteCount < window && site >= 0) {
if (filterBits.fastGet(site)) {
sumr += Math.abs(computeGenotypeR(snp, site, a));
siteCount++;
sitesTestedCount++;
}
site--;
}
return sumr / sitesTestedCount;
}
public MutableNucleotideAlignment imputeUsingPhasedViterbi(PopulationData family, double probHeterozygous, String familyName) {
//call parent alleles by window first for intial estimate
//impute haplotypes using Viterbi without iteration
PhasedEmissionProbability pep = new PhasedEmissionProbability();
//calculate parent allele probability given data
//P(A=N1|y) = P(y|A=N1)/[P(y|A=N1) + P(y|A=N2)]
int nsites = family.imputed.getSiteCount();
int ntaxa = family.imputed.getSequenceCount();
double[][][] alleleProb = new double[nsites][4][4]; //1st dim is site (node), 2nd dim is haplotype, 3rd dim is nucleotide (A,C,G,T)
for (int s = 0; s < nsites; s++) {
family.imputed.getSNPID(s);
for (int t = 0; t < ntaxa; t++) {
}
}
return null;
}
}
| Fixed bug… boolean validSite = true; to boolean validSite = nextSite < nsites; -Jason
| src/net/maizegenetics/gwas/imputation/NucleotideImputationUtils.java | Fixed bug… boolean validSite = true; to boolean validSite = nextSite < nsites; -Jason |
|
Java | mit | 21ab4ab10eda3ceb2506a61dc22f62f956850e60 | 0 | reigntech/Team02 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package FanManager.model;
import java.io.Serializable;
public class Fan implements Serializable {
/**
* For serialization/deserialization to check class version.
*/
private static final long serialVersionUID = -7621164129293024859L;
private boolean isOn;
private double power;
private double duty;
private double speed;
private double minStartingTemp;
private double minRunningTemp;
private double minSpeed;
private double maxSpeed;
private double temperature;
// Constructor
//
public Fan() {
this(0.0, 0.0, 0.0, 70, 60, 0.0, 100.0, 70.0);
}
public Fan(double speed, Fan f){
this.power = f.power;
this.duty = f.duty;
this.minStartingTemp = f.minStartingTemp;
this.minRunningTemp = f.minRunningTemp;
this.minSpeed = f.minSpeed;
this.maxSpeed = f.maxSpeed;
this.temperature = f.temperature;
setSpeed(speed);
}
public Fan(double power, double duty, double speed,
double minStartingTemp, double minRunningTemp,
double minSpeed, double maxSpeed, double temperature) {
super();
this.power = power;
this.duty = duty;
this.minStartingTemp = minStartingTemp;
this.minRunningTemp = minRunningTemp;
this.minSpeed = minSpeed;
this.maxSpeed = maxSpeed;
this.temperature = temperature;
setSpeed(speed);
}
// Turn Off
//
public void turnOff() {
isOn = false;
this.power = 0;
this.duty = 0;
setSpeed(0);
}
// Turn On
//
public void turnOn(double power, double duty, double speed) {
isOn = true;
this.power = power;
this.duty = duty;
setSpeed(speed);
}
public void turnOn(double power, double duty) {
isOn = true;
this.power = power;
this.duty = duty;
setSpeed(minSpeed);
}
// Getters & Setters
//
// Is On?
public boolean isOn() {
return isOn;
}
// Power
public double getPower() {
return power;
}
public void setPower(double power) {
this.power = power;
}
// Duty
public double getDuty() {
return duty;
}
public void setDuty(double duty) {
this.duty = duty;
}
// Speed
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
if (isOn && this.speed + speed > this.maxSpeed) {
this.speed = this.maxSpeed;
} else if (isOn && this.speed + speed < this.minSpeed) {
this.speed = this.minSpeed;
} else {
this.speed = speed;
}
}
// Temperature
public double getTemperature() {
return temperature;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
// Minimum Starting Temperature
public double getMinStartingTemp() {
return minStartingTemp;
}
public void setMinStartingTemp(double minStartingTemp) {
this.minStartingTemp = minStartingTemp;
}
// Minimum Running Temperature
public double getMinRunningTemp() {
return minRunningTemp;
}
public void setMinRunningTemp(double minRunningTemp) {
this.minRunningTemp = minRunningTemp;
}
// Minimum Speed
public double getMinSpeed() {
return minSpeed;
}
public void setMinSpeed(double minSpeed) {
this.minSpeed = minSpeed;
}
// Maximum Speed
public double getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(double maxSpeed) {
this.maxSpeed = maxSpeed;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Fan) {
Fan temp = (Fan) obj;
if (this.isOn == temp.isOn
&& this.power == temp.power
&& this.duty == temp.duty
&& this.speed == temp.speed
&& this.minStartingTemp == temp.minStartingTemp
&& this.minRunningTemp == temp.minRunningTemp
&& this.minSpeed == temp.minSpeed
&& this.maxSpeed == temp.maxSpeed
&& this.temperature == temp.temperature) {
return true;
}
}
return false;
}
}
| FanManager_01.02/src/FanManager/model/Fan.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package FanManager.model;
import java.io.Serializable;
public class Fan implements Serializable {
/**
* For serialization/deserialization to check class version.
*/
private static final long serialVersionUID = -7621164129293024859L;
private boolean isOn;
private double power;
private double duty;
private double speed;
private double minStartingTemp;
private double minRunningTemp;
private double minSpeed;
private double maxSpeed;
private double temperature;
// Constructor
//
public Fan() {
this(0.0, 0.0, 0.0, 70, 60, 0.0, 100.0, 70.0);
}
public Fan(double power, double duty, double speed,
double minStartingTemp, double minRunningTemp,
double minSpeed, double maxSpeed, double temperature) {
super();
this.power = power;
this.duty = duty;
this.minStartingTemp = minStartingTemp;
this.minRunningTemp = minRunningTemp;
this.minSpeed = minSpeed;
this.maxSpeed = maxSpeed;
this.temperature = temperature;
setSpeed(speed);
}
// Turn Off
//
public void turnOff() {
isOn = false;
this.power = 0;
this.duty = 0;
setSpeed(0);
}
// Turn On
//
public void turnOn(double power, double duty, double speed) {
isOn = true;
this.power = power;
this.duty = duty;
setSpeed(speed);
}
public void turnOn(double power, double duty) {
isOn = true;
this.power = power;
this.duty = duty;
setSpeed(minSpeed);
}
// Getters & Setters
//
// Is On?
public boolean isOn() {
return isOn;
}
// Power
public double getPower() {
return power;
}
public void setPower(double power) {
this.power = power;
}
// Duty
public double getDuty() {
return duty;
}
public void setDuty(double duty) {
this.duty = duty;
}
// Speed
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
if (isOn && this.speed + speed > this.maxSpeed) {
this.speed = this.maxSpeed;
} else if (isOn && this.speed + speed < this.minSpeed) {
this.speed = this.minSpeed;
} else {
this.speed = speed;
}
}
// Temperature
public double getTemperature() {
return temperature;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
// Minimum Starting Temperature
public double getMinStartingTemp() {
return minStartingTemp;
}
public void setMinStartingTemp(double minStartingTemp) {
this.minStartingTemp = minStartingTemp;
}
// Minimum Running Temperature
public double getMinRunningTemp() {
return minRunningTemp;
}
public void setMinRunningTemp(double minRunningTemp) {
this.minRunningTemp = minRunningTemp;
}
// Minimum Speed
public double getMinSpeed() {
return minSpeed;
}
public void setMinSpeed(double minSpeed) {
this.minSpeed = minSpeed;
}
// Maximum Speed
public double getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(double maxSpeed) {
this.maxSpeed = maxSpeed;
}
}
| Add new Fan constructor using speed and second Fan object;
Add equals method | FanManager_01.02/src/FanManager/model/Fan.java | Add new Fan constructor using speed and second Fan object; Add equals method |
|
Java | mit | 3766a149053651583e8c55a146fe6de7af351e87 | 0 | hvarona/smartcoins-wallet,computationalcore/smartcoins-wallet,kenCode-de/smartcoins-wallet | package de.bitshares_munich.fragments;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.bitshares_munich.Interfaces.AssetDelegate;
import de.bitshares_munich.Interfaces.ISound;
import de.bitshares_munich.adapters.TransactionsTableAdapter;
import de.bitshares_munich.models.AccountAssets;
import de.bitshares_munich.models.AccountDetails;
import de.bitshares_munich.models.AccountUpgrade;
import de.bitshares_munich.models.EquivalentComponentResponse;
import de.bitshares_munich.models.EquivalentFiatStorage;
import de.bitshares_munich.models.LtmFee;
import de.bitshares_munich.models.TransactionDetails;
import de.bitshares_munich.smartcoinswallet.AssestsActivty;
import de.bitshares_munich.smartcoinswallet.AssetsSymbols;
import de.bitshares_munich.smartcoinswallet.AudioFilePath;
import de.bitshares_munich.smartcoinswallet.MediaService;
import de.bitshares_munich.smartcoinswallet.R;
import de.bitshares_munich.smartcoinswallet.RecieveActivity;
import de.bitshares_munich.smartcoinswallet.SendScreen;
import de.bitshares_munich.smartcoinswallet.pdfTable;
import de.bitshares_munich.smartcoinswallet.qrcodeActivity;
import de.bitshares_munich.utils.Application;
import de.bitshares_munich.utils.Crypt;
import de.bitshares_munich.utils.Helper;
import de.bitshares_munich.utils.PermissionManager;
import de.bitshares_munich.utils.IWebService;
import de.bitshares_munich.utils.ServiceGenerator;
import de.bitshares_munich.utils.SupportMethods;
import de.bitshares_munich.utils.TinyDB;
import de.bitshares_munich.utils.TransactionActivity;
import de.bitshares_munich.utils.tableViewClickListener;
import de.bitshares_munich.utils.transactionsDateComparator;
import de.bitshares_munich.utils.webSocketCallHelper;
import de.codecrafters.tableview.SortableTableView;
import de.codecrafters.tableview.TableDataAdapter;
import de.codecrafters.tableview.toolkit.SimpleTableHeaderAdapter;
import de.codecrafters.tableview.toolkit.SortStateViewProviders;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by qasim on 5/10/16.
*/
public class BalancesFragment extends Fragment implements AssetDelegate ,ISound{
public static Activity balanceActivity;
static Boolean audioSevice = false;
Application application = new Application();
int accountDetailsId;
String accountId = "";
DecimalFormat df = new DecimalFormat("0.0");
Boolean isLoading = false;
public static Boolean onClicked = false;
Handler myHandler = new Handler();
String to = "";
String wifkey = "";
String finalFaitCurrency;
@Bind(R.id.load_more_values)
Button load_more_values;
@Bind(R.id.scrollViewBalances)
ScrollView scrollViewBalances;
@Bind(R.id.backLine)
View backLine;
@Bind(R.id.progressBar)
ProgressBar progressBar;
@Bind(R.id.progressBar1)
ProgressBar progressBar1;
@Bind(R.id.qrCamera)
ImageView qrCamera;
@Bind(R.id.tvBalances)
TextView tvBalances;
@Bind(R.id.tvUpgradeLtm)
TextView tvUpgradeLtm;
@Bind(R.id.llBalances)
LinearLayout llBalances;
int number_of_transactions_loaded = 0;
int number_of_transactions_to_load = 0;
@Bind(R.id.whiteSpaceAfterBalances)
LinearLayout whiteSpaceAfterBalances;
private SortableTableView<TransactionDetails> tableView;
private ArrayList<TransactionDetails> myTransactions;
TinyDB tinyDB;
@Bind(R.id.tableViewparent)
LinearLayout tableViewparent;
@Bind(R.id.account_name)
TextView tvAccountName;
@Bind(R.id.recievebtn)
ImageView recievebtn;
@Bind(R.id.sendbtn)
ImageView sendbtn;
@Bind(R.id.ivLifeTime)
ImageView ivLifeTime;
@Bind(R.id.ivMultiAccArrow)
ImageView ivMultiAccArrow;
ProgressDialog progressDialog;
//Boolean sentCallForTransactions = false;
//Boolean isSavedTransactions = false;
Locale locale;
NumberFormat format;
String language;
public static ISound iSound;
// String ltmAmount="17611.7";
public BalancesFragment() {
// Required empty public constructor
}
webSocketCallHelper myWebSocketHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tinyDB = new TinyDB(getContext());
application.registerAssetDelegate(this);
iSound=this;
updateEquivalentAmount = new Handler();
myWebSocketHelper = new webSocketCallHelper(getContext());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_balances, container, false);
ButterKnife.bind(this, rootView);
language = Helper.fetchStringSharePref(getActivity(), getString(R.string.pref_language));
locale = new Locale(language);
balanceActivity = getActivity();
format = NumberFormat.getInstance(locale);
tvUpgradeLtm.setPaintFlags(tvUpgradeLtm.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
progressDialog = new ProgressDialog(getActivity());
tableView = (SortableTableView<TransactionDetails>) rootView.findViewById(R.id.tableView);
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
assetsSymbols.getAssetsFromServer();
// getAssetsFromServer();
final Handler handler = new Handler();
final Runnable updateTask = new Runnable() {
@Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
setSortableTableViewHeight(rootView, handler, this);
}
});
}
};
final Runnable createFolder = new Runnable() {
@Override
public void run() {
createFolder();
}
};
loadBasic(false,true,false);
loadBalancesFromSharedPref();
TransactionUpdateOnStartUp(to);
handler.postDelayed(updateTask, 2000);
handler.postDelayed(createFolder, 5000);
if (!Helper.containKeySharePref(getActivity(), "ltmAmount")) {
Helper.storeStringSharePref(getActivity(), "ltmAmount", "17611.7");
}
getLtmPrice(getActivity(), tvAccountName.getText().toString());
return rootView;
}
private void setSortableTableViewHeight(View rootView, Handler handler, Runnable task) {
try {
View scrollViewBalances = rootView.findViewById(R.id.scrollViewBalances);
int height1 = scrollViewBalances.getHeight();
if (height1 == 0) {
handler.postDelayed(task, 2000);
return;
}
Log.d("setSortableHeight", "Scroll Heght : " + Long.toString(height1));
View transactionsExportHeader = rootView.findViewById(R.id.transactionsExportHeader);
int height2 = transactionsExportHeader.getHeight();
Log.d("setSortableHeight", "Scroll Header Heght : " + Long.toString(height2));
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tableView.getLayoutParams();
params.height = height1 - height2;
Log.d("setSortableHeight", "View Heght : " + Long.toString(params.height));
tableViewparent.setLayoutParams(params);
Log.d("setSortableHeight", "View Heght Set");
} catch (Exception e) {
Log.d("List Height", e.getMessage());
handler.postDelayed(task, 2000);
}
}
private void createFolder() {
try {
PermissionManager manager = new PermissionManager();
manager.verifyStoragePermissions(getActivity());
final File folder = new File(Environment.getExternalStorageDirectory() + File.separator + getResources().getString(R.string.folder_name));
boolean success = false;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
// Do something on success
Toast.makeText(getContext(), getResources().getString(R.string.txt_folder_created) + " : " + folder.getAbsolutePath(), Toast.LENGTH_LONG).show();
}
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
File file2 = new File(folder.getAbsolutePath(), "Woohoo.wav");
if (!file2.exists()) {
FileOutputStream save = new FileOutputStream(file2);
byte[] buffer = null;
InputStream fIn = getResources().openRawResource(R.raw.woohoo);
int size = 0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
save.write(buffer);
//save.flush();
//save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
save.flush();
save.close();
}
} catch (Exception e) {
}
}
});
}catch (Exception e){}
}
@Override
public void onResume() {
super.onResume();
// Inflate the layout for this fragment
scrollViewBalances.fullScroll(View.FOCUS_UP);
scrollViewBalances.pageScroll(View.FOCUS_UP);
onClicked = false;
final String hide_donations_isChanged = "hide_donations_isChanged";
Boolean isHideDonationsChanged = false;
if (Helper.containKeySharePref(getContext(), hide_donations_isChanged)) {
if (Helper.fetchBoolianSharePref(getContext(), hide_donations_isChanged)) {
isHideDonationsChanged = true;
Helper.storeBoolianSharePref(getContext(), hide_donations_isChanged, false);
}
}
Boolean isCheckedTimeZone=false;
isCheckedTimeZone=Helper.fetchBoolianSharePref(getActivity(),getString(R.string.pre_ischecked_timezone));
Boolean accountNameChange = checkIfAccountNameChange();
if(accountNameChange || (finalFaitCurrency != null && !Helper.getFadeCurrency(getContext()).equals(finalFaitCurrency)) )
llBalances.removeAllViews();
if (isCheckedTimeZone || isHideDonationsChanged || accountNameChange || (finalFaitCurrency != null && !Helper.getFadeCurrency(getContext()).equals(finalFaitCurrency)) )
{
if (finalFaitCurrency != null && !Helper.getFadeCurrency(getContext()).equals(finalFaitCurrency) )
{
loadBasic(true,accountNameChange,true);
}
else
{
loadBasic(true,accountNameChange,false);
}
}
}
@OnClick(R.id.recievebtn)
public void GoToRecieveActivity() {
final Intent intent = new Intent(getActivity(), RecieveActivity.class);
intent.putExtra(getString(R.string.to), to);
intent.putExtra(getString(R.string.account_id), accountId);
Animation coinAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.coin_animation);
coinAnimation.setAnimationListener(new android.view.animation.Animation.AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
startActivity(intent);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
});
recievebtn.startAnimation(coinAnimation);
}
@OnClick(R.id.sendbtn)
public void GoToSendActivity() {
if (isLoading) {
final Intent intent = new Intent(getActivity(), SendScreen.class);
Animation coinAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.coin_animation);
coinAnimation.setAnimationListener(new android.view.animation.Animation.AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
startActivity(intent);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
});
sendbtn.startAnimation(coinAnimation);
} else Toast.makeText(getContext(), R.string.loading_msg, Toast.LENGTH_LONG).show();
}
@OnClick(R.id.tvUpgradeLtm)
public void updateLtm() {
final boolean[] balanceValid = {true};
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.alert_delete_dialog);
final Button btnDone = (Button) dialog.findViewById(R.id.btnDone);
final TextView alertMsg = (TextView) dialog.findViewById(R.id.alertMsg);
alertMsg.setText(getString(R.string.help_message));
final Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
btnCancel.setBackgroundColor(Color.RED);
btnCancel.setText(getString(R.string.txt_no));
btnDone.setText(getString(R.string.next));
btnDone.setOnClickListener(new View.OnClickListener() {
@SuppressLint("StringFormatInvalid")
@Override
public void onClick(View v) {
String ltmAmount=Helper.fetchStringSharePref(getActivity(),"ltmAmount");
//Check Balance
if (btnDone.getText().equals(getString(R.string.next))) {
alertMsg.setText("Upgrade to LTM now? " + ltmAmount + " BTS will be deducted from " + tvAccountName.getText().toString() + " account.");
btnDone.setText(getString(R.string.txt_yes));
btnCancel.setText(getString(R.string.txt_back));
} else {
dialog.cancel();
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
try {
for (int i = 0; i < accountDetails.size(); i++) {
if (accountDetails.get(i).isSelected) {
ArrayList<AccountAssets> arrayListAccountAssets = accountDetails.get(i).AccountAssets;
for (int j = 0; j < arrayListAccountAssets.size(); j++) {
AccountAssets accountAssets = arrayListAccountAssets.get(j);
if (accountAssets.symbol.equalsIgnoreCase("BTS")) {
Double amount = Double.valueOf(SupportMethods.ConvertValueintoPrecision(accountAssets.precision, accountAssets.ammount));
if (amount < Double.parseDouble(ltmAmount)) {
balanceValid[0] = false;
Toast.makeText(getActivity(), getString(R.string.insufficient_funds), Toast.LENGTH_LONG).show();
}
break;
}
}
}
}
} catch (Exception e) {
}
if (balanceValid[0]) {
showDialog("", getString(R.string.upgrading));
getAccountUpgradeInfo(getActivity(), tvAccountName.getText().toString());
}
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (btnCancel.getText().equals(getString(R.string.txt_back))) {
alertMsg.setText(getString(R.string.help_message));
btnCancel.setText(getString(R.string.txt_no));
btnDone.setText(getString(R.string.next));
} else {
dialog.cancel();
}
}
});
dialog.show();
}
@OnClick(R.id.qrCamera)
public void QrCodeActivity() {
if (isLoading) {
final Intent intent = new Intent(getContext(), qrcodeActivity.class);
intent.putExtra("id", 1);
Animation coinAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.coin_animation);
coinAnimation.setAnimationListener(new android.view.animation.Animation.AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
startActivity(intent);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
});
qrCamera.startAnimation(coinAnimation);
} else Toast.makeText(getContext(), R.string.loading_msg, Toast.LENGTH_LONG).show();
}
@OnClick(R.id.exportButton)
public void onExportButton() {
if (isLoading) {
TableDataAdapter myAdapter = tableView.getDataAdapter();
List<TransactionDetails> det = myAdapter.getData();
pdfTable myTable = new pdfTable(getContext(), getActivity(), "Transactions-scwall");
myTable.createTable(det);
} else Toast.makeText(getContext(), R.string.loading_msg, Toast.LENGTH_LONG).show();
}
public void loadBalancesFromSharedPref() {
try {
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
if (accountDetails.size() > 1) {
ivMultiAccArrow.setVisibility(View.VISIBLE);
} else {
ivMultiAccArrow.setVisibility(View.GONE);
}
for (int i = 0; i < accountDetails.size(); i++) {
if (accountDetails.get(i).isSelected)
{
ArrayList<AccountAssets> accountAsset = accountDetails.get(i).AccountAssets;
if ((accountAsset != null) && (accountAsset.size() > 0)) {
ArrayList<String> sym = new ArrayList<>();
ArrayList<String> pre = new ArrayList<>();
ArrayList<String> am = new ArrayList<>();
for (int j = 0; j < accountAsset.size(); j++) {
pre.add(j, accountAsset.get(j).precision);
sym.add(j, accountAsset.get(j).symbol);
am.add(j, accountAsset.get(j).ammount);
}
// getEquivalentComponents(accountAsset);
BalanceAssetsUpdate(sym, pre, am, true);
}
break;
}
}
} catch (Exception e) {
}
}
Handler updateEquivalentAmount;
@Override
public void isUpdate(ArrayList<String> ids, ArrayList<String> sym, ArrayList<String> pre, ArrayList<String> am) {
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
ArrayList<AccountAssets> accountAssets = new ArrayList<>();
for (int i = 0; i < ids.size(); i++)
{
long amount = Long.parseLong(am.get(i));
if ( amount != 0 )
{
AccountAssets accountAsset = new AccountAssets();
accountAsset.id = ids.get(i);
if (pre.size() > i) accountAsset.precision = pre.get(i);
if (sym.size() > i) accountAsset.symbol = sym.get(i);
if (am.size() > i) accountAsset.ammount = am.get(i);
accountAssets.add(accountAsset);
}
}
try
{
for (int i = 0; i < accountDetails.size(); i++) {
if (accountDetails.get(i).isSelected) {
accountDetails.get(i).AccountAssets = accountAssets;
getEquivalentComponents(accountAssets);
break;
}
}
}
catch (Exception w)
{
SupportMethods.testing("Assets", w, "Asset Activity");
}
SupportMethods.testing("Assets", "Assets views 3", "Asset Activity");
tinyDB.putListObject(getString(R.string.pref_wallet_accounts), accountDetails);
SupportMethods.testing("Assets", "Assets views 4", "Asset Activity");
BalanceAssetsUpdate(sym, pre, am, false);
}
public void BalanceAssetsUpdate(final ArrayList<String> sym, final ArrayList<String> pre, final ArrayList<String> am, final Boolean onStartUp) {
int count = llBalances.getChildCount();
// use standard asset names (like add bit etc)
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
ArrayList<String> symbols = assetsSymbols.updatedList(sym);
if (count <= 0)
BalanceAssetsLoad(symbols, pre, am, onStartUp);
if (count > 0)
BalanceAssetsUpdate(symbols, pre, am);
/*
Handler zeroBalanceHandler = new Handler();
Runnable zeroKardo = new Runnable() {
@Override
public void run() {
am.set(0,"0");
BalanceAssetsUpdate(sym, pre, am, false);
}
};
zeroBalanceHandler.postDelayed(zeroKardo,10000);
*/
}
private void getEquivalentComponents(final ArrayList<AccountAssets> accountAssets)
{
//AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
final Runnable getEquivalentCompRunnable = new Runnable() {
@Override
public void run() {
getEquivalentComponents(accountAssets);
}
};
String faitCurrency = Helper.getFadeCurrency(getContext());
if (faitCurrency.isEmpty())
{
faitCurrency = "EUR";
}
final String fc = faitCurrency;
final List<String> pairs = new ArrayList<>();
String values = "";
for (int i = 0; i < accountAssets.size(); i++) {
AccountAssets accountAsset = accountAssets.get(i);
if (!accountAsset.symbol.equals(faitCurrency)) {
values += accountAsset.symbol + ":" + faitCurrency + ",";
pairs.add(accountAsset.symbol + ":" + faitCurrency);
}
}
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("method", "equivalent_component");
hashMap.put("values", values.substring(0, values.length() - 1));
String url;
try
{
url = String.format(Locale.ENGLISH,"%s",getString(R.string.account_from_brainkey_url));
}
catch (Exception e)
{
return;
}
if ( url == null || url.isEmpty() )
{
return;
}
ServiceGenerator sg = new ServiceGenerator(url);
IWebService service = sg.getService(IWebService.class);
final Call<EquivalentComponentResponse> postingService = service.getEquivalentComponent(hashMap);
finalFaitCurrency = faitCurrency;
postingService.enqueue(new Callback<EquivalentComponentResponse>() {
@Override
public void onResponse(Response<EquivalentComponentResponse> response)
{
if (response.isSuccess())
{
EquivalentComponentResponse resp = response.body();
if (resp.status.equals("success"))
{
try
{
JSONObject rates = new JSONObject(resp.rates);
Iterator<String> keys = rates.keys();
HashMap<String,String> hm = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
hm.put(key.split(":")[0], rates.get(key).toString());
if ( pairs.contains(key) )
{
pairs.remove(key);
}
}
if ( getContext() == null ) return;
EquivalentFiatStorage myFiatStorage = new EquivalentFiatStorage(getContext());
myFiatStorage.saveEqHM(fc,hm);
if ( pairs.size() > 0 )
{
getEquivalentComponentsIndirect(pairs,fc);
return;
}
if ( getContext() == null ) return;
hm = myFiatStorage.getEqHM(fc);
for (int i = 0; i < llBalances.getChildCount(); i++)
{
LinearLayout llRow = (LinearLayout) llBalances.getChildAt(i);
for (int j = 1; j <= 2; j++) {
TextView tvAsset;
TextView tvAmount;
TextView tvFaitAmount;
if (j == 1)
{
tvAsset = (TextView) llRow.findViewById(R.id.symbol_child_one);
tvAmount = (TextView) llRow.findViewById(R.id.amount_child_one);
tvFaitAmount = (TextView) llRow.findViewById(R.id.fait_child_one);
}
else
{
tvAsset = (TextView) llRow.findViewById(R.id.symbol_child_two);
tvAmount = (TextView) llRow.findViewById(R.id.amount_child_two);
tvFaitAmount = (TextView) llRow.findViewById(R.id.fait_child_two);
}
if (tvAsset == null || tvAmount == null || tvFaitAmount == null)
{
updateEquivalentAmount.postDelayed(getEquivalentCompRunnable,500);
return;
}
String asset = tvAsset.getText().toString();
String amount = tvAmount.getText().toString();
asset = asset.replace("bit","");
//amount = android.text.Html.fromHtml(amount).toString();
if (amount.isEmpty())
{
amount = "0.0";
}
if (!amount.isEmpty() && hm.containsKey(asset))
{
Currency currency = Currency.getInstance(finalFaitCurrency);
try
{
double d = convertLocalizeStringToDouble(amount);
Double eqAmount = d * convertLocalizeStringToDouble(hm.get(asset).toString());
if ( Helper.isRTL(locale,currency.getSymbol()) )
{
tvFaitAmount.setText(String.format(locale, "%.2f %s", eqAmount,currency.getSymbol()));
}
else
{
tvFaitAmount.setText(String.format(locale, "%s %.2f", currency.getSymbol(),eqAmount));
}
tvFaitAmount.setVisibility(View.VISIBLE);
}
catch (Exception e)
{
tvFaitAmount.setVisibility(View.GONE);
}
}
else
{
tvFaitAmount.setVisibility(View.GONE);
}
}
}
}
catch (JSONException e)
{
updateEquivalentAmount.postDelayed(getEquivalentCompRunnable,500);
//e.printStackTrace();
}
}
else
{
updateEquivalentAmount.postDelayed(getEquivalentCompRunnable,500);
}
}
else
{
hideDialog();
updateEquivalentAmount.postDelayed(getEquivalentCompRunnable,500);
}
}
@Override
public void onFailure(Throwable t)
{
hideDialog();
//Toast.makeText(getActivity(), getString(R.string.txt_no_internet_connection), Toast.LENGTH_SHORT).show();
updateEquivalentAmount.postDelayed(getEquivalentCompRunnable,500);
}
});
}
private void getEquivalentComponentsIndirect(final List<String> leftOvers, final String faitCurrency)
{
//try
//{
final Runnable getEquivalentCompIndirectRunnable = new Runnable() {
@Override
public void run() {
getEquivalentComponentsIndirect(leftOvers, faitCurrency);
}
};
List<String> newPairs = new ArrayList<>();
for (String pair : leftOvers) {
String firstHalf = pair.split(":")[0];
newPairs.add(firstHalf + ":" + "BTS");
}
newPairs.add("BTS" + ":" + faitCurrency);
String values = "";
for (String pair : newPairs) {
values += pair + ",";
}
values = values.substring(0, values.length() - 1);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("method", "equivalent_component");
hashMap.put("values", values);
String url;
try
{
url = String.format(Locale.ENGLISH,"%s",getString(R.string.account_from_brainkey_url));
}
catch (Exception e)
{
return;
}
if ( url == null || url.isEmpty() )
{
return;
}
ServiceGenerator sg = new ServiceGenerator(url);
IWebService service = sg.getService(IWebService.class);
final Call<EquivalentComponentResponse> postingService = service.getEquivalentComponent(hashMap);
postingService.enqueue(new Callback<EquivalentComponentResponse>() {
@Override
public void onResponse(Response<EquivalentComponentResponse> response) {
if (response.isSuccess())
{
EquivalentComponentResponse resp = response.body();
if (resp.status.equals("success"))
{
try {
JSONObject rates = new JSONObject(resp.rates);
Iterator<String> keys = rates.keys();
String btsToFait = "";
while (keys.hasNext()) {
String key = keys.next();
if (key.equals("BTS:" + faitCurrency)) {
btsToFait = rates.get("BTS:" + faitCurrency).toString();
break;
}
}
HashMap<String,String> hm = new HashMap<>();
if (!btsToFait.isEmpty())
{
keys = rates.keys();
while (keys.hasNext())
{
String key = keys.next();
if (!key.equals("BTS:" + faitCurrency)) {
String asset = key.split(":")[0];
String assetConversionToBTS = rates.get(key).toString();
double newConversionRate = convertLocalizeStringToDouble(assetConversionToBTS) * convertLocalizeStringToDouble(btsToFait);
String assetToFaitConversion = Double.toString(newConversionRate);
hm.put(asset, assetToFaitConversion);
}
}
if ( getContext() == null ) return;
EquivalentFiatStorage myFiatStorage = new EquivalentFiatStorage(getContext());
myFiatStorage.saveEqHM(faitCurrency,hm);
}
if ( getContext() == null ) return;
EquivalentFiatStorage myFiatStorage = new EquivalentFiatStorage(getContext());
hm = myFiatStorage.getEqHM(faitCurrency);
for (int i = 0; i < llBalances.getChildCount(); i++) {
LinearLayout llRow = (LinearLayout) llBalances.getChildAt(i);
for (int j = 1; j <= 2; j++) {
TextView tvAsset;
TextView tvAmount;
TextView tvFaitAmount;
if (j == 1) {
tvAsset = (TextView) llRow.findViewById(R.id.symbol_child_one);
tvAmount = (TextView) llRow.findViewById(R.id.amount_child_one);
tvFaitAmount = (TextView) llRow.findViewById(R.id.fait_child_one);
} else {
tvAsset = (TextView) llRow.findViewById(R.id.symbol_child_two);
tvAmount = (TextView) llRow.findViewById(R.id.amount_child_two);
tvFaitAmount = (TextView) llRow.findViewById(R.id.fait_child_two);
}
if (tvAsset == null || tvAmount == null || tvFaitAmount == null) {
updateEquivalentAmount.postDelayed(getEquivalentCompIndirectRunnable, 500);
return;
}
String asset = tvAsset.getText().toString();
String amount = tvAmount.getText().toString();
asset = asset.replace("bit","");
if (!amount.isEmpty() && hm.containsKey(asset)) {
Currency currency = Currency.getInstance(faitCurrency);
try {
double d = convertLocalizeStringToDouble(amount);
Double eqAmount = d * convertLocalizeStringToDouble(hm.get(asset).toString());
if (Helper.isRTL(locale,currency.getSymbol())) {
tvFaitAmount.setText(String.format(locale, "%.2f %s", eqAmount, currency.getSymbol()));
} else {
tvFaitAmount.setText(String.format(locale, "%s %.2f", currency.getSymbol(), eqAmount));
}
tvFaitAmount.setVisibility(View.VISIBLE);
} catch (Exception e) {
tvFaitAmount.setVisibility(View.GONE);
}
}
}
}
}
catch (JSONException e)
{
hideDialog();
updateEquivalentAmount.postDelayed(getEquivalentCompIndirectRunnable, 500);
}
}
else
{
hideDialog();
updateEquivalentAmount.postDelayed(getEquivalentCompIndirectRunnable, 500);
}
}
else
{
hideDialog();
updateEquivalentAmount.postDelayed(getEquivalentCompIndirectRunnable, 500);
//Toast.makeText(getActivity(), getString(R.string.upgrade_failed), Toast.LENGTH_SHORT).show();
//updateEquivalentAmount.postDelayed(getEquivalentCompRunnable,500);
}
}
@Override
public void onFailure(Throwable t) {
hideDialog();
//Toast.makeText(getActivity(), getString(R.string.txt_no_internet_connection), Toast.LENGTH_SHORT).show();
updateEquivalentAmount.postDelayed(getEquivalentCompIndirectRunnable, 500);
}
});
//}
//catch (Exception e)
//{
//}
}
ArrayList<String> symbolsArray;
ArrayList<String> precisionsArray;
ArrayList<String> amountsArray;
private void updateBalanceArrays (final ArrayList<String> sym, final ArrayList<String> pre, final ArrayList<String> am)
{
try
{
symbolsArray = new ArrayList<>();
precisionsArray = new ArrayList<>();
amountsArray = new ArrayList<>();
for( int i = 0 ; i < sym.size() ; i++ )
{
Long _amount = Long.parseLong(am.get(i));
// remove balances which are zero
if ( _amount != 0 )
{
amountsArray.add(am.get(i));
precisionsArray.add(pre.get(i));
symbolsArray.add(sym.get(i));
}
}
}
catch (Exception e)
{
}
}
public void BalanceAssetsLoad(final ArrayList<String> sym, final ArrayList<String> pre, final ArrayList<String> am, final Boolean onStartUp) {
final AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
updateBalanceArrays( sym,pre,am );
sym.clear();
sym.addAll(symbolsArray);
pre.clear();
pre.addAll(precisionsArray);
am.clear();
am.addAll(amountsArray);
getActivity().runOnUiThread(new Runnable()
{
public void run()
{
SupportMethods.testing("Assets", "Assets views ", "Asset Activity");
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
llBalances.removeAllViews();
for (int i = 0; i < sym.size(); i += 2)
{
int counter = 1;
int op = sym.size();
int pr;
if ((op - i) > 2)
{
pr = 2;
}
else
{
pr = op - i;
}
View customView = layoutInflater.inflate(R.layout.items_rows_balances, null);
for (int l = i; l < i + pr; l++)
{
if (counter == 1)
{
TextView textView = (TextView) customView.findViewById(R.id.symbol_child_one);
//textView.setText(sym.get(l));
assetsSymbols.displaySpannable(textView,sym.get(l));
TextView textView1 = (TextView) customView.findViewById(R.id.amount_child_one);
float b = powerInFloat(pre.get(l), am.get(i));
if(assetsSymbols.isUiaSymbol(sym.get(l))) textView1.setText(String.format(locale, "%.4f", b));
else if(assetsSymbols.isSmartCoinSymbol(sym.get(l))) textView1.setText(String.format(locale, "%.2f", b));
else textView1.setText(String.format(locale, "%.4f", b));
}
if (counter == 2)
{
TextView textView2 = (TextView) customView.findViewById(R.id.symbol_child_two);
// textView2.setText(sym.get(l));
assetsSymbols.displaySpannable(textView2,sym.get(l));
TextView textView3 = (TextView) customView.findViewById(R.id.amount_child_two);
String r = returnFromPower(pre.get(l), am.get(l));
if(assetsSymbols.isUiaSymbol(sym.get(l))) textView3.setText(String.format(locale, "%.4f",Float.parseFloat(r)));
else if(assetsSymbols.isSmartCoinSymbol(sym.get(l))) textView3.setText(String.format(locale, "%.2f", Float.parseFloat(r)));
else textView3.setText(String.format(locale, "%.4f", Float.parseFloat(r)));
llBalances.addView(customView);
}
if (counter == 1 && i == sym.size() - 1)
{
TextView textView2 = (TextView) customView.findViewById(R.id.symbol_child_two);
textView2.setText("");
TextView textView3 = (TextView) customView.findViewById(R.id.amount_child_two);
textView3.setVisibility(View.GONE);
llBalances.addView(customView);
}
if (counter == 1)
{
counter = 2;
}
else counter = 1;
}
}
if (!onStartUp)
{
progressBar1.setVisibility(View.GONE);
isLoading = true;
}
else
{
try
{
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
for (int i = 0; i < accountDetails.size(); i++)
{
if (accountDetails.get(i).isSelected)
{
getEquivalentComponents(accountDetails.get(i).AccountAssets);
break;
}
}
} catch (Exception w) {
SupportMethods.testing("Assets", w, "Asset Activity");
}
}
whiteSpaceAfterBalances.setVisibility(View.GONE);
}
});
}
/* public void setCounter(CounterView counterView, float sValue, float eValue) {
if (counterView != null) {
counterView.setAutoStart(false);
counterView.setAutoFormat(false);
counterView.setStartValue(sValue);
counterView.setEndValue(eValue);
counterView.setIncrement(5f); // the amount the number increments at each time interval
counterView.setTimeInterval(5); // the time interval (ms) at which the text changes
counterView.setPrefix("");
counterView.setSuffix("");
counterView.start();
counterView.setTextLocale(locale);
}
}*/
private void rotateRecieveButton() {
ImageView rcvBtn = (ImageView) getActivity().findViewById(R.id.recievebtn);
final Animation rotAnim = AnimationUtils.loadAnimation(getContext(), R.anim.rotate360);
rcvBtn.startAnimation(rotAnim);
}
public void playSound() {
try {
AudioFilePath audioFilePath = new AudioFilePath(getContext());
MediaPlayer mediaPlayer = audioFilePath.fetchMediaPlayer();
if(mediaPlayer != null)
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void animateText(final TextView tvCounter, float startValue, float endValue) {
ValueAnimator animator = new ValueAnimator();
animator.setFloatValues(startValue, endValue);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float animateValue = Float.parseFloat(String.valueOf(animation.getAnimatedValue()));
tvCounter.setText(Helper.setLocaleNumberFormat(locale, animateValue));
}
});
animator.setEvaluator(new TypeEvaluator<Float>() {
public Float evaluate(float fraction, Float startValue, Float endValue) {
return startValue + (endValue - startValue) * fraction;
}
});
animator.setDuration(2000);
animator.start();
}
public void removeZeroedBalanceViews ()
{
getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
for (int i = 0; i < llBalances.getChildCount(); i++)
{
View row = llBalances.getChildAt(i);
TextView tvSymOne = (TextView) row.findViewById(R.id.symbol_child_one);
TextView tvAmOne = (TextView) row.findViewById(R.id.amount_child_one);
TextView tvfaitOne = (TextView) row.findViewById(R.id.fait_child_one);
TextView tvSymtwo = (TextView) row.findViewById(R.id.symbol_child_two);
TextView tvAmtwo = (TextView) row.findViewById(R.id.amount_child_two);
TextView tvFaitTwo = (TextView) row.findViewById(R.id.fait_child_two);
// If first balance in row is zeroed then update it
if (tvSymOne.getText().toString().equals("")) {
// shift balances from next child here
String symbol = "";
String amount = "";
String fait = "";
// Get next non-zero balance
if (tvSymtwo.getText().toString().isEmpty()) {
// if second balance in row is also empty then get next non-zero balance
for (int j = i+1; j < llBalances.getChildCount(); j++)
{
View nextrow = llBalances.getChildAt(j);
TextView tvSymOnenextrow = (TextView) nextrow.findViewById(R.id.symbol_child_one);
TextView tvAmOnenextrow = (TextView) nextrow.findViewById(R.id.amount_child_one);
TextView tvfaitOnenextrow = (TextView) nextrow.findViewById(R.id.fait_child_one);
if (!tvSymOnenextrow.getText().toString().isEmpty()) {
symbol = tvSymOnenextrow.getText().toString();
amount = tvAmOnenextrow.getText().toString();
fait = tvfaitOnenextrow.getText().toString();
tvSymOnenextrow.setText("");
tvAmOnenextrow.setText("");
tvfaitOnenextrow.setText("");
break;
}
TextView tvSymtwonextrow = (TextView) nextrow.findViewById(R.id.symbol_child_two);
TextView tvAmtwonextrow = (TextView) nextrow.findViewById(R.id.amount_child_two);
TextView tvFaitTwonextrow = (TextView) nextrow.findViewById(R.id.fait_child_two);
if (!tvSymtwonextrow.getText().toString().isEmpty()) {
symbol = tvSymtwonextrow.getText().toString();
amount = tvAmtwonextrow.getText().toString();
fait = tvFaitTwonextrow.getText().toString();
tvSymtwonextrow.setText("");
tvAmtwonextrow.setText("");
tvFaitTwonextrow.setText("");
break;
}
}
}
else
{
// if second balance is row is non-empty then move it to first balance
symbol = tvSymtwo.getText().toString();
amount = tvAmtwo.getText().toString();
fait = tvFaitTwo.getText().toString();
tvSymtwo.setText("");
tvAmtwo.setText("");
tvFaitTwo.setText("");
}
// update first balance amount
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
if(assetsSymbols.isUiaSymbol(symbol)) tvAmOne.setText(String.format(locale, "%.4f",Float.parseFloat(amount)));
else if(assetsSymbols.isSmartCoinSymbol(symbol)) tvAmOne.setText(String.format(locale, "%.2f", Float.parseFloat(amount)));
else tvAmOne.setText(String.format(locale, "%.4f", Float.parseFloat(amount)));
//tvSymOne.setText(symbol);
assetsSymbols.displaySpannable(tvSymOne,symbol);
// tvAmOne.setText(amount);
tvfaitOne.setText(fait);
if (fait.isEmpty())
{
tvfaitOne.setVisibility(View.GONE);
}
else
{
tvfaitOne.setVisibility(View.VISIBLE);
}
}
if (tvSymtwo.getText().toString().isEmpty()) {
String symbol = "";
String amount = "";
String fait = "";
// Get next non-zero balance
for (int j = i+1; j < llBalances.getChildCount(); j++) {
View nextrow = llBalances.getChildAt(j);
TextView tvSymOnenextrow = (TextView) nextrow.findViewById(R.id.symbol_child_one);
TextView tvAmOnenextrow = (TextView) nextrow.findViewById(R.id.amount_child_one);
TextView tvfaitOnenextrow = (TextView) nextrow.findViewById(R.id.fait_child_one);
if (!tvSymOnenextrow.getText().toString().isEmpty()) {
symbol = tvSymOnenextrow.getText().toString();
amount = tvAmOnenextrow.getText().toString();
fait = tvfaitOnenextrow.getText().toString();
tvSymOnenextrow.setText("");
tvAmOnenextrow.setText("");
tvfaitOnenextrow.setText("");
break;
}
TextView tvSymtwonextrow = (TextView) nextrow.findViewById(R.id.symbol_child_two);
TextView tvAmtwonextrow = (TextView) nextrow.findViewById(R.id.amount_child_two);
TextView tvFaitTwonextrow = (TextView) nextrow.findViewById(R.id.fait_child_two);
if (!tvSymtwonextrow.getText().toString().isEmpty()) {
symbol = tvSymtwonextrow.getText().toString();
amount = tvAmtwonextrow.getText().toString();
fait = tvFaitTwonextrow.getText().toString();
tvSymtwonextrow.setText("");
tvAmtwonextrow.setText("");
tvFaitTwonextrow.setText("");
break;
}
}
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
if(assetsSymbols.isUiaSymbol(symbol)) tvAmtwo.setText(String.format(locale, "%.4f",Float.parseFloat(amount)));
else if(assetsSymbols.isSmartCoinSymbol(symbol)) tvAmtwo.setText(String.format(locale, "%.2f", Float.parseFloat(amount)));
else tvAmtwo.setText(String.format(locale, "%.4f", Float.parseFloat(amount)));
//tvSymtwo.setText(symbol);
assetsSymbols.displaySpannable(tvSymtwo,symbol);
// tvAmtwo.setText(amount);
tvFaitTwo.setText(fait);
if (fait.isEmpty())
{
tvFaitTwo.setVisibility(View.GONE);
}
else
{
tvFaitTwo.setVisibility(View.VISIBLE);
}
}
}
// remove empty rows
for (int i = 0; i < llBalances.getChildCount(); i++) {
View row = llBalances.getChildAt(i);
TextView tvSymOne = (TextView) row.findViewById(R.id.symbol_child_one);
TextView tvSymtwo = (TextView) row.findViewById(R.id.symbol_child_two);
if (tvSymOne.getText().toString().isEmpty() && tvSymtwo.getText().toString().isEmpty()) {
llBalances.removeView(row);
}
}
if (llBalances.getChildCount() == 0) {
whiteSpaceAfterBalances.setVisibility(View.VISIBLE);
}
}
catch (Exception e)
{}
}
});
}
Handler animateNsoundHandler = new Handler();
public void BalanceAssetsUpdate(final ArrayList<String> sym, final ArrayList<String> pre, final ArrayList<String> am)
{
final Runnable reloadBalances = new Runnable() {
@Override
public void run() {
removeZeroedBalanceViews();
}
};
getActivity().runOnUiThread(new Runnable() {
public void run() {
try
{
// remove zero balances not in previously loaded balances
List<Integer> indexesToRemove = new ArrayList<>();
for( int i = 0 ; i < sym.size() ; i++ )
{
Long _amount = Long.parseLong(am.get(i));
if ( _amount == 0 )
{
Boolean matchFound = symbolsArray.contains(sym.get(i));
if ( !matchFound )
{
indexesToRemove.add(i);
sym.remove(i);
am.remove(i);
pre.remove(i);
sym.trimToSize();
am.trimToSize();
pre.trimToSize();
i--;
}
}
}
}
catch (Exception e)
{
}
try {
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int count = llBalances.getChildCount();
int m = 0;
try {
Log.d("Balances Update", "Start");
Boolean animateOnce = true;
for (int i = 0; i < count; i++)
{
// count == number of row
// m == number of child in the row
// Get balances row
LinearLayout linearLayout = (LinearLayout) llBalances.getChildAt(i);
TextView tvSymOne = (TextView) linearLayout.findViewById(R.id.symbol_child_one);
TextView tvAmOne = (TextView) linearLayout.findViewById(R.id.amount_child_one);
TextView tvfaitOne = (TextView) linearLayout.findViewById(R.id.fait_child_one);
TextView tvSymtwo = (TextView) linearLayout.findViewById(R.id.symbol_child_two);
TextView tvAmtwo = (TextView) linearLayout.findViewById(R.id.amount_child_two);
TextView tvFaitTwo = (TextView) linearLayout.findViewById(R.id.fait_child_two);
// First child updation
if (sym.size() > m)
{
Log.d("Balances Update", "sym size 1 : " + Long.toString(m));
String symbol = sym.get(m);
Log.d("Balances Update", "symbol : " + symbol);
String amount = "";
if (pre.size() > m && am.size() > m) {
amount = returnFromPower(pre.get(m), am.get(m));
}
Log.d("Balances Update", "amount : " + symbol);
String amountInInt = am.get(m);
Log.d("Balances Update", "amount in int : " + amountInInt);
String txtSymbol = "";// tvSymOne.getText().toString();
String txtAmount = "";//tvAmOne.getText().toString();
if (symbolsArray.size() > m) {
txtSymbol = symbolsArray.get(m);// tvSymOne.getText().toString();
txtAmount = amountsArray.get(m);//tvAmOne.getText().toString();
}
Log.d("Balances Update", "old symbol : " + txtSymbol);
Log.d("Balances Update", "old amount : " + txtAmount);
if (!symbol.equals(txtSymbol))
{
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
assetsSymbols.displaySpannable(tvSymOne,symbol);
//tvSymOne.setText(symbol);
}
if (!amountInInt.equals(txtAmount)) {
// previous amount
//float txtAmount_d = convertLocalizeStringToFloat(txtAmount);
if ( txtAmount.isEmpty() )
{
txtAmount = "0";
}
Long txtAmount_d = Long.parseLong(txtAmount);
// New amount
//float amount_d = convertLocalizeStringToFloat(amount);
Long amount_d = Long.parseLong(amountInInt);
// Balance is sent
if (txtAmount_d > amount_d) {
Log.d("Balances Update", "Balance sent");
SupportMethods.testing("float", txtAmount_d, "txtamount");
SupportMethods.testing("float", amount_d, "amount");
tvAmOne.setTypeface(tvAmOne.getTypeface(), Typeface.BOLD);
tvAmOne.setTextColor(getResources().getColor(R.color.red));
animateText(tvAmOne, convertLocalizeStringToFloat(tvAmOne.getText().toString()), convertLocalizeStringToFloat(amount));
final TextView cView = tvAmOne;
final TextView aView = tvSymOne;
final TextView bView = tvfaitOne;
//final Handler handler = new Handler();
final Runnable updateTask = new Runnable() {
@Override
public void run() {
try {
// cView.setTypeface(null, Typeface.NORMAL);
cView.setTextColor(getResources().getColor(R.color.green));
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(updateTask, 4000);
if (amount_d == 0) {
final Runnable zeroAmount = new Runnable() {
@Override
public void run() {
try {
cView.setText("");
aView.setText("");
bView.setText("");
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(zeroAmount, 4200);
animateNsoundHandler.postDelayed(reloadBalances, 5000);
}
Log.d("Balances Update", "Animation initiated");
}
// Balance is rcvd
else if (amount_d > txtAmount_d) {
Log.d("Balances Update", "Balance received");
tvAmOne.setTypeface(tvAmOne.getTypeface(), Typeface.BOLD);
tvAmOne.setTextColor(getResources().getColor(R.color.green));
// run animation
if (animateOnce) {
AudioFilePath audioFilePath = new AudioFilePath(getContext());
if(!audioFilePath.fetchAudioEnabled()) {
audioSevice = true;
getActivity().startService(new Intent(getActivity(), MediaService.class));
}
/* final Runnable playSOund = new Runnable() {
@Override
public void run() {
playSound();
}
};*/
final Runnable rotateTask = new Runnable() {
@Override
public void run() {
try {
getActivity().runOnUiThread(new Runnable() {
public void run() {
rotateRecieveButton();
}
});
} catch (Exception e) {
}
}
};
// animateNsoundHandler.postDelayed(playSOund, 100);
animateNsoundHandler.postDelayed(rotateTask, 200);
animateOnce = false;
Log.d("Balances Update", "Animation initiated");
}
animateText(tvAmOne, convertLocalizeStringToFloat(tvAmOne.getText().toString()), convertLocalizeStringToFloat(amount));
Log.d("Balances Update", "Text Animated");
final TextView cView = tvAmOne;
final TextView aView = tvSymOne;
final TextView bView = tvfaitOne;
//final Handler handler = new Handler();
final Runnable updateTask = new Runnable() {
@Override
public void run() {
try {
//cView.setTypeface(null, Typeface.NORMAL);
cView.setTextColor(getResources().getColor(R.color.green));
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(updateTask, 4000);
if (amount_d == 0) {
final Runnable zeroAmount = new Runnable() {
@Override
public void run() {
try {
cView.setText("");
aView.setText("");
bView.setText("");
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(zeroAmount, 4200);
animateNsoundHandler.postDelayed(reloadBalances, 5000);
}
Log.d("Balances Update", "Rcv done");
}
}
m++;
Log.d("Balances Update", "m++");
}
else
{
Log.d("Balances Update", "linearLayout.removeAllViews");
linearLayout.removeAllViews();
}
// Second child updation
if (sym.size() > m)
{
Log.d("Balances Update", "sym size 2 : " + Long.toString(m));
String symbol = sym.get(m);
String amount = "";
Log.d("Balances Update", "symbol : " + symbol);
if (pre.size() > m && am.size() > m) {
amount = returnFromPower(pre.get(m), am.get(m));
}
Log.d("Balances Update", "amount : " + amount);
String amountInInt = am.get(m);
Log.d("Balances Update", "amount in int : " + amountInInt);
String txtSymbol = "";
String txtAmount = "";
if (symbolsArray.size() > m) {
txtSymbol = symbolsArray.get(m);// tvSymOne.getText().toString();
txtAmount = amountsArray.get(m);//tvAmOne.getText().toString();
}
Log.d("Balances Update", "old symbol : " + txtSymbol);
Log.d("Balances Update", "old amount : " + txtAmount);
if ( txtAmount.isEmpty() )
{
txtAmount = "0";
}
//float txtAmount_d = convertLocalizeStringToFloat(txtAmount);
Long txtAmount_d = Long.parseLong(txtAmount);
//float amount_d = convertLocalizeStringToFloat(amount);
Long amount_d = Long.parseLong(amountInInt);
if (!symbol.equals(txtSymbol)) {
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
assetsSymbols.displaySpannable(tvSymtwo,symbol);
// tvSymtwo.setText(symbol);
}
if (!amountInInt.equals(txtAmount))
{
tvAmtwo.setVisibility(View.VISIBLE);
// balance is sent
if (txtAmount_d > amount_d)
{
Log.d("Balances Update", "Balance sent");
tvAmtwo.setTextColor(getResources().getColor(R.color.red));
tvAmtwo.setTypeface(tvAmtwo.getTypeface(), Typeface.BOLD);
animateText(tvAmtwo, convertLocalizeStringToFloat(tvAmtwo.getText().toString()), convertLocalizeStringToFloat(amount));
Log.d("Balances Update", "Text animated");
final TextView cView = tvAmtwo;
final TextView aView = tvSymtwo;
final TextView bView = tvFaitTwo;
final Runnable updateTask = new Runnable() {
@Override
public void run() {
try {
//cView.setTypeface(null, Typeface.NORMAL);
cView.setTextColor(getResources().getColor(R.color.green));
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(updateTask, 4000);
if (amount_d == 0) {
final Runnable zeroAmount = new Runnable() {
@Override
public void run() {
try
{
cView.setText("");
aView.setText("");
bView.setText("");
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(zeroAmount, 4200);
animateNsoundHandler.postDelayed(reloadBalances, 5000);
}
Log.d("Balances Update","Animation done");
}
// Balance is recieved
else if (amount_d > txtAmount_d)
{
Log.d("Balances Update","Balance is received");
tvAmtwo.setTextColor(getResources().getColor(R.color.green));
tvAmtwo.setTypeface(tvAmtwo.getTypeface(), Typeface.BOLD);
// run animation
if (animateOnce) {
final Runnable playSOund = new Runnable() {
@Override
public void run() {
try
{
playSound();
}
catch (Exception e)
{
}
}
};
final Runnable rotateTask = new Runnable() {
@Override
public void run() {
try {
getActivity().runOnUiThread(new Runnable() {
public void run() {
try
{
rotateRecieveButton();
}
catch (Exception e)
{
}
}
});
} catch (Exception e) {
}
}
};
animateNsoundHandler.postDelayed(playSOund, 100);
animateNsoundHandler.postDelayed(rotateTask, 200);
animateOnce = false;
Log.d("Balances Update", "Animation initiated");
}
animateText(tvAmtwo, convertLocalizeStringToFloat(tvAmtwo.getText().toString()), convertLocalizeStringToFloat(amount));
Log.d("Balances Update","Text animated");
final TextView cView = tvAmtwo;
final TextView aView = tvSymtwo;
final TextView bView = tvFaitTwo;
//final Handler handler = new Handler();
final Runnable updateTask = new Runnable() {
@Override
public void run() {
try
{
// cView.setTypeface(null, Typeface.NORMAL);
cView.setTextColor(getResources().getColor(R.color.green));
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(updateTask, 4000);
if (amount_d == 0) {
final Runnable zeroAmount = new Runnable() {
@Override
public void run() {
try {
cView.setText("");
aView.setText("");
bView.setText("");
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(zeroAmount, 4200);
animateNsoundHandler.postDelayed(reloadBalances, 5000);
}
Log.d("Balances Update","rcv done");
}
}
m++;
Log.d("Balances Update","m updated");
}
else
{
Log.d("Balances Update","else when sym > m");
// i == number of row
if (i == (count - 1) ) // if its the last row
{
if (sym.size() > m) // if number of balances is more than traversed
m--; // then minus 1 from m
}
}
}
// Calculate m : number of balances loaded in ui
m = 0;
for ( int i = 0 ; i < llBalances.getChildCount(); i++ )
{
LinearLayout linearLayout = (LinearLayout) llBalances.getChildAt(i);
TextView tvSymOne = (TextView) linearLayout.findViewById(R.id.symbol_child_one);
TextView tvSymtwo = (TextView) linearLayout.findViewById(R.id.symbol_child_two);
if ( !tvSymOne.getText().toString().isEmpty() )
{
m++;
}
if ( !tvSymtwo.getText().toString().isEmpty() )
{
m++;
}
}
Log.d("Balances Update","Number of balances loaded : " + Long.toString(m));
// Insert/remove balance objects if updated
Log.d("Balances Update","Insert or remove balance objects if needed");
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
int loop = sym.size() - m; // number of extra balances to be loaded
if (loop > 0)
{
Log.d("Balances Update","Yes updation required : " + Long.toString(loop));
for (int i = m; i < sym.size(); i += 2)
{
int counter = 1;
int totalNumberOfBalances = sym.size(); // total number of balances 6
int pr;
if ( (totalNumberOfBalances - i) > 2 )
{
pr = 2;
}
else
{
pr = totalNumberOfBalances - i;
}
View customView = layoutInflater.inflate(R.layout.items_rows_balances, null);
for (int l = i; l < (i + pr); l++)
{
if (counter == 1)
{
TextView textView = (TextView) customView.findViewById(R.id.symbol_child_one);
// textView.setText(sym.get(l));
assetsSymbols.displaySpannable(textView,sym.get(l));
TextView textView1 = (TextView) customView.findViewById(R.id.amount_child_one);
if ( (pre.size() > l) && (am.size() > i) )
{
String r = returnFromPower(pre.get(l), am.get(i));
textView1.setText(r);
// setCounter(textView1, 0f, 0f);
textView1.setText(String.format(locale, "%.4f", Float.parseFloat(r)));
//setCounter(textView1, Float.parseFloat(r), Float.parseFloat(r));
}
else textView1.setText("");
}
if (counter == 2)
{
TextView textView2 = (TextView) customView.findViewById(R.id.symbol_child_two);
// textView2.setText(sym.get(l));
assetsSymbols.displaySpannable(textView2,sym.get(l));
TextView textView3 = (TextView) customView.findViewById(R.id.amount_child_two);
if ( (pre.size() > l) && (am.size() > l) )
{
String r = returnFromPower(pre.get(l), am.get(l));
textView3.setText(String.format(locale, "%.4f", Float.parseFloat(r)));
//setCounter(textView3, 0f, 0f);
// setCounter(textView3, Float.parseFloat(r), Float.parseFloat(r));
}
llBalances.addView(customView);
// run animation
if (animateOnce) {
final Runnable playSOund = new Runnable() {
@Override
public void run() {
try {
playSound();
}
catch (Exception e)
{
}
}
};
final Runnable rotateTask = new Runnable() {
@Override
public void run() {
try {
getActivity().runOnUiThread(new Runnable() {
public void run() {
rotateRecieveButton();
}
});
} catch (Exception e) {
}
}
};
animateNsoundHandler.postDelayed(playSOund, 100);
animateNsoundHandler.postDelayed(rotateTask, 200);
animateOnce = false;
Log.d("Balances Update", "Animation initiated");
}
}
if ( (counter == 1) && ( i == (sym.size() - 1) ) )
{
llBalances.addView(customView);
// run animation
if (animateOnce) {
final Runnable playSOund = new Runnable() {
@Override
public void run() {
try {
playSound();
}
catch (Exception e)
{
}
}
};
final Runnable rotateTask = new Runnable() {
@Override
public void run() {
try {
getActivity().runOnUiThread(new Runnable() {
public void run() {
rotateRecieveButton();
}
});
} catch (Exception e) {
}
}
};
animateNsoundHandler.postDelayed(playSOund, 100);
animateNsoundHandler.postDelayed(rotateTask, 200);
animateOnce = false;
Log.d("Balances Update", "Animation initiated");
}
}
if (counter == 1)
{
counter = 2;
}
else counter = 1;
}
}
}
}
catch (Exception e)
{
Log.d("Balances Update", e.getMessage());
}
}
catch (Exception e)
{
Log.d("Balances Load", e.getMessage());
}
progressBar1.setVisibility(View.GONE);
whiteSpaceAfterBalances.setVisibility(View.GONE);
isLoading = true;
updateBalanceArrays( sym,pre,am );
}
});
}
String returnFromPower(String i, String str) {
Double ok = 1.0;
Double pre = Double.valueOf(i);
Double value = Double.valueOf(str);
for (int k = 0; k < pre; k++) {
ok = ok * 10;
}
return Double.toString(value / ok);
}
float powerInFloat(String i, String str) {
float ok = 1.0f;
float pre = Float.parseFloat(i);
float value = Float.parseFloat(str);
for (int k = 0; k < pre; k++) {
ok = ok * 10;
}
return (value / ok);
}
public void updateSortTableView(SortableTableView<TransactionDetails> tableView, List<TransactionDetails> myTransactions) {
SimpleTableHeaderAdapter simpleTableHeaderAdapter = new SimpleTableHeaderAdapter(getContext(), getContext().getString(R.string.date), getContext().getString(R.string.all), getContext().getString(R.string.to_from), getContext().getString(R.string.amount));
simpleTableHeaderAdapter.setPaddingLeft(getResources().getDimensionPixelSize(R.dimen.transactionsheaderpading));
tableView.setHeaderAdapter(simpleTableHeaderAdapter);
tableView.setHeaderSortStateViewProvider(SortStateViewProviders.darkArrows());
tableView.setColumnWeight(0, 17);
tableView.setColumnWeight(1, 12);
tableView.setColumnWeight(2, 30);
tableView.setColumnWeight(3, 20);
tableView.setColumnComparator(0, new TransactionsDateComparator());
tableView.setColumnComparator(1, new TransactionsSendRecieveComparator());
tableView.setColumnComparator(3, new TransactionsAmountComparator());
//tableView.setDataAdapter(new TransactionsTableAdapter(getContext(), myTransactions));
/*
TableDataAdapter myAdapter = tableView.getDataAdapter();
List<TransactionDetails> det = myAdapter.getData();
float height = tableView.getHeight();
for(int l=0; l<=30; l++){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2016);
cal.set(Calendar.MONTH, 3);
cal.set(Calendar.DATE, l);
cal.set(Calendar.HOUR_OF_DAY, 14);
cal.set(Calendar.MINUTE, 33);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date myDate = cal.getTime();
myTransactions.add(new TransactionDetails(myDate,true,"yasir-ibrahim","yasir-mobile","#scwal",(float)l,"OBITS",(float)3.33,"USD"));
}
*/
}
@Override
public void soundFinish() {
if(audioSevice) {
getActivity().stopService(new Intent(getActivity(), MediaService.class));
}
audioSevice = false;
}
private static class TransactionsDateComparator implements Comparator<TransactionDetails>
{
@Override
public int compare(TransactionDetails one, TransactionDetails two) {
return one.getDate().compareTo(two.getDate());
}
}
private static class TransactionsSendRecieveComparator implements Comparator<TransactionDetails>
{
@Override
public int compare(TransactionDetails one, TransactionDetails two) {
return one.getSent().compareTo(two.getSent());
}
}
private static int compareFloats(float change1, float change2)
{
if (change1 < change2) {
return -1;
} else if (change1 == change2) {
return 0; // Fails on NaN however, not sure what you want
} else if (change2 > change2) {
return 1;
} else {
return 1;
}
}
private static int compareDoubles(double change1, double change2)
{
if (change1 < change2) {
return -1;
} else if (change1 == change2) {
return 0; // Fails on NaN however, not sure what you want
} else if (change2 > change2) {
return 1;
} else {
return 1;
}
}
private static class TransactionsAmountComparator implements Comparator<TransactionDetails> {
@Override
public int compare(TransactionDetails one, TransactionDetails two) {
return compareDoubles(one.getAmount(), two.getAmount());
}
}
private void saveTransactions(List<TransactionDetails> transactionDetails, String accountName) {
tinyDB.putTransactions(getActivity(), getContext(), getResources().getString(R.string.pref_local_transactions) + accountName, new ArrayList<>(transactionDetails));
}
private ArrayList<TransactionDetails> getTransactionsFromSharedPref(String accountName)
{
ArrayList<TransactionDetails> mySavedList = tinyDB.getTransactions(getResources().getString(R.string.pref_local_transactions) + accountName, TransactionDetails.class);
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
assetsSymbols.updatedTransactionDetails(mySavedList);
for (TransactionDetails td : mySavedList) {
td.updateContext(getContext());
}
return mySavedList;
}
TransactionsTableAdapter myTransactionsTableAdapter;
public void TransactionUpdateOnStartUp(String accountName)
{
final List<TransactionDetails> localTransactionDetails = getTransactionsFromSharedPref(accountName);
if (localTransactionDetails != null && localTransactionDetails.size() > 0)
{
//myTransactions.addAll(localTransactionDetails);
getActivity().runOnUiThread(new Runnable()
{
public void run()
{
//isSavedTransactions = true;
if ( myTransactionsTableAdapter == null )
{
myTransactionsTableAdapter = new TransactionsTableAdapter(getContext(), localTransactionDetails);
}
else
{
myTransactionsTableAdapter.clear();
myTransactionsTableAdapter.addAll(localTransactionDetails);
}
tableView.setDataAdapter(myTransactionsTableAdapter);
// load_more_values.setVisibility(View.VISIBLE);
// load_more_values.setEnabled(true);
tableViewparent.setVisibility(View.VISIBLE);
}
});
}
}
Handler updateTransactionsList;
@Override
public void TransactionUpdate(final List<TransactionDetails> transactionDetails, final int number_of_transactions_in_queue)
{
/*
sentCallForTransactions = false;
try
{
if(isSavedTransactions)
{
myTransactions.clear();
isSavedTransactions = false;
myTransactions = new ArrayList<>();
}
if (myTransactions.size() == 0)
{
saveTransactions(transactionDetails);
}
myTransactions.addAll(transactionDetails);
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
myTransactions = assetsSymbols.updatedTransactionDetails(myTransactions);
//tableView.setDataAdapter(new TransactionsTableAdapter(getContext(), myTransactions));
getActivity().runOnUiThread(new Runnable() {
@Override
public void run()
{
if ( updateTransactionsList == null )
{
updateTransactionsList = new Handler();
}
if (number_of_transactions_in_queue == 0)
{
load_more_values.setVisibility(View.GONE);
} else {
load_more_values.setVisibility(View.VISIBLE);
load_more_values.setEnabled(true);
}
//tableView.setDataAdapter(myTransactionsTableAdapter);
//tableView.getDataAdapter().clear();
//tableView.getDataAdapter().addAll(myTransactions);
if ( progressBar.getVisibility() != View.GONE )
progressBar.setVisibility(View.GONE);
if ( tableViewparent.getVisibility() != View.VISIBLE )
tableViewparent.setVisibility(View.VISIBLE);
}
});
if ( myTransactionsTableAdapter == null )
{
myTransactionsTableAdapter = new TransactionsTableAdapter(getContext(), myTransactions);
tableView.setDataAdapter(myTransactionsTableAdapter);
}
else
{
myTransactionsTableAdapter = new TransactionsTableAdapter(getContext(), myTransactions);
tableView.setDataAdapter(myTransactionsTableAdapter);
}
}
catch (Exception e) {
SupportMethods.testing("TransactionUpdate", e, "try/catch");
}
*/
}
int counterRepeatTransactionLoad = 0;
@Override
public void transactionsLoadComplete(List<TransactionDetails> transactionDetails,int newTransactionsLoaded)
{
//sentCallForTransactions = false;
try
{
/*
if ( number_of_transactions_loaded == 0 )
{
myTransactions.clear();
}
if(isSavedTransactions)
{
myTransactions.clear();
isSavedTransactions = false;
myTransactions = new ArrayList<>();
}
if (myTransactions.size() == 0)
{
saveTransactions(transactionDetails);
}
*/
if ( updateTriggerFromNetworkBroadcast && ( newTransactionsLoaded == 0 ) && (counterRepeatTransactionLoad++ < 20) )
{
if (Application.isReady)
{
Application.webSocketG.close();
}
loadTransactions(getContext(), accountId, this, wifkey, number_of_transactions_loaded, number_of_transactions_to_load, myTransactions);
return;
}
updateTriggerFromNetworkBroadcast = false;
counterRepeatTransactionLoad = 0;
Context context = getContext();
// update context
for(TransactionDetails td:transactionDetails)
{
td.updateContext(context);
}
myTransactions.clear();
myTransactions.addAll(transactionDetails);
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
myTransactions = assetsSymbols.updatedTransactionDetails(myTransactions);
saveTransactions(myTransactions,to);
number_of_transactions_loaded += number_of_transactions_to_load;
getActivity().runOnUiThread(new Runnable() {
@Override
public void run()
{
if ( updateTransactionsList == null )
{
updateTransactionsList = new Handler();
}
if ( myTransactionsTableAdapter == null )
{
Set<TransactionDetails> hs = new HashSet<>();
hs.addAll(myTransactions);
myTransactions.clear();
myTransactions.addAll(hs);
Collections.sort(myTransactions, new transactionsDateComparator());
myTransactionsTableAdapter = new TransactionsTableAdapter(getContext(), myTransactions);
tableView.setDataAdapter(myTransactionsTableAdapter);
}
else
{
Set<TransactionDetails> hs = new HashSet<>();
hs.addAll(myTransactions);
myTransactions.clear();
myTransactions.addAll(hs);
Collections.sort(myTransactions, new transactionsDateComparator());
myTransactionsTableAdapter = new TransactionsTableAdapter(getContext(), myTransactions);
tableView.setDataAdapter(myTransactionsTableAdapter);
}
if (myTransactionActivity.finalBlockRecieved)
{
load_more_values.setVisibility(View.GONE);
}
else
{
load_more_values.setVisibility(View.VISIBLE);
load_more_values.setEnabled(true);
}
if ( progressBar.getVisibility() != View.GONE )
progressBar.setVisibility(View.GONE);
if ( tableViewparent.getVisibility() != View.VISIBLE )
tableViewparent.setVisibility(View.VISIBLE);
}
});
/*
if ( number_of_transactions_loaded < 20 )
{
loadTransactions(getContext(), accountId, this, wifkey, number_of_transactions_loaded, number_of_transactions_to_load);
}
*/
}
catch (Exception e)
{
SupportMethods.testing("TransactionUpdate", e, "try/catch");
}
}
@Override
public void transactionsLoadMessageStatus(String message)
{
}
@Override
public void transactionsLoadFailure(String reason)
{
//sentCallForTransactions = false;
if ( reason.equals(getContext().getString(R.string.account_names_not_found)) )
{
//number_of_transactions_loaded += number_of_transactions_to_load;
}
//if ( reason.equals(getContext().getString(R.string.no_assets_found)) )
//{
//number_of_transactions_loaded += number_of_transactions_to_load;
loadTransactions(getContext(), accountId, this, wifkey, number_of_transactions_loaded, number_of_transactions_to_load,myTransactions);
//return;
//}
/*
getActivity().runOnUiThread(new Runnable() {
@Override
public void run()
{
if (myTransactionActivity.finalBlockRecieved)
{
load_more_values.setVisibility(View.GONE);
}
else
{
load_more_values.setVisibility(View.VISIBLE);
load_more_values.setEnabled(true);
}
if ( progressBar.getVisibility() != View.GONE )
progressBar.setVisibility(View.GONE);
if ( tableViewparent.getVisibility() != View.VISIBLE )
tableViewparent.setVisibility(View.VISIBLE);
}
});
*/
}
@OnClick(R.id.load_more_values)
public void Load_more_Values() {
load_more_values.setEnabled(false);
progressBar.setVisibility(View.VISIBLE);
number_of_transactions_to_load = 20;
loadTransactions(getContext(), accountId, this, wifkey, number_of_transactions_loaded, number_of_transactions_to_load,myTransactions);
//number_of_transactions_loaded = number_of_transactions_loaded + 20;
}
void isLifeTime(final String name_id, final String id) {
String getDetails = "{\"id\":" + id + ",\"method\":\"call\",\"params\":[";
String getDetails2 = ",\"get_accounts\",[[\"" + name_id + "\"]]]}";
myWebSocketHelper.make_websocket_call(getDetails,getDetails2, webSocketCallHelper.api_identifier.database);
}
/*
void get_full_accounts(final String name_id, final String id)
{
String getDetails = "{\"id\":" + id + ",\"method\":\"call\",\"params\":[";
String getDetails2 = ",\"get_full_accounts\",[[\"" + name_id + "\"],true]]}";
myWebSocketHelper.make_websocket_call(getDetails,getDetails2, webSocketCallHelper.api_identifier.database);
}
*/
@Override
public void getLifetime(String s, int id) {
myWebSocketHelper.cleanUpTransactionsHandler();
SupportMethods.testing("getLifetime", s, "s");
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
SupportMethods.testing("getAccountID", s, "s");
String result = SupportMethods.ParseJsonObject(s, "result");
String nameObject = SupportMethods.ParseObjectFromJsonArray(result, 0);
String expiration = SupportMethods.ParseJsonObject(nameObject, "membership_expiration_date");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
Date date1 = dateFormat.parse(expiration);
Date date2 = dateFormat.parse("1969-12-31T23:59:59");
if (date2.getTime() >= date1.getTime()) {
SupportMethods.testing("getLifetime", "true", "s");
//accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
if (accountDetails.size() > accountDetailsId) {
accountDetails.get(accountDetailsId).isLifeTime = true;
showHideLifeTime(true);
} else if (accountDetails.size() == 1) {
accountDetails.get(0).isLifeTime = true;
showHideLifeTime(true);
}
tinyDB.putListObject(getString(R.string.pref_wallet_accounts), accountDetails);
} else {
SupportMethods.testing("getLifetime", "false", "s");
}
} catch (Exception e) {
SupportMethods.testing("getLifetime", e, "Exception");
}
}
void startAnimation() {
scrollViewBalances.fullScroll(View.FOCUS_UP);
scrollViewBalances.pageScroll(View.FOCUS_UP);
qrCamera.setVisibility(View.INVISIBLE);
backLine.setVisibility(View.INVISIBLE);
final Animation animationFadeIn = AnimationUtils.loadAnimation(getContext(), R.anim.fade_in);
final Animation animationRigthtoLeft = AnimationUtils.loadAnimation(getContext(), R.anim.home_anim);
animationRigthtoLeft.setInterpolator(new AccelerateDecelerateInterpolator());
qrCamera.postDelayed(new Runnable() {
public void run() {
qrCamera.startAnimation(animationRigthtoLeft);
qrCamera.setVisibility(View.VISIBLE);
}
}, 333);
backLine.postDelayed(new Runnable() {
public void run() {
backLine.setVisibility(View.VISIBLE);
backLine.startAnimation(animationFadeIn);
}
}, 999);
}
@Override
public void setUserVisibleHint(boolean visible) {
super.setUserVisibleHint(visible);
if (visible) {
if (qrCamera != null && backLine != null) {
startAnimation();
} else {
myHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (qrCamera != null && backLine != null) {
startAnimation();
} else myHandler.postDelayed(this, 333);
}
}, 333);
}
}
}
Handler loadOndemand = new Handler();
private void loadOnDemand(final Activity _activity)
{
try {
loadOndemand.removeCallbacksAndMessages(null);
Runnable loadOnDemandRunnable = new Runnable() {
@Override
public void run() {
try {
_activity.runOnUiThread(new Runnable() {
public void run() {
//sentCallForTransactions = false;
//isSavedTransactions = true;
loadViews(false, true, false);
}
});
}
catch (Exception e){}
}
};
//loadOndemand.removeCallbacks(loadOnDemandRunnable);
loadOndemand.postDelayed(loadOnDemandRunnable, 5000);
}
catch (Exception e){}
}
boolean updateTriggerFromNetworkBroadcast = false;
@Override
public void loadAll()
{
//extra
if(!updateTriggerFromNetworkBroadcast) {
//
ArrayList<TransactionDetails> mySavedList = tinyDB.getTransactions(getResources().getString(R.string.pref_local_transactions) + to, TransactionDetails.class);
mySavedList.clear();
tinyDB.putTransactions(getActivity(), getContext(), getResources().getString(R.string.pref_local_transactions) + to, mySavedList);
//original
updateTriggerFromNetworkBroadcast = true;
loadOnDemand(getActivity());
}
}
AssestsActivty myAssetsActivity;
boolean firstTimeLoad = true;
String transactionsLoadedAccountName = "";
void loadViews(Boolean onResume,Boolean accountNameChanged,boolean faitCurrencyChanged) {
if ( firstTimeLoad )
{
//if(!isSavedTransactions)
//{
tableViewparent.setVisibility(View.GONE);
myTransactions = new ArrayList<>();
updateSortTableView(tableView, myTransactions);
//}
tableView.addDataClickListener(new tableViewClickListener(getContext()));
progressBar.setVisibility(View.VISIBLE);
load_more_values.setVisibility(View.GONE);
firstTimeLoad = false;
}
whiteSpaceAfterBalances.setVisibility(View.VISIBLE);
if (myAssetsActivity == null)
{
myAssetsActivity = new AssestsActivty(getContext(), to, this, application);
myAssetsActivity.registerDelegate();
}
// get transactions from sharedPref
myTransactions = getTransactionsFromSharedPref(to);
//myTransactions.clear();
//saveTransactions(myTransactions);
if ( !onResume || accountNameChanged || faitCurrencyChanged )
{
progressBar1.setVisibility(View.VISIBLE);
myAssetsActivity.loadBalances(to);
//sentCallForTransactions = false;
progressBar.setVisibility(View.VISIBLE);
load_more_values.setVisibility(View.GONE);
number_of_transactions_loaded = 0;
number_of_transactions_to_load = 20;
loadTransactions(getContext(), accountId, this, wifkey, number_of_transactions_loaded, number_of_transactions_to_load, myTransactions);
}
}
void loadBasic(boolean onResume,boolean accountNameChanged, boolean faitCurrencyChanged) {
if ( !onResume )
{
isLoading = false;
}
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
if (accountDetails.size() == 1) {
accountDetailsId = 0;
accountDetails.get(0).isSelected = true;
to = accountDetails.get(0).account_name;
accountId = accountDetails.get(0).account_id;
wifkey = accountDetails.get(0).wif_key;
showHideLifeTime(accountDetails.get(0).isLifeTime);
tinyDB.putListObject(getString(R.string.pref_wallet_accounts), accountDetails);
} else {
for (int i = 0; i < accountDetails.size(); i++) {
if (accountDetails.get(i).isSelected) {
accountDetailsId = i;
to = accountDetails.get(i).account_name;
accountId = accountDetails.get(i).account_id;
wifkey = accountDetails.get(i).wif_key;
showHideLifeTime(accountDetails.get(i).isLifeTime);
break;
}
}
}
Application.monitorAccountId = accountId;
tvAccountName.setText(to);
isLifeTime(accountId, "15");
//get_full_accounts(accountId, "17");
loadViews(onResume,accountNameChanged, faitCurrencyChanged);
}
Boolean checkIfAccountNameChange() {
//ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
String checkAccountName = "";
if (accountDetails.size() == 1) {
checkAccountName = accountDetails.get(0).account_name;
ivMultiAccArrow.setVisibility(View.GONE);
} else {
ivMultiAccArrow.setVisibility(View.VISIBLE);
for (int i = 0; i < accountDetails.size(); i++) {
if (accountDetails.get(i).isSelected) {
checkAccountName = accountDetails.get(i).account_name;
break;
}
}
}
return !checkAccountName.equals(to);
}
void onChangedAccount(){
final ArrayList<AccountDetails> accountDetailsList;
accountDetailsList = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
List<String> accountlist = new ArrayList<String>();
for (int i = 0; i < accountDetailsList.size(); i++) {
accountlist.add(accountDetailsList.get(i).account_name);
}
AlertDialog.Builder builderSingle = new AlertDialog.Builder(getContext());
builderSingle.setTitle(getString(R.string.imported_created_accounts));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
getContext(), android.R.layout.simple_list_item_1, accountlist);
builderSingle.setAdapter(
arrayAdapter,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String strName = arrayAdapter.getItem(which);
for (int i = 0; i < accountDetailsList.size(); i++) {
if (strName.equals(accountDetailsList.get(i).account_name)) {
accountDetailsList.get(i).isSelected = true;
} else {
accountDetailsList.get(i).isSelected = false;
}
}
tinyDB.putListObject(getString(R.string.pref_wallet_accounts), accountDetailsList);
Helper.storeStringSharePref(getContext(), getString(R.string.pref_account_name), strName);
onResume();
dialog.dismiss();
}
});
builderSingle.show();
}
@OnClick(R.id.ivMultiAccArrow)
public void ivOnChangedAccount(View view){
onChangedAccount();
}
@OnClick(R.id.account_name)
public void tvOnChangedAccount(View view){
onChangedAccount();
}
private void showHideLifeTime(final Boolean show) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (show) {
ivLifeTime.setVisibility(View.VISIBLE);
tvUpgradeLtm.setVisibility(View.GONE);
} else {
ivLifeTime.setVisibility(View.GONE);
tvUpgradeLtm.setVisibility(View.VISIBLE);
}
}
});
}
public void getAccountUpgradeInfo(final Activity activity, final String accountName) {
ServiceGenerator sg = new ServiceGenerator(getString(R.string.account_from_brainkey_url));
IWebService service = sg.getService(IWebService.class);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("method", "upgrade_account");
hashMap.put("account", accountName);
try {
hashMap.put("wifkey", Crypt.getInstance().decrypt_string(wifkey));
} catch (Exception e) {
}
final Call<AccountUpgrade> postingService = service.getAccountUpgrade(hashMap);
postingService.enqueue(new Callback<AccountUpgrade>() {
@Override
public void onResponse(Response<AccountUpgrade> response) {
if (response.isSuccess()) {
AccountUpgrade accountDetails = response.body();
if (accountDetails.status.equals("success")) {
updateLifeTimeModel(accountName);
hideDialog();
Toast.makeText(activity, getString(R.string.upgrade_success), Toast.LENGTH_SHORT).show();
} else {
hideDialog();
Toast.makeText(activity, getString(R.string.upgrade_failed), Toast.LENGTH_SHORT).show();
}
} else {
hideDialog();
Toast.makeText(activity, getString(R.string.upgrade_failed), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Throwable t) {
hideDialog();
Toast.makeText(activity, activity.getString(R.string.txt_no_internet_connection), Toast.LENGTH_SHORT).show();
}
});
}
public void getLtmPrice(final Activity activity, final String accountName) {
ServiceGenerator sg = new ServiceGenerator(getString(R.string.account_from_brainkey_url));
IWebService service = sg.getService(IWebService.class);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("method", "upgrade_account_fees");
hashMap.put("account", accountName);
try {
hashMap.put("wifkey", Crypt.getInstance().decrypt_string(wifkey));
} catch (Exception e) {
}
final Call<LtmFee> postingService = service.getLtmFee(hashMap);
postingService.enqueue(new Callback<LtmFee>() {
@Override
public void onResponse(Response<LtmFee> response) {
if (response.isSuccess()) {
hideDialog();
LtmFee ltmFee = response.body();
if (ltmFee.status.equals("success")) {
try {
JSONObject jsonObject = new JSONObject(ltmFee.transaction);
JSONObject jsonObject1 = jsonObject.getJSONArray("operations").getJSONArray(0).getJSONObject(1);
JSONObject jsonObject2 = jsonObject1.getJSONObject("fee");
String amount = jsonObject2.getString("amount");
//String asset_id = jsonObject2.getString("asset_id");
String temp = SupportMethods.ConvertValueintoPrecision("5", amount);
Helper.storeStringSharePref(getActivity(), "ltmAmount", temp);
} catch (Exception e) {
}
}
}
}
@Override
public void onFailure(Throwable t) {
hideDialog();
Toast.makeText(activity, activity.getString(R.string.txt_no_internet_connection), Toast.LENGTH_SHORT).show();
}
});
}
private void hideDialog() {
try {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.cancel();
}
}
}
});
}
catch (Exception e)
{}
}
private void showDialog(String title, String msg) {
if (progressDialog != null) {
if (!progressDialog.isShowing()) {
progressDialog.setTitle(title);
progressDialog.setMessage(msg);
progressDialog.show();
}
}
}
private void updateLifeTimeModel(String accountName) {
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
try {
for (int i = 0; i < accountDetails.size(); i++) {
if (accountDetails.get(i).account_name.equals(accountName)) {
accountDetails.get(i).isLifeTime = true;
break;
}
}
} catch (Exception e) {
}
tinyDB.putListObject(getString(R.string.pref_wallet_accounts), accountDetails);
showHideLifeTime(true);
}
private float convertLocalizeStringToFloat(String text) {
float txtAmount_d = 0;
try {
NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
Number number = format.parse(text);
txtAmount_d = number.floatValue();
} catch (Exception e) {
try {
NumberFormat format = NumberFormat.getInstance(locale);
Number number = format.parse(text);
txtAmount_d = number.floatValue();
} catch (Exception e1) {
}
}
return txtAmount_d;
}
private double convertLocalizeStringToDouble(String text) {
double txtAmount_d = 0;
try {
NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
Number number = format.parse(text);
txtAmount_d = number.doubleValue();
} catch (Exception e) {
try {
NumberFormat format = NumberFormat.getInstance(locale);
Number number = format.parse(text);
txtAmount_d = number.doubleValue();
} catch (Exception e1) {
}
}
return txtAmount_d;
}
private int convertLocalizeStringToInt(String text) {
int txtAmount_d = 0;
try {
NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
Number number = format.parse(text);
txtAmount_d = number.intValue();
} catch (Exception e) {
try {
NumberFormat format = NumberFormat.getInstance(locale);
Number number = format.parse(text);
txtAmount_d = number.intValue();
} catch (Exception e1) {
}
}
return txtAmount_d;
}
TransactionActivity myTransactionActivity;
void loadTransactions(final Context context,final String id,final AssetDelegate in ,final String wkey,final int loaded,final int toLoad, final ArrayList<TransactionDetails> alreadyLoadedTransactions)
{
if (myTransactionActivity == null) {
myTransactionActivity = new TransactionActivity(context, id, in, wkey, loaded, toLoad, alreadyLoadedTransactions);
} else {
//myTransactionActivity = null;
myTransactionActivity.context = null;
myTransactionActivity = new TransactionActivity(context, id, in, wkey, loaded, toLoad, alreadyLoadedTransactions);
}
//new TransactionActivity(context, id ,in , wkey , loaded , toLoad);
}
/*
void loadTransactions(final Context context,final String id ,final String wkey,final int loaded,final int toLoad)
{
sentCallForTransactions = true;
new TransactionActivity(context, id ,this , wkey , loaded , toLoad);
}
*/
// final Handler handlerTransactions = new Handler();
// handlerTransactions.postDelayed(new Runnable() {
// @Override
// public void run() {
//
// if(!rcvdCallForTransactions && sentCallForTransactions) {
// new TransactionActivity(context, id ,in , wkey , loaded , toLoad);
// handlerTransactions.postDelayed(this, 20000);
// }
//
// if(!sentCallForTransactions){
// sentCallForTransactions = true;
// new TransactionActivity(context, id ,in , wkey , loaded , toLoad);
// handlerTransactions.postDelayed(this, 20000);
// }
//
// if(rcvdCallForTransactions){
// handlerTransactions.removeCallbacks(this);
// handlerTransactions.removeCallbacksAndMessages(this);
// }
//
// }
// }, 100);
// }
}
| app/src/main/java/de/bitshares_munich/fragments/BalancesFragment.java | package de.bitshares_munich.fragments;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.bitshares_munich.Interfaces.AssetDelegate;
import de.bitshares_munich.Interfaces.ISound;
import de.bitshares_munich.adapters.TransactionsTableAdapter;
import de.bitshares_munich.models.AccountAssets;
import de.bitshares_munich.models.AccountDetails;
import de.bitshares_munich.models.AccountUpgrade;
import de.bitshares_munich.models.EquivalentComponentResponse;
import de.bitshares_munich.models.EquivalentFiatStorage;
import de.bitshares_munich.models.LtmFee;
import de.bitshares_munich.models.TransactionDetails;
import de.bitshares_munich.smartcoinswallet.AssestsActivty;
import de.bitshares_munich.smartcoinswallet.AssetsSymbols;
import de.bitshares_munich.smartcoinswallet.AudioFilePath;
import de.bitshares_munich.smartcoinswallet.MediaService;
import de.bitshares_munich.smartcoinswallet.R;
import de.bitshares_munich.smartcoinswallet.RecieveActivity;
import de.bitshares_munich.smartcoinswallet.SendScreen;
import de.bitshares_munich.smartcoinswallet.pdfTable;
import de.bitshares_munich.smartcoinswallet.qrcodeActivity;
import de.bitshares_munich.utils.Application;
import de.bitshares_munich.utils.Crypt;
import de.bitshares_munich.utils.Helper;
import de.bitshares_munich.utils.PermissionManager;
import de.bitshares_munich.utils.IWebService;
import de.bitshares_munich.utils.ServiceGenerator;
import de.bitshares_munich.utils.SupportMethods;
import de.bitshares_munich.utils.TinyDB;
import de.bitshares_munich.utils.TransactionActivity;
import de.bitshares_munich.utils.tableViewClickListener;
import de.bitshares_munich.utils.transactionsDateComparator;
import de.bitshares_munich.utils.webSocketCallHelper;
import de.codecrafters.tableview.SortableTableView;
import de.codecrafters.tableview.TableDataAdapter;
import de.codecrafters.tableview.toolkit.SimpleTableHeaderAdapter;
import de.codecrafters.tableview.toolkit.SortStateViewProviders;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by qasim on 5/10/16.
*/
public class BalancesFragment extends Fragment implements AssetDelegate ,ISound{
public static Activity balanceActivity;
static Boolean audioSevice = false;
Application application = new Application();
int accountDetailsId;
String accountId = "";
DecimalFormat df = new DecimalFormat("0.0");
Boolean isLoading = false;
public static Boolean onClicked = false;
Handler myHandler = new Handler();
String to = "";
String wifkey = "";
String finalFaitCurrency;
@Bind(R.id.load_more_values)
Button load_more_values;
@Bind(R.id.scrollViewBalances)
ScrollView scrollViewBalances;
@Bind(R.id.backLine)
View backLine;
@Bind(R.id.progressBar)
ProgressBar progressBar;
@Bind(R.id.progressBar1)
ProgressBar progressBar1;
@Bind(R.id.qrCamera)
ImageView qrCamera;
@Bind(R.id.tvBalances)
TextView tvBalances;
@Bind(R.id.tvUpgradeLtm)
TextView tvUpgradeLtm;
@Bind(R.id.llBalances)
LinearLayout llBalances;
int number_of_transactions_loaded = 0;
int number_of_transactions_to_load = 0;
@Bind(R.id.whiteSpaceAfterBalances)
LinearLayout whiteSpaceAfterBalances;
private SortableTableView<TransactionDetails> tableView;
private ArrayList<TransactionDetails> myTransactions;
TinyDB tinyDB;
@Bind(R.id.tableViewparent)
LinearLayout tableViewparent;
@Bind(R.id.account_name)
TextView tvAccountName;
@Bind(R.id.recievebtn)
ImageView recievebtn;
@Bind(R.id.sendbtn)
ImageView sendbtn;
@Bind(R.id.ivLifeTime)
ImageView ivLifeTime;
@Bind(R.id.ivMultiAccArrow)
ImageView ivMultiAccArrow;
ProgressDialog progressDialog;
//Boolean sentCallForTransactions = false;
//Boolean isSavedTransactions = false;
Locale locale;
NumberFormat format;
String language;
public static ISound iSound;
// String ltmAmount="17611.7";
public BalancesFragment() {
// Required empty public constructor
}
webSocketCallHelper myWebSocketHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tinyDB = new TinyDB(getContext());
application.registerAssetDelegate(this);
iSound=this;
updateEquivalentAmount = new Handler();
myWebSocketHelper = new webSocketCallHelper(getContext());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_balances, container, false);
ButterKnife.bind(this, rootView);
language = Helper.fetchStringSharePref(getActivity(), getString(R.string.pref_language));
locale = new Locale(language);
balanceActivity = getActivity();
format = NumberFormat.getInstance(locale);
tvUpgradeLtm.setPaintFlags(tvUpgradeLtm.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
progressDialog = new ProgressDialog(getActivity());
tableView = (SortableTableView<TransactionDetails>) rootView.findViewById(R.id.tableView);
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
assetsSymbols.getAssetsFromServer();
// getAssetsFromServer();
final Handler handler = new Handler();
final Runnable updateTask = new Runnable() {
@Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
setSortableTableViewHeight(rootView, handler, this);
}
});
}
};
final Runnable createFolder = new Runnable() {
@Override
public void run() {
createFolder();
}
};
loadBasic(false,true,false);
loadBalancesFromSharedPref();
TransactionUpdateOnStartUp(to);
handler.postDelayed(updateTask, 2000);
handler.postDelayed(createFolder, 5000);
if (!Helper.containKeySharePref(getActivity(), "ltmAmount")) {
Helper.storeStringSharePref(getActivity(), "ltmAmount", "17611.7");
}
getLtmPrice(getActivity(), tvAccountName.getText().toString());
return rootView;
}
private void setSortableTableViewHeight(View rootView, Handler handler, Runnable task) {
try {
View scrollViewBalances = rootView.findViewById(R.id.scrollViewBalances);
int height1 = scrollViewBalances.getHeight();
if (height1 == 0) {
handler.postDelayed(task, 2000);
return;
}
Log.d("setSortableHeight", "Scroll Heght : " + Long.toString(height1));
View transactionsExportHeader = rootView.findViewById(R.id.transactionsExportHeader);
int height2 = transactionsExportHeader.getHeight();
Log.d("setSortableHeight", "Scroll Header Heght : " + Long.toString(height2));
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tableView.getLayoutParams();
params.height = height1 - height2;
Log.d("setSortableHeight", "View Heght : " + Long.toString(params.height));
tableViewparent.setLayoutParams(params);
Log.d("setSortableHeight", "View Heght Set");
} catch (Exception e) {
Log.d("List Height", e.getMessage());
handler.postDelayed(task, 2000);
}
}
private void createFolder() {
try {
PermissionManager manager = new PermissionManager();
manager.verifyStoragePermissions(getActivity());
final File folder = new File(Environment.getExternalStorageDirectory() + File.separator + getResources().getString(R.string.folder_name));
boolean success = false;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
// Do something on success
Toast.makeText(getContext(), getResources().getString(R.string.txt_folder_created) + " : " + folder.getAbsolutePath(), Toast.LENGTH_LONG).show();
}
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
File file2 = new File(folder.getAbsolutePath(), "Woohoo.wav");
if (!file2.exists()) {
FileOutputStream save = new FileOutputStream(file2);
byte[] buffer = null;
InputStream fIn = getResources().openRawResource(R.raw.woohoo);
int size = 0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
save.write(buffer);
//save.flush();
//save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
save.flush();
save.close();
}
} catch (Exception e) {
}
}
});
}catch (Exception e){}
}
@Override
public void onResume() {
super.onResume();
// Inflate the layout for this fragment
scrollViewBalances.fullScroll(View.FOCUS_UP);
scrollViewBalances.pageScroll(View.FOCUS_UP);
onClicked = false;
final String hide_donations_isChanged = "hide_donations_isChanged";
Boolean isHideDonationsChanged = false;
if (Helper.containKeySharePref(getContext(), hide_donations_isChanged)) {
if (Helper.fetchBoolianSharePref(getContext(), hide_donations_isChanged)) {
isHideDonationsChanged = true;
Helper.storeBoolianSharePref(getContext(), hide_donations_isChanged, false);
}
}
Boolean isCheckedTimeZone=false;
isCheckedTimeZone=Helper.fetchBoolianSharePref(getActivity(),getString(R.string.pre_ischecked_timezone));
Boolean accountNameChange = checkIfAccountNameChange();
if(accountNameChange || (finalFaitCurrency != null && !Helper.getFadeCurrency(getContext()).equals(finalFaitCurrency)) )
llBalances.removeAllViews();
if (isCheckedTimeZone || isHideDonationsChanged || accountNameChange || (finalFaitCurrency != null && !Helper.getFadeCurrency(getContext()).equals(finalFaitCurrency)) )
{
if (finalFaitCurrency != null && !Helper.getFadeCurrency(getContext()).equals(finalFaitCurrency) )
{
loadBasic(true,accountNameChange,true);
}
else
{
loadBasic(true,accountNameChange,false);
}
}
}
@OnClick(R.id.recievebtn)
public void GoToRecieveActivity() {
final Intent intent = new Intent(getActivity(), RecieveActivity.class);
intent.putExtra(getString(R.string.to), to);
intent.putExtra(getString(R.string.account_id), accountId);
Animation coinAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.coin_animation);
coinAnimation.setAnimationListener(new android.view.animation.Animation.AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
startActivity(intent);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
});
recievebtn.startAnimation(coinAnimation);
}
@OnClick(R.id.sendbtn)
public void GoToSendActivity() {
if (isLoading) {
final Intent intent = new Intent(getActivity(), SendScreen.class);
Animation coinAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.coin_animation);
coinAnimation.setAnimationListener(new android.view.animation.Animation.AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
startActivity(intent);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
});
sendbtn.startAnimation(coinAnimation);
} else Toast.makeText(getContext(), R.string.loading_msg, Toast.LENGTH_LONG).show();
}
@OnClick(R.id.tvUpgradeLtm)
public void updateLtm() {
final boolean[] balanceValid = {true};
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.alert_delete_dialog);
final Button btnDone = (Button) dialog.findViewById(R.id.btnDone);
final TextView alertMsg = (TextView) dialog.findViewById(R.id.alertMsg);
alertMsg.setText(getString(R.string.help_message));
final Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
btnCancel.setBackgroundColor(Color.RED);
btnCancel.setText(getString(R.string.txt_no));
btnDone.setText(getString(R.string.next));
btnDone.setOnClickListener(new View.OnClickListener() {
@SuppressLint("StringFormatInvalid")
@Override
public void onClick(View v) {
String ltmAmount=Helper.fetchStringSharePref(getActivity(),"ltmAmount");
//Check Balance
if (btnDone.getText().equals(getString(R.string.next))) {
alertMsg.setText("Upgrade to LTM now? " + ltmAmount + " BTS will be deducted from " + tvAccountName.getText().toString() + " account.");
btnDone.setText(getString(R.string.txt_yes));
btnCancel.setText(getString(R.string.txt_back));
} else {
dialog.cancel();
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
try {
for (int i = 0; i < accountDetails.size(); i++) {
if (accountDetails.get(i).isSelected) {
ArrayList<AccountAssets> arrayListAccountAssets = accountDetails.get(i).AccountAssets;
for (int j = 0; j < arrayListAccountAssets.size(); j++) {
AccountAssets accountAssets = arrayListAccountAssets.get(j);
if (accountAssets.symbol.equalsIgnoreCase("BTS")) {
Double amount = Double.valueOf(SupportMethods.ConvertValueintoPrecision(accountAssets.precision, accountAssets.ammount));
if (amount < Double.parseDouble(ltmAmount)) {
balanceValid[0] = false;
Toast.makeText(getActivity(), getString(R.string.insufficient_funds), Toast.LENGTH_LONG).show();
}
break;
}
}
}
}
} catch (Exception e) {
}
if (balanceValid[0]) {
showDialog("", getString(R.string.upgrading));
getAccountUpgradeInfo(getActivity(), tvAccountName.getText().toString());
}
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (btnCancel.getText().equals(getString(R.string.txt_back))) {
alertMsg.setText(getString(R.string.help_message));
btnCancel.setText(getString(R.string.txt_no));
btnDone.setText(getString(R.string.next));
} else {
dialog.cancel();
}
}
});
dialog.show();
}
@OnClick(R.id.qrCamera)
public void QrCodeActivity() {
if (isLoading) {
final Intent intent = new Intent(getContext(), qrcodeActivity.class);
intent.putExtra("id", 1);
Animation coinAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.coin_animation);
coinAnimation.setAnimationListener(new android.view.animation.Animation.AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
startActivity(intent);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
});
qrCamera.startAnimation(coinAnimation);
} else Toast.makeText(getContext(), R.string.loading_msg, Toast.LENGTH_LONG).show();
}
@OnClick(R.id.exportButton)
public void onExportButton() {
if (isLoading) {
TableDataAdapter myAdapter = tableView.getDataAdapter();
List<TransactionDetails> det = myAdapter.getData();
pdfTable myTable = new pdfTable(getContext(), getActivity(), "Transactions-scwall");
myTable.createTable(det);
} else Toast.makeText(getContext(), R.string.loading_msg, Toast.LENGTH_LONG).show();
}
public void loadBalancesFromSharedPref() {
try {
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
if (accountDetails.size() > 1) {
ivMultiAccArrow.setVisibility(View.VISIBLE);
} else {
ivMultiAccArrow.setVisibility(View.GONE);
}
for (int i = 0; i < accountDetails.size(); i++) {
if (accountDetails.get(i).isSelected)
{
ArrayList<AccountAssets> accountAsset = accountDetails.get(i).AccountAssets;
if ((accountAsset != null) && (accountAsset.size() > 0)) {
ArrayList<String> sym = new ArrayList<>();
ArrayList<String> pre = new ArrayList<>();
ArrayList<String> am = new ArrayList<>();
for (int j = 0; j < accountAsset.size(); j++) {
pre.add(j, accountAsset.get(j).precision);
sym.add(j, accountAsset.get(j).symbol);
am.add(j, accountAsset.get(j).ammount);
}
// getEquivalentComponents(accountAsset);
BalanceAssetsUpdate(sym, pre, am, true);
}
break;
}
}
} catch (Exception e) {
}
}
Handler updateEquivalentAmount;
@Override
public void isUpdate(ArrayList<String> ids, ArrayList<String> sym, ArrayList<String> pre, ArrayList<String> am) {
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
ArrayList<AccountAssets> accountAssets = new ArrayList<>();
for (int i = 0; i < ids.size(); i++)
{
long amount = Long.parseLong(am.get(i));
if ( amount != 0 )
{
AccountAssets accountAsset = new AccountAssets();
accountAsset.id = ids.get(i);
if (pre.size() > i) accountAsset.precision = pre.get(i);
if (sym.size() > i) accountAsset.symbol = sym.get(i);
if (am.size() > i) accountAsset.ammount = am.get(i);
accountAssets.add(accountAsset);
}
}
try
{
for (int i = 0; i < accountDetails.size(); i++) {
if (accountDetails.get(i).isSelected) {
accountDetails.get(i).AccountAssets = accountAssets;
getEquivalentComponents(accountAssets);
break;
}
}
}
catch (Exception w)
{
SupportMethods.testing("Assets", w, "Asset Activity");
}
SupportMethods.testing("Assets", "Assets views 3", "Asset Activity");
tinyDB.putListObject(getString(R.string.pref_wallet_accounts), accountDetails);
SupportMethods.testing("Assets", "Assets views 4", "Asset Activity");
BalanceAssetsUpdate(sym, pre, am, false);
}
public void BalanceAssetsUpdate(final ArrayList<String> sym, final ArrayList<String> pre, final ArrayList<String> am, final Boolean onStartUp) {
int count = llBalances.getChildCount();
// use standard asset names (like add bit etc)
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
ArrayList<String> symbols = assetsSymbols.updatedList(sym);
if (count <= 0)
BalanceAssetsLoad(symbols, pre, am, onStartUp);
if (count > 0)
BalanceAssetsUpdate(symbols, pre, am);
/*
Handler zeroBalanceHandler = new Handler();
Runnable zeroKardo = new Runnable() {
@Override
public void run() {
am.set(0,"0");
BalanceAssetsUpdate(sym, pre, am, false);
}
};
zeroBalanceHandler.postDelayed(zeroKardo,10000);
*/
}
private void getEquivalentComponents(final ArrayList<AccountAssets> accountAssets)
{
//AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
final Runnable getEquivalentCompRunnable = new Runnable() {
@Override
public void run() {
getEquivalentComponents(accountAssets);
}
};
String faitCurrency = Helper.getFadeCurrency(getContext());
if (faitCurrency.isEmpty())
{
faitCurrency = "EUR";
}
final String fc = faitCurrency;
final List<String> pairs = new ArrayList<>();
String values = "";
for (int i = 0; i < accountAssets.size(); i++) {
AccountAssets accountAsset = accountAssets.get(i);
if (!accountAsset.symbol.equals(faitCurrency)) {
values += accountAsset.symbol + ":" + faitCurrency + ",";
pairs.add(accountAsset.symbol + ":" + faitCurrency);
}
}
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("method", "equivalent_component");
hashMap.put("values", values.substring(0, values.length() - 1));
String url;
try
{
url = String.format(Locale.ENGLISH,"%s",getString(R.string.account_from_brainkey_url));
}
catch (Exception e)
{
return;
}
if ( url == null || url.isEmpty() )
{
return;
}
ServiceGenerator sg = new ServiceGenerator(url);
IWebService service = sg.getService(IWebService.class);
final Call<EquivalentComponentResponse> postingService = service.getEquivalentComponent(hashMap);
finalFaitCurrency = faitCurrency;
postingService.enqueue(new Callback<EquivalentComponentResponse>() {
@Override
public void onResponse(Response<EquivalentComponentResponse> response)
{
if (response.isSuccess())
{
EquivalentComponentResponse resp = response.body();
if (resp.status.equals("success"))
{
try
{
JSONObject rates = new JSONObject(resp.rates);
Iterator<String> keys = rates.keys();
HashMap<String,String> hm = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
hm.put(key.split(":")[0], rates.get(key).toString());
if ( pairs.contains(key) )
{
pairs.remove(key);
}
}
if ( getContext() == null ) return;
EquivalentFiatStorage myFiatStorage = new EquivalentFiatStorage(getContext());
myFiatStorage.saveEqHM(fc,hm);
if ( pairs.size() > 0 )
{
getEquivalentComponentsIndirect(pairs,fc);
return;
}
if ( getContext() == null ) return;
hm = myFiatStorage.getEqHM(fc);
for (int i = 0; i < llBalances.getChildCount(); i++)
{
LinearLayout llRow = (LinearLayout) llBalances.getChildAt(i);
for (int j = 1; j <= 2; j++) {
TextView tvAsset;
TextView tvAmount;
TextView tvFaitAmount;
if (j == 1)
{
tvAsset = (TextView) llRow.findViewById(R.id.symbol_child_one);
tvAmount = (TextView) llRow.findViewById(R.id.amount_child_one);
tvFaitAmount = (TextView) llRow.findViewById(R.id.fait_child_one);
}
else
{
tvAsset = (TextView) llRow.findViewById(R.id.symbol_child_two);
tvAmount = (TextView) llRow.findViewById(R.id.amount_child_two);
tvFaitAmount = (TextView) llRow.findViewById(R.id.fait_child_two);
}
if (tvAsset == null || tvAmount == null || tvFaitAmount == null)
{
updateEquivalentAmount.postDelayed(getEquivalentCompRunnable,500);
return;
}
String asset = tvAsset.getText().toString();
String amount = tvAmount.getText().toString();
asset = asset.replace("bit","");
//amount = android.text.Html.fromHtml(amount).toString();
if (amount.isEmpty())
{
amount = "0.0";
}
if (!amount.isEmpty() && hm.containsKey(asset))
{
Currency currency = Currency.getInstance(finalFaitCurrency);
try
{
double d = convertLocalizeStringToDouble(amount);
Double eqAmount = d * convertLocalizeStringToDouble(hm.get(asset).toString());
if ( Helper.isRTL(locale,currency.getSymbol()) )
{
tvFaitAmount.setText(String.format(locale, "%.2f %s", eqAmount,currency.getSymbol()));
}
else
{
tvFaitAmount.setText(String.format(locale, "%s %.2f", currency.getSymbol(),eqAmount));
}
tvFaitAmount.setVisibility(View.VISIBLE);
}
catch (Exception e)
{
tvFaitAmount.setVisibility(View.GONE);
}
}
else
{
tvFaitAmount.setVisibility(View.GONE);
}
}
}
}
catch (JSONException e)
{
updateEquivalentAmount.postDelayed(getEquivalentCompRunnable,500);
//e.printStackTrace();
}
}
else
{
updateEquivalentAmount.postDelayed(getEquivalentCompRunnable,500);
}
}
else
{
hideDialog();
updateEquivalentAmount.postDelayed(getEquivalentCompRunnable,500);
}
}
@Override
public void onFailure(Throwable t)
{
hideDialog();
//Toast.makeText(getActivity(), getString(R.string.txt_no_internet_connection), Toast.LENGTH_SHORT).show();
updateEquivalentAmount.postDelayed(getEquivalentCompRunnable,500);
}
});
}
private void getEquivalentComponentsIndirect(final List<String> leftOvers, final String faitCurrency)
{
//try
//{
final Runnable getEquivalentCompIndirectRunnable = new Runnable() {
@Override
public void run() {
getEquivalentComponentsIndirect(leftOvers, faitCurrency);
}
};
List<String> newPairs = new ArrayList<>();
for (String pair : leftOvers) {
String firstHalf = pair.split(":")[0];
newPairs.add(firstHalf + ":" + "BTS");
}
newPairs.add("BTS" + ":" + faitCurrency);
String values = "";
for (String pair : newPairs) {
values += pair + ",";
}
values = values.substring(0, values.length() - 1);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("method", "equivalent_component");
hashMap.put("values", values);
String url;
try
{
url = String.format(Locale.ENGLISH,"%s",getString(R.string.account_from_brainkey_url));
}
catch (Exception e)
{
return;
}
if ( url == null || url.isEmpty() )
{
return;
}
ServiceGenerator sg = new ServiceGenerator(url);
IWebService service = sg.getService(IWebService.class);
final Call<EquivalentComponentResponse> postingService = service.getEquivalentComponent(hashMap);
postingService.enqueue(new Callback<EquivalentComponentResponse>() {
@Override
public void onResponse(Response<EquivalentComponentResponse> response) {
if (response.isSuccess())
{
EquivalentComponentResponse resp = response.body();
if (resp.status.equals("success"))
{
try {
JSONObject rates = new JSONObject(resp.rates);
Iterator<String> keys = rates.keys();
String btsToFait = "";
while (keys.hasNext()) {
String key = keys.next();
if (key.equals("BTS:" + faitCurrency)) {
btsToFait = rates.get("BTS:" + faitCurrency).toString();
break;
}
}
HashMap<String,String> hm = new HashMap<>();
if (!btsToFait.isEmpty())
{
keys = rates.keys();
while (keys.hasNext())
{
String key = keys.next();
if (!key.equals("BTS:" + faitCurrency)) {
String asset = key.split(":")[0];
String assetConversionToBTS = rates.get(key).toString();
double newConversionRate = convertLocalizeStringToDouble(assetConversionToBTS) * convertLocalizeStringToDouble(btsToFait);
String assetToFaitConversion = Double.toString(newConversionRate);
hm.put(asset, assetToFaitConversion);
}
}
if ( getContext() == null ) return;
EquivalentFiatStorage myFiatStorage = new EquivalentFiatStorage(getContext());
myFiatStorage.saveEqHM(faitCurrency,hm);
}
if ( getContext() == null ) return;
EquivalentFiatStorage myFiatStorage = new EquivalentFiatStorage(getContext());
hm = myFiatStorage.getEqHM(faitCurrency);
for (int i = 0; i < llBalances.getChildCount(); i++) {
LinearLayout llRow = (LinearLayout) llBalances.getChildAt(i);
for (int j = 1; j <= 2; j++) {
TextView tvAsset;
TextView tvAmount;
TextView tvFaitAmount;
if (j == 1) {
tvAsset = (TextView) llRow.findViewById(R.id.symbol_child_one);
tvAmount = (TextView) llRow.findViewById(R.id.amount_child_one);
tvFaitAmount = (TextView) llRow.findViewById(R.id.fait_child_one);
} else {
tvAsset = (TextView) llRow.findViewById(R.id.symbol_child_two);
tvAmount = (TextView) llRow.findViewById(R.id.amount_child_two);
tvFaitAmount = (TextView) llRow.findViewById(R.id.fait_child_two);
}
if (tvAsset == null || tvAmount == null || tvFaitAmount == null) {
updateEquivalentAmount.postDelayed(getEquivalentCompIndirectRunnable, 500);
return;
}
String asset = tvAsset.getText().toString();
String amount = tvAmount.getText().toString();
asset = asset.replace("bit","");
if (!amount.isEmpty() && hm.containsKey(asset)) {
Currency currency = Currency.getInstance(faitCurrency);
try {
double d = convertLocalizeStringToDouble(amount);
Double eqAmount = d * convertLocalizeStringToDouble(hm.get(asset).toString());
if (Helper.isRTL(locale,currency.getSymbol())) {
tvFaitAmount.setText(String.format(locale, "%.2f %s", eqAmount, currency.getSymbol()));
} else {
tvFaitAmount.setText(String.format(locale, "%s %.2f", currency.getSymbol(), eqAmount));
}
tvFaitAmount.setVisibility(View.VISIBLE);
} catch (Exception e) {
tvFaitAmount.setVisibility(View.GONE);
}
}
}
}
}
catch (JSONException e)
{
hideDialog();
updateEquivalentAmount.postDelayed(getEquivalentCompIndirectRunnable, 500);
}
}
else
{
hideDialog();
updateEquivalentAmount.postDelayed(getEquivalentCompIndirectRunnable, 500);
}
}
else
{
hideDialog();
updateEquivalentAmount.postDelayed(getEquivalentCompIndirectRunnable, 500);
//Toast.makeText(getActivity(), getString(R.string.upgrade_failed), Toast.LENGTH_SHORT).show();
//updateEquivalentAmount.postDelayed(getEquivalentCompRunnable,500);
}
}
@Override
public void onFailure(Throwable t) {
hideDialog();
//Toast.makeText(getActivity(), getString(R.string.txt_no_internet_connection), Toast.LENGTH_SHORT).show();
updateEquivalentAmount.postDelayed(getEquivalentCompIndirectRunnable, 500);
}
});
//}
//catch (Exception e)
//{
//}
}
ArrayList<String> symbolsArray;
ArrayList<String> precisionsArray;
ArrayList<String> amountsArray;
private void updateBalanceArrays (final ArrayList<String> sym, final ArrayList<String> pre, final ArrayList<String> am)
{
try
{
symbolsArray = new ArrayList<>();
precisionsArray = new ArrayList<>();
amountsArray = new ArrayList<>();
for( int i = 0 ; i < sym.size() ; i++ )
{
Long _amount = Long.parseLong(am.get(i));
// remove balances which are zero
if ( _amount != 0 )
{
amountsArray.add(am.get(i));
precisionsArray.add(pre.get(i));
symbolsArray.add(sym.get(i));
}
}
}
catch (Exception e)
{
}
}
public void BalanceAssetsLoad(final ArrayList<String> sym, final ArrayList<String> pre, final ArrayList<String> am, final Boolean onStartUp) {
final AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
updateBalanceArrays( sym,pre,am );
sym.clear();
sym.addAll(symbolsArray);
pre.clear();
pre.addAll(precisionsArray);
am.clear();
am.addAll(amountsArray);
getActivity().runOnUiThread(new Runnable()
{
public void run()
{
SupportMethods.testing("Assets", "Assets views ", "Asset Activity");
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
llBalances.removeAllViews();
for (int i = 0; i < sym.size(); i += 2)
{
int counter = 1;
int op = sym.size();
int pr;
if ((op - i) > 2)
{
pr = 2;
}
else
{
pr = op - i;
}
View customView = layoutInflater.inflate(R.layout.items_rows_balances, null);
for (int l = i; l < i + pr; l++)
{
if (counter == 1)
{
TextView textView = (TextView) customView.findViewById(R.id.symbol_child_one);
//textView.setText(sym.get(l));
assetsSymbols.displaySpannable(textView,sym.get(l));
TextView textView1 = (TextView) customView.findViewById(R.id.amount_child_one);
float b = powerInFloat(pre.get(l), am.get(i));
if(assetsSymbols.isUiaSymbol(sym.get(l))) textView1.setText(String.format(locale, "%.4f", b));
else if(assetsSymbols.isSmartCoinSymbol(sym.get(l))) textView1.setText(String.format(locale, "%.2f", b));
else textView1.setText(String.format(locale, "%.4f", b));
}
if (counter == 2)
{
TextView textView2 = (TextView) customView.findViewById(R.id.symbol_child_two);
// textView2.setText(sym.get(l));
assetsSymbols.displaySpannable(textView2,sym.get(l));
TextView textView3 = (TextView) customView.findViewById(R.id.amount_child_two);
String r = returnFromPower(pre.get(l), am.get(l));
if(assetsSymbols.isUiaSymbol(sym.get(l))) textView3.setText(String.format(locale, "%.4f",Float.parseFloat(r)));
else if(assetsSymbols.isSmartCoinSymbol(sym.get(l))) textView3.setText(String.format(locale, "%.2f", Float.parseFloat(r)));
else textView3.setText(String.format(locale, "%.4f", Float.parseFloat(r)));
llBalances.addView(customView);
}
if (counter == 1 && i == sym.size() - 1)
{
TextView textView2 = (TextView) customView.findViewById(R.id.symbol_child_two);
textView2.setText("");
TextView textView3 = (TextView) customView.findViewById(R.id.amount_child_two);
textView3.setVisibility(View.GONE);
llBalances.addView(customView);
}
if (counter == 1)
{
counter = 2;
}
else counter = 1;
}
}
if (!onStartUp)
{
progressBar1.setVisibility(View.GONE);
isLoading = true;
}
else
{
try
{
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
for (int i = 0; i < accountDetails.size(); i++)
{
if (accountDetails.get(i).isSelected)
{
getEquivalentComponents(accountDetails.get(i).AccountAssets);
break;
}
}
} catch (Exception w) {
SupportMethods.testing("Assets", w, "Asset Activity");
}
}
whiteSpaceAfterBalances.setVisibility(View.GONE);
}
});
}
/* public void setCounter(CounterView counterView, float sValue, float eValue) {
if (counterView != null) {
counterView.setAutoStart(false);
counterView.setAutoFormat(false);
counterView.setStartValue(sValue);
counterView.setEndValue(eValue);
counterView.setIncrement(5f); // the amount the number increments at each time interval
counterView.setTimeInterval(5); // the time interval (ms) at which the text changes
counterView.setPrefix("");
counterView.setSuffix("");
counterView.start();
counterView.setTextLocale(locale);
}
}*/
private void rotateRecieveButton() {
ImageView rcvBtn = (ImageView) getActivity().findViewById(R.id.recievebtn);
final Animation rotAnim = AnimationUtils.loadAnimation(getContext(), R.anim.rotate360);
rcvBtn.startAnimation(rotAnim);
}
public void playSound() {
try {
AudioFilePath audioFilePath = new AudioFilePath(getContext());
MediaPlayer mediaPlayer = audioFilePath.fetchMediaPlayer();
if(mediaPlayer != null)
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void animateText(final TextView tvCounter, float startValue, float endValue) {
ValueAnimator animator = new ValueAnimator();
animator.setFloatValues(startValue, endValue);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float animateValue = Float.parseFloat(String.valueOf(animation.getAnimatedValue()));
tvCounter.setText(Helper.setLocaleNumberFormat(locale, animateValue));
}
});
animator.setEvaluator(new TypeEvaluator<Float>() {
public Float evaluate(float fraction, Float startValue, Float endValue) {
return startValue + (endValue - startValue) * fraction;
}
});
animator.setDuration(2000);
animator.start();
}
public void removeZeroedBalanceViews ()
{
getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
for (int i = 0; i < llBalances.getChildCount(); i++)
{
View row = llBalances.getChildAt(i);
TextView tvSymOne = (TextView) row.findViewById(R.id.symbol_child_one);
TextView tvAmOne = (TextView) row.findViewById(R.id.amount_child_one);
TextView tvfaitOne = (TextView) row.findViewById(R.id.fait_child_one);
TextView tvSymtwo = (TextView) row.findViewById(R.id.symbol_child_two);
TextView tvAmtwo = (TextView) row.findViewById(R.id.amount_child_two);
TextView tvFaitTwo = (TextView) row.findViewById(R.id.fait_child_two);
// If first balance in row is zeroed then update it
if (tvSymOne.getText().toString().equals("")) {
// shift balances from next child here
String symbol = "";
String amount = "";
String fait = "";
// Get next non-zero balance
if (tvSymtwo.getText().toString().isEmpty()) {
// if second balance in row is also empty then get next non-zero balance
for (int j = i+1; j < llBalances.getChildCount(); j++)
{
View nextrow = llBalances.getChildAt(j);
TextView tvSymOnenextrow = (TextView) nextrow.findViewById(R.id.symbol_child_one);
TextView tvAmOnenextrow = (TextView) nextrow.findViewById(R.id.amount_child_one);
TextView tvfaitOnenextrow = (TextView) nextrow.findViewById(R.id.fait_child_one);
if (!tvSymOnenextrow.getText().toString().isEmpty()) {
symbol = tvSymOnenextrow.getText().toString();
amount = tvAmOnenextrow.getText().toString();
fait = tvfaitOnenextrow.getText().toString();
tvSymOnenextrow.setText("");
tvAmOnenextrow.setText("");
tvfaitOnenextrow.setText("");
break;
}
TextView tvSymtwonextrow = (TextView) nextrow.findViewById(R.id.symbol_child_two);
TextView tvAmtwonextrow = (TextView) nextrow.findViewById(R.id.amount_child_two);
TextView tvFaitTwonextrow = (TextView) nextrow.findViewById(R.id.fait_child_two);
if (!tvSymtwonextrow.getText().toString().isEmpty()) {
symbol = tvSymtwonextrow.getText().toString();
amount = tvAmtwonextrow.getText().toString();
fait = tvFaitTwonextrow.getText().toString();
tvSymtwonextrow.setText("");
tvAmtwonextrow.setText("");
tvFaitTwonextrow.setText("");
break;
}
}
}
else
{
// if second balance is row is non-empty then move it to first balance
symbol = tvSymtwo.getText().toString();
amount = tvAmtwo.getText().toString();
fait = tvFaitTwo.getText().toString();
tvSymtwo.setText("");
tvAmtwo.setText("");
tvFaitTwo.setText("");
}
// update first balance amount
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
if(assetsSymbols.isUiaSymbol(symbol)) tvAmOne.setText(String.format(locale, "%.4f",Float.parseFloat(amount)));
else if(assetsSymbols.isSmartCoinSymbol(symbol)) tvAmOne.setText(String.format(locale, "%.2f", Float.parseFloat(amount)));
else tvAmOne.setText(String.format(locale, "%.4f", Float.parseFloat(amount)));
//tvSymOne.setText(symbol);
assetsSymbols.displaySpannable(tvSymOne,symbol);
// tvAmOne.setText(amount);
tvfaitOne.setText(fait);
if (fait.isEmpty())
{
tvfaitOne.setVisibility(View.GONE);
}
else
{
tvfaitOne.setVisibility(View.VISIBLE);
}
}
if (tvSymtwo.getText().toString().isEmpty()) {
String symbol = "";
String amount = "";
String fait = "";
// Get next non-zero balance
for (int j = i+1; j < llBalances.getChildCount(); j++) {
View nextrow = llBalances.getChildAt(j);
TextView tvSymOnenextrow = (TextView) nextrow.findViewById(R.id.symbol_child_one);
TextView tvAmOnenextrow = (TextView) nextrow.findViewById(R.id.amount_child_one);
TextView tvfaitOnenextrow = (TextView) nextrow.findViewById(R.id.fait_child_one);
if (!tvSymOnenextrow.getText().toString().isEmpty()) {
symbol = tvSymOnenextrow.getText().toString();
amount = tvAmOnenextrow.getText().toString();
fait = tvfaitOnenextrow.getText().toString();
tvSymOnenextrow.setText("");
tvAmOnenextrow.setText("");
tvfaitOnenextrow.setText("");
break;
}
TextView tvSymtwonextrow = (TextView) nextrow.findViewById(R.id.symbol_child_two);
TextView tvAmtwonextrow = (TextView) nextrow.findViewById(R.id.amount_child_two);
TextView tvFaitTwonextrow = (TextView) nextrow.findViewById(R.id.fait_child_two);
if (!tvSymtwonextrow.getText().toString().isEmpty()) {
symbol = tvSymtwonextrow.getText().toString();
amount = tvAmtwonextrow.getText().toString();
fait = tvFaitTwonextrow.getText().toString();
tvSymtwonextrow.setText("");
tvAmtwonextrow.setText("");
tvFaitTwonextrow.setText("");
break;
}
}
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
if(assetsSymbols.isUiaSymbol(symbol)) tvAmtwo.setText(String.format(locale, "%.4f",Float.parseFloat(amount)));
else if(assetsSymbols.isSmartCoinSymbol(symbol)) tvAmtwo.setText(String.format(locale, "%.2f", Float.parseFloat(amount)));
else tvAmtwo.setText(String.format(locale, "%.4f", Float.parseFloat(amount)));
//tvSymtwo.setText(symbol);
assetsSymbols.displaySpannable(tvSymtwo,symbol);
// tvAmtwo.setText(amount);
tvFaitTwo.setText(fait);
if (fait.isEmpty())
{
tvFaitTwo.setVisibility(View.GONE);
}
else
{
tvFaitTwo.setVisibility(View.VISIBLE);
}
}
}
// remove empty rows
for (int i = 0; i < llBalances.getChildCount(); i++) {
View row = llBalances.getChildAt(i);
TextView tvSymOne = (TextView) row.findViewById(R.id.symbol_child_one);
TextView tvSymtwo = (TextView) row.findViewById(R.id.symbol_child_two);
if (tvSymOne.getText().toString().isEmpty() && tvSymtwo.getText().toString().isEmpty()) {
llBalances.removeView(row);
}
}
if (llBalances.getChildCount() == 0) {
whiteSpaceAfterBalances.setVisibility(View.VISIBLE);
}
}
catch (Exception e)
{}
}
});
}
Handler animateNsoundHandler = new Handler();
public void BalanceAssetsUpdate(final ArrayList<String> sym, final ArrayList<String> pre, final ArrayList<String> am)
{
final Runnable reloadBalances = new Runnable() {
@Override
public void run() {
removeZeroedBalanceViews();
}
};
getActivity().runOnUiThread(new Runnable() {
public void run() {
try
{
// remove zero balances not in previously loaded balances
List<Integer> indexesToRemove = new ArrayList<>();
for( int i = 0 ; i < sym.size() ; i++ )
{
Long _amount = Long.parseLong(am.get(i));
if ( _amount == 0 )
{
Boolean matchFound = symbolsArray.contains(sym.get(i));
if ( !matchFound )
{
indexesToRemove.add(i);
sym.remove(i);
am.remove(i);
pre.remove(i);
sym.trimToSize();
am.trimToSize();
pre.trimToSize();
i--;
}
}
}
}
catch (Exception e)
{
}
try {
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int count = llBalances.getChildCount();
int m = 0;
try {
Log.d("Balances Update", "Start");
Boolean animateOnce = true;
for (int i = 0; i < count; i++)
{
// count == number of row
// m == number of child in the row
// Get balances row
LinearLayout linearLayout = (LinearLayout) llBalances.getChildAt(i);
TextView tvSymOne = (TextView) linearLayout.findViewById(R.id.symbol_child_one);
TextView tvAmOne = (TextView) linearLayout.findViewById(R.id.amount_child_one);
TextView tvfaitOne = (TextView) linearLayout.findViewById(R.id.fait_child_one);
TextView tvSymtwo = (TextView) linearLayout.findViewById(R.id.symbol_child_two);
TextView tvAmtwo = (TextView) linearLayout.findViewById(R.id.amount_child_two);
TextView tvFaitTwo = (TextView) linearLayout.findViewById(R.id.fait_child_two);
// First child updation
if (sym.size() > m)
{
Log.d("Balances Update", "sym size 1 : " + Long.toString(m));
String symbol = sym.get(m);
Log.d("Balances Update", "symbol : " + symbol);
String amount = "";
if (pre.size() > m && am.size() > m) {
amount = returnFromPower(pre.get(m), am.get(m));
}
Log.d("Balances Update", "amount : " + symbol);
String amountInInt = am.get(m);
Log.d("Balances Update", "amount in int : " + amountInInt);
String txtSymbol = "";// tvSymOne.getText().toString();
String txtAmount = "";//tvAmOne.getText().toString();
if (symbolsArray.size() > m) {
txtSymbol = symbolsArray.get(m);// tvSymOne.getText().toString();
txtAmount = amountsArray.get(m);//tvAmOne.getText().toString();
}
Log.d("Balances Update", "old symbol : " + txtSymbol);
Log.d("Balances Update", "old amount : " + txtAmount);
if (!symbol.equals(txtSymbol))
{
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
assetsSymbols.displaySpannable(tvSymOne,symbol);
//tvSymOne.setText(symbol);
}
if (!amountInInt.equals(txtAmount)) {
// previous amount
//float txtAmount_d = convertLocalizeStringToFloat(txtAmount);
if ( txtAmount.isEmpty() )
{
txtAmount = "0";
}
Long txtAmount_d = Long.parseLong(txtAmount);
// New amount
//float amount_d = convertLocalizeStringToFloat(amount);
Long amount_d = Long.parseLong(amountInInt);
// Balance is sent
if (txtAmount_d > amount_d) {
Log.d("Balances Update", "Balance sent");
SupportMethods.testing("float", txtAmount_d, "txtamount");
SupportMethods.testing("float", amount_d, "amount");
tvAmOne.setTypeface(tvAmOne.getTypeface(), Typeface.BOLD);
tvAmOne.setTextColor(getResources().getColor(R.color.red));
animateText(tvAmOne, convertLocalizeStringToFloat(tvAmOne.getText().toString()), convertLocalizeStringToFloat(amount));
final TextView cView = tvAmOne;
final TextView aView = tvSymOne;
final TextView bView = tvfaitOne;
//final Handler handler = new Handler();
final Runnable updateTask = new Runnable() {
@Override
public void run() {
try {
// cView.setTypeface(null, Typeface.NORMAL);
cView.setTextColor(getResources().getColor(R.color.green));
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(updateTask, 4000);
if (amount_d == 0) {
final Runnable zeroAmount = new Runnable() {
@Override
public void run() {
try {
cView.setText("");
aView.setText("");
bView.setText("");
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(zeroAmount, 4200);
animateNsoundHandler.postDelayed(reloadBalances, 5000);
}
Log.d("Balances Update", "Animation initiated");
}
// Balance is rcvd
else if (amount_d > txtAmount_d) {
Log.d("Balances Update", "Balance received");
tvAmOne.setTypeface(tvAmOne.getTypeface(), Typeface.BOLD);
tvAmOne.setTextColor(getResources().getColor(R.color.green));
// run animation
if (animateOnce) {
AudioFilePath audioFilePath = new AudioFilePath(getContext());
if(!audioFilePath.fetchAudioEnabled()) {
audioSevice = true;
getActivity().startService(new Intent(getActivity(), MediaService.class));
}
/* final Runnable playSOund = new Runnable() {
@Override
public void run() {
playSound();
}
};*/
final Runnable rotateTask = new Runnable() {
@Override
public void run() {
try {
getActivity().runOnUiThread(new Runnable() {
public void run() {
rotateRecieveButton();
}
});
} catch (Exception e) {
}
}
};
// animateNsoundHandler.postDelayed(playSOund, 100);
animateNsoundHandler.postDelayed(rotateTask, 200);
animateOnce = false;
Log.d("Balances Update", "Animation initiated");
}
animateText(tvAmOne, convertLocalizeStringToFloat(tvAmOne.getText().toString()), convertLocalizeStringToFloat(amount));
Log.d("Balances Update", "Text Animated");
final TextView cView = tvAmOne;
final TextView aView = tvSymOne;
final TextView bView = tvfaitOne;
//final Handler handler = new Handler();
final Runnable updateTask = new Runnable() {
@Override
public void run() {
try {
//cView.setTypeface(null, Typeface.NORMAL);
cView.setTextColor(getResources().getColor(R.color.green));
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(updateTask, 4000);
if (amount_d == 0) {
final Runnable zeroAmount = new Runnable() {
@Override
public void run() {
try {
cView.setText("");
aView.setText("");
bView.setText("");
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(zeroAmount, 4200);
animateNsoundHandler.postDelayed(reloadBalances, 5000);
}
Log.d("Balances Update", "Rcv done");
}
}
m++;
Log.d("Balances Update", "m++");
}
else
{
Log.d("Balances Update", "linearLayout.removeAllViews");
linearLayout.removeAllViews();
}
// Second child updation
if (sym.size() > m)
{
Log.d("Balances Update", "sym size 2 : " + Long.toString(m));
String symbol = sym.get(m);
String amount = "";
Log.d("Balances Update", "symbol : " + symbol);
if (pre.size() > m && am.size() > m) {
amount = returnFromPower(pre.get(m), am.get(m));
}
Log.d("Balances Update", "amount : " + amount);
String amountInInt = am.get(m);
Log.d("Balances Update", "amount in int : " + amountInInt);
String txtSymbol = "";
String txtAmount = "";
if (symbolsArray.size() > m) {
txtSymbol = symbolsArray.get(m);// tvSymOne.getText().toString();
txtAmount = amountsArray.get(m);//tvAmOne.getText().toString();
}
Log.d("Balances Update", "old symbol : " + txtSymbol);
Log.d("Balances Update", "old amount : " + txtAmount);
if ( txtAmount.isEmpty() )
{
txtAmount = "0";
}
//float txtAmount_d = convertLocalizeStringToFloat(txtAmount);
Long txtAmount_d = Long.parseLong(txtAmount);
//float amount_d = convertLocalizeStringToFloat(amount);
Long amount_d = Long.parseLong(amountInInt);
if (!symbol.equals(txtSymbol)) {
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
assetsSymbols.displaySpannable(tvSymtwo,symbol);
// tvSymtwo.setText(symbol);
}
if (!amountInInt.equals(txtAmount))
{
tvAmtwo.setVisibility(View.VISIBLE);
// balance is sent
if (txtAmount_d > amount_d)
{
Log.d("Balances Update", "Balance sent");
tvAmtwo.setTextColor(getResources().getColor(R.color.red));
tvAmtwo.setTypeface(tvAmtwo.getTypeface(), Typeface.BOLD);
animateText(tvAmtwo, convertLocalizeStringToFloat(tvAmtwo.getText().toString()), convertLocalizeStringToFloat(amount));
Log.d("Balances Update", "Text animated");
final TextView cView = tvAmtwo;
final TextView aView = tvSymtwo;
final TextView bView = tvFaitTwo;
final Runnable updateTask = new Runnable() {
@Override
public void run() {
try {
//cView.setTypeface(null, Typeface.NORMAL);
cView.setTextColor(getResources().getColor(R.color.green));
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(updateTask, 4000);
if (amount_d == 0) {
final Runnable zeroAmount = new Runnable() {
@Override
public void run() {
try
{
cView.setText("");
aView.setText("");
bView.setText("");
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(zeroAmount, 4200);
animateNsoundHandler.postDelayed(reloadBalances, 5000);
}
Log.d("Balances Update","Animation done");
}
// Balance is recieved
else if (amount_d > txtAmount_d)
{
Log.d("Balances Update","Balance is received");
tvAmtwo.setTextColor(getResources().getColor(R.color.green));
tvAmtwo.setTypeface(tvAmtwo.getTypeface(), Typeface.BOLD);
// run animation
if (animateOnce) {
final Runnable playSOund = new Runnable() {
@Override
public void run() {
try
{
playSound();
}
catch (Exception e)
{
}
}
};
final Runnable rotateTask = new Runnable() {
@Override
public void run() {
try {
getActivity().runOnUiThread(new Runnable() {
public void run() {
try
{
rotateRecieveButton();
}
catch (Exception e)
{
}
}
});
} catch (Exception e) {
}
}
};
animateNsoundHandler.postDelayed(playSOund, 100);
animateNsoundHandler.postDelayed(rotateTask, 200);
animateOnce = false;
Log.d("Balances Update", "Animation initiated");
}
animateText(tvAmtwo, convertLocalizeStringToFloat(tvAmtwo.getText().toString()), convertLocalizeStringToFloat(amount));
Log.d("Balances Update","Text animated");
final TextView cView = tvAmtwo;
final TextView aView = tvSymtwo;
final TextView bView = tvFaitTwo;
//final Handler handler = new Handler();
final Runnable updateTask = new Runnable() {
@Override
public void run() {
try
{
// cView.setTypeface(null, Typeface.NORMAL);
cView.setTextColor(getResources().getColor(R.color.green));
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(updateTask, 4000);
if (amount_d == 0) {
final Runnable zeroAmount = new Runnable() {
@Override
public void run() {
try {
cView.setText("");
aView.setText("");
bView.setText("");
}
catch (Exception e)
{
}
}
};
animateNsoundHandler.postDelayed(zeroAmount, 4200);
animateNsoundHandler.postDelayed(reloadBalances, 5000);
}
Log.d("Balances Update","rcv done");
}
}
m++;
Log.d("Balances Update","m updated");
}
else
{
Log.d("Balances Update","else when sym > m");
// i == number of row
if (i == (count - 1) ) // if its the last row
{
if (sym.size() > m) // if number of balances is more than traversed
m--; // then minus 1 from m
}
}
}
// Calculate m : number of balances loaded in ui
m = 0;
for ( int i = 0 ; i < llBalances.getChildCount(); i++ )
{
LinearLayout linearLayout = (LinearLayout) llBalances.getChildAt(i);
TextView tvSymOne = (TextView) linearLayout.findViewById(R.id.symbol_child_one);
TextView tvSymtwo = (TextView) linearLayout.findViewById(R.id.symbol_child_two);
if ( !tvSymOne.getText().toString().isEmpty() )
{
m++;
}
if ( !tvSymtwo.getText().toString().isEmpty() )
{
m++;
}
}
Log.d("Balances Update","Number of balances loaded : " + Long.toString(m));
// Insert/remove balance objects if updated
Log.d("Balances Update","Insert or remove balance objects if needed");
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
int loop = sym.size() - m; // number of extra balances to be loaded
if (loop > 0)
{
Log.d("Balances Update","Yes updation required : " + Long.toString(loop));
for (int i = m; i < sym.size(); i += 2)
{
int counter = 1;
int totalNumberOfBalances = sym.size(); // total number of balances 6
int pr;
if ( (totalNumberOfBalances - i) > 2 )
{
pr = 2;
}
else
{
pr = totalNumberOfBalances - i;
}
View customView = layoutInflater.inflate(R.layout.items_rows_balances, null);
for (int l = i; l < (i + pr); l++)
{
if (counter == 1)
{
TextView textView = (TextView) customView.findViewById(R.id.symbol_child_one);
// textView.setText(sym.get(l));
assetsSymbols.displaySpannable(textView,sym.get(l));
TextView textView1 = (TextView) customView.findViewById(R.id.amount_child_one);
if ( (pre.size() > l) && (am.size() > i) )
{
String r = returnFromPower(pre.get(l), am.get(i));
textView1.setText(r);
// setCounter(textView1, 0f, 0f);
textView1.setText(String.format(locale, "%.4f", Float.parseFloat(r)));
//setCounter(textView1, Float.parseFloat(r), Float.parseFloat(r));
}
else textView1.setText("");
}
if (counter == 2)
{
TextView textView2 = (TextView) customView.findViewById(R.id.symbol_child_two);
// textView2.setText(sym.get(l));
assetsSymbols.displaySpannable(textView2,sym.get(l));
TextView textView3 = (TextView) customView.findViewById(R.id.amount_child_two);
if ( (pre.size() > l) && (am.size() > l) )
{
String r = returnFromPower(pre.get(l), am.get(l));
textView3.setText(String.format(locale, "%.4f", Float.parseFloat(r)));
//setCounter(textView3, 0f, 0f);
// setCounter(textView3, Float.parseFloat(r), Float.parseFloat(r));
}
llBalances.addView(customView);
// run animation
if (animateOnce) {
final Runnable playSOund = new Runnable() {
@Override
public void run() {
try {
playSound();
}
catch (Exception e)
{
}
}
};
final Runnable rotateTask = new Runnable() {
@Override
public void run() {
try {
getActivity().runOnUiThread(new Runnable() {
public void run() {
rotateRecieveButton();
}
});
} catch (Exception e) {
}
}
};
animateNsoundHandler.postDelayed(playSOund, 100);
animateNsoundHandler.postDelayed(rotateTask, 200);
animateOnce = false;
Log.d("Balances Update", "Animation initiated");
}
}
if ( (counter == 1) && ( i == (sym.size() - 1) ) )
{
llBalances.addView(customView);
// run animation
if (animateOnce) {
final Runnable playSOund = new Runnable() {
@Override
public void run() {
try {
playSound();
}
catch (Exception e)
{
}
}
};
final Runnable rotateTask = new Runnable() {
@Override
public void run() {
try {
getActivity().runOnUiThread(new Runnable() {
public void run() {
rotateRecieveButton();
}
});
} catch (Exception e) {
}
}
};
animateNsoundHandler.postDelayed(playSOund, 100);
animateNsoundHandler.postDelayed(rotateTask, 200);
animateOnce = false;
Log.d("Balances Update", "Animation initiated");
}
}
if (counter == 1)
{
counter = 2;
}
else counter = 1;
}
}
}
}
catch (Exception e)
{
Log.d("Balances Update", e.getMessage());
}
}
catch (Exception e)
{
Log.d("Balances Load", e.getMessage());
}
progressBar1.setVisibility(View.GONE);
whiteSpaceAfterBalances.setVisibility(View.GONE);
isLoading = true;
updateBalanceArrays( sym,pre,am );
}
});
}
String returnFromPower(String i, String str) {
Double ok = 1.0;
Double pre = Double.valueOf(i);
Double value = Double.valueOf(str);
for (int k = 0; k < pre; k++) {
ok = ok * 10;
}
return Double.toString(value / ok);
}
float powerInFloat(String i, String str) {
float ok = 1.0f;
float pre = Float.parseFloat(i);
float value = Float.parseFloat(str);
for (int k = 0; k < pre; k++) {
ok = ok * 10;
}
return (value / ok);
}
public void updateSortTableView(SortableTableView<TransactionDetails> tableView, List<TransactionDetails> myTransactions) {
SimpleTableHeaderAdapter simpleTableHeaderAdapter = new SimpleTableHeaderAdapter(getContext(), getContext().getString(R.string.date), getContext().getString(R.string.all), getContext().getString(R.string.to_from), getContext().getString(R.string.amount));
simpleTableHeaderAdapter.setPaddingLeft(getResources().getDimensionPixelSize(R.dimen.transactionsheaderpading));
tableView.setHeaderAdapter(simpleTableHeaderAdapter);
tableView.setHeaderSortStateViewProvider(SortStateViewProviders.darkArrows());
tableView.setColumnWeight(0, 17);
tableView.setColumnWeight(1, 12);
tableView.setColumnWeight(2, 30);
tableView.setColumnWeight(3, 20);
tableView.setColumnComparator(0, new TransactionsDateComparator());
tableView.setColumnComparator(1, new TransactionsSendRecieveComparator());
tableView.setColumnComparator(3, new TransactionsAmountComparator());
//tableView.setDataAdapter(new TransactionsTableAdapter(getContext(), myTransactions));
/*
TableDataAdapter myAdapter = tableView.getDataAdapter();
List<TransactionDetails> det = myAdapter.getData();
float height = tableView.getHeight();
for(int l=0; l<=30; l++){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2016);
cal.set(Calendar.MONTH, 3);
cal.set(Calendar.DATE, l);
cal.set(Calendar.HOUR_OF_DAY, 14);
cal.set(Calendar.MINUTE, 33);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date myDate = cal.getTime();
myTransactions.add(new TransactionDetails(myDate,true,"yasir-ibrahim","yasir-mobile","#scwal",(float)l,"OBITS",(float)3.33,"USD"));
}
*/
}
@Override
public void soundFinish() {
if(audioSevice) {
getActivity().stopService(new Intent(getActivity(), MediaService.class));
}
audioSevice = false;
}
private static class TransactionsDateComparator implements Comparator<TransactionDetails>
{
@Override
public int compare(TransactionDetails one, TransactionDetails two) {
return one.getDate().compareTo(two.getDate());
}
}
private static class TransactionsSendRecieveComparator implements Comparator<TransactionDetails>
{
@Override
public int compare(TransactionDetails one, TransactionDetails two) {
return one.getSent().compareTo(two.getSent());
}
}
private static int compareFloats(float change1, float change2)
{
if (change1 < change2) {
return -1;
} else if (change1 == change2) {
return 0; // Fails on NaN however, not sure what you want
} else if (change2 > change2) {
return 1;
} else {
return 1;
}
}
private static int compareDoubles(double change1, double change2)
{
if (change1 < change2) {
return -1;
} else if (change1 == change2) {
return 0; // Fails on NaN however, not sure what you want
} else if (change2 > change2) {
return 1;
} else {
return 1;
}
}
private static class TransactionsAmountComparator implements Comparator<TransactionDetails> {
@Override
public int compare(TransactionDetails one, TransactionDetails two) {
return compareDoubles(one.getAmount(), two.getAmount());
}
}
private void saveTransactions(List<TransactionDetails> transactionDetails, String accountName) {
tinyDB.putTransactions(getActivity(), getContext(), getResources().getString(R.string.pref_local_transactions) + accountName, new ArrayList<>(transactionDetails));
}
private ArrayList<TransactionDetails> getTransactionsFromSharedPref(String accountName)
{
ArrayList<TransactionDetails> mySavedList = tinyDB.getTransactions(getResources().getString(R.string.pref_local_transactions) + accountName, TransactionDetails.class);
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
assetsSymbols.updatedTransactionDetails(mySavedList);
for (TransactionDetails td : mySavedList) {
td.updateContext(getContext());
}
return mySavedList;
}
TransactionsTableAdapter myTransactionsTableAdapter;
public void TransactionUpdateOnStartUp(String accountName)
{
final List<TransactionDetails> localTransactionDetails = getTransactionsFromSharedPref(accountName);
if (localTransactionDetails != null && localTransactionDetails.size() > 0)
{
//myTransactions.addAll(localTransactionDetails);
getActivity().runOnUiThread(new Runnable()
{
public void run()
{
//isSavedTransactions = true;
if ( myTransactionsTableAdapter == null )
{
myTransactionsTableAdapter = new TransactionsTableAdapter(getContext(), localTransactionDetails);
}
else
{
myTransactionsTableAdapter.clear();
myTransactionsTableAdapter.addAll(localTransactionDetails);
}
tableView.setDataAdapter(myTransactionsTableAdapter);
// load_more_values.setVisibility(View.VISIBLE);
// load_more_values.setEnabled(true);
tableViewparent.setVisibility(View.VISIBLE);
}
});
}
}
Handler updateTransactionsList;
@Override
public void TransactionUpdate(final List<TransactionDetails> transactionDetails, final int number_of_transactions_in_queue)
{
/*
sentCallForTransactions = false;
try
{
if(isSavedTransactions)
{
myTransactions.clear();
isSavedTransactions = false;
myTransactions = new ArrayList<>();
}
if (myTransactions.size() == 0)
{
saveTransactions(transactionDetails);
}
myTransactions.addAll(transactionDetails);
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
myTransactions = assetsSymbols.updatedTransactionDetails(myTransactions);
//tableView.setDataAdapter(new TransactionsTableAdapter(getContext(), myTransactions));
getActivity().runOnUiThread(new Runnable() {
@Override
public void run()
{
if ( updateTransactionsList == null )
{
updateTransactionsList = new Handler();
}
if (number_of_transactions_in_queue == 0)
{
load_more_values.setVisibility(View.GONE);
} else {
load_more_values.setVisibility(View.VISIBLE);
load_more_values.setEnabled(true);
}
//tableView.setDataAdapter(myTransactionsTableAdapter);
//tableView.getDataAdapter().clear();
//tableView.getDataAdapter().addAll(myTransactions);
if ( progressBar.getVisibility() != View.GONE )
progressBar.setVisibility(View.GONE);
if ( tableViewparent.getVisibility() != View.VISIBLE )
tableViewparent.setVisibility(View.VISIBLE);
}
});
if ( myTransactionsTableAdapter == null )
{
myTransactionsTableAdapter = new TransactionsTableAdapter(getContext(), myTransactions);
tableView.setDataAdapter(myTransactionsTableAdapter);
}
else
{
myTransactionsTableAdapter = new TransactionsTableAdapter(getContext(), myTransactions);
tableView.setDataAdapter(myTransactionsTableAdapter);
}
}
catch (Exception e) {
SupportMethods.testing("TransactionUpdate", e, "try/catch");
}
*/
}
int counterRepeatTransactionLoad = 0;
@Override
public void transactionsLoadComplete(List<TransactionDetails> transactionDetails,int newTransactionsLoaded)
{
//sentCallForTransactions = false;
try
{
/*
if ( number_of_transactions_loaded == 0 )
{
myTransactions.clear();
}
if(isSavedTransactions)
{
myTransactions.clear();
isSavedTransactions = false;
myTransactions = new ArrayList<>();
}
if (myTransactions.size() == 0)
{
saveTransactions(transactionDetails);
}
*/
if ( updateTriggerFromNetworkBroadcast && ( newTransactionsLoaded == 0 ) && (counterRepeatTransactionLoad++ < 20) )
{
if (Application.isReady)
{
Application.webSocketG.close();
}
loadTransactions(getContext(), accountId, this, wifkey, number_of_transactions_loaded, number_of_transactions_to_load, myTransactions);
return;
}
updateTriggerFromNetworkBroadcast = false;
counterRepeatTransactionLoad = 0;
Context context = getContext();
// update context
for(TransactionDetails td:transactionDetails)
{
td.updateContext(context);
}
myTransactions.clear();
myTransactions.addAll(transactionDetails);
AssetsSymbols assetsSymbols = new AssetsSymbols(getContext());
myTransactions = assetsSymbols.updatedTransactionDetails(myTransactions);
saveTransactions(myTransactions,to);
number_of_transactions_loaded += number_of_transactions_to_load;
getActivity().runOnUiThread(new Runnable() {
@Override
public void run()
{
if ( updateTransactionsList == null )
{
updateTransactionsList = new Handler();
}
if ( myTransactionsTableAdapter == null )
{
Set<TransactionDetails> hs = new HashSet<>();
hs.addAll(myTransactions);
myTransactions.clear();
myTransactions.addAll(hs);
Collections.sort(myTransactions, new transactionsDateComparator());
myTransactionsTableAdapter = new TransactionsTableAdapter(getContext(), myTransactions);
tableView.setDataAdapter(myTransactionsTableAdapter);
}
else
{
Set<TransactionDetails> hs = new HashSet<>();
hs.addAll(myTransactions);
myTransactions.clear();
myTransactions.addAll(hs);
Collections.sort(myTransactions, new transactionsDateComparator());
myTransactionsTableAdapter = new TransactionsTableAdapter(getContext(), myTransactions);
tableView.setDataAdapter(myTransactionsTableAdapter);
}
if (myTransactionActivity.finalBlockRecieved)
{
load_more_values.setVisibility(View.GONE);
}
else
{
load_more_values.setVisibility(View.VISIBLE);
load_more_values.setEnabled(true);
}
if ( progressBar.getVisibility() != View.GONE )
progressBar.setVisibility(View.GONE);
if ( tableViewparent.getVisibility() != View.VISIBLE )
tableViewparent.setVisibility(View.VISIBLE);
}
});
/*
if ( number_of_transactions_loaded < 20 )
{
loadTransactions(getContext(), accountId, this, wifkey, number_of_transactions_loaded, number_of_transactions_to_load);
}
*/
}
catch (Exception e)
{
SupportMethods.testing("TransactionUpdate", e, "try/catch");
}
}
@Override
public void transactionsLoadMessageStatus(String message)
{
}
@Override
public void transactionsLoadFailure(String reason)
{
//sentCallForTransactions = false;
if ( reason.equals(getContext().getString(R.string.account_names_not_found)) )
{
//number_of_transactions_loaded += number_of_transactions_to_load;
}
//if ( reason.equals(getContext().getString(R.string.no_assets_found)) )
//{
//number_of_transactions_loaded += number_of_transactions_to_load;
loadTransactions(getContext(), accountId, this, wifkey, number_of_transactions_loaded, number_of_transactions_to_load,myTransactions);
//return;
//}
/*
getActivity().runOnUiThread(new Runnable() {
@Override
public void run()
{
if (myTransactionActivity.finalBlockRecieved)
{
load_more_values.setVisibility(View.GONE);
}
else
{
load_more_values.setVisibility(View.VISIBLE);
load_more_values.setEnabled(true);
}
if ( progressBar.getVisibility() != View.GONE )
progressBar.setVisibility(View.GONE);
if ( tableViewparent.getVisibility() != View.VISIBLE )
tableViewparent.setVisibility(View.VISIBLE);
}
});
*/
}
@OnClick(R.id.load_more_values)
public void Load_more_Values() {
load_more_values.setEnabled(false);
progressBar.setVisibility(View.VISIBLE);
number_of_transactions_to_load = 20;
loadTransactions(getContext(), accountId, this, wifkey, number_of_transactions_loaded, number_of_transactions_to_load,myTransactions);
//number_of_transactions_loaded = number_of_transactions_loaded + 20;
}
void isLifeTime(final String name_id, final String id) {
String getDetails = "{\"id\":" + id + ",\"method\":\"call\",\"params\":[";
String getDetails2 = ",\"get_accounts\",[[\"" + name_id + "\"]]]}";
myWebSocketHelper.make_websocket_call(getDetails,getDetails2, webSocketCallHelper.api_identifier.database);
}
/*
void get_full_accounts(final String name_id, final String id)
{
String getDetails = "{\"id\":" + id + ",\"method\":\"call\",\"params\":[";
String getDetails2 = ",\"get_full_accounts\",[[\"" + name_id + "\"],true]]}";
myWebSocketHelper.make_websocket_call(getDetails,getDetails2, webSocketCallHelper.api_identifier.database);
}
*/
@Override
public void getLifetime(String s, int id) {
myWebSocketHelper.cleanUpTransactionsHandler();
SupportMethods.testing("getLifetime", s, "s");
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
SupportMethods.testing("getAccountID", s, "s");
String result = SupportMethods.ParseJsonObject(s, "result");
String nameObject = SupportMethods.ParseObjectFromJsonArray(result, 0);
String expiration = SupportMethods.ParseJsonObject(nameObject, "membership_expiration_date");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
Date date1 = dateFormat.parse(expiration);
Date date2 = dateFormat.parse("1969-12-31T23:59:59");
if (date2.getTime() >= date1.getTime()) {
SupportMethods.testing("getLifetime", "true", "s");
//accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
if (accountDetails.size() > accountDetailsId) {
accountDetails.get(accountDetailsId).isLifeTime = true;
showHideLifeTime(true);
} else if (accountDetails.size() == 1) {
accountDetails.get(0).isLifeTime = true;
showHideLifeTime(true);
}
tinyDB.putListObject(getString(R.string.pref_wallet_accounts), accountDetails);
} else {
SupportMethods.testing("getLifetime", "false", "s");
}
} catch (Exception e) {
SupportMethods.testing("getLifetime", e, "Exception");
}
}
void startAnimation() {
scrollViewBalances.fullScroll(View.FOCUS_UP);
scrollViewBalances.pageScroll(View.FOCUS_UP);
qrCamera.setVisibility(View.INVISIBLE);
backLine.setVisibility(View.INVISIBLE);
final Animation animationFadeIn = AnimationUtils.loadAnimation(getContext(), R.anim.fade_in);
final Animation animationRigthtoLeft = AnimationUtils.loadAnimation(getContext(), R.anim.home_anim);
animationRigthtoLeft.setInterpolator(new AccelerateDecelerateInterpolator());
qrCamera.postDelayed(new Runnable() {
public void run() {
qrCamera.startAnimation(animationRigthtoLeft);
qrCamera.setVisibility(View.VISIBLE);
}
}, 333);
backLine.postDelayed(new Runnable() {
public void run() {
backLine.setVisibility(View.VISIBLE);
backLine.startAnimation(animationFadeIn);
}
}, 999);
}
@Override
public void setUserVisibleHint(boolean visible) {
super.setUserVisibleHint(visible);
if (visible) {
if (qrCamera != null && backLine != null) {
startAnimation();
} else {
myHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (qrCamera != null && backLine != null) {
startAnimation();
} else myHandler.postDelayed(this, 333);
}
}, 333);
}
}
}
Handler loadOndemand = new Handler();
private void loadOnDemand(final Activity _activity)
{
try {
loadOndemand.removeCallbacksAndMessages(null);
Runnable loadOnDemandRunnable = new Runnable() {
@Override
public void run() {
try {
_activity.runOnUiThread(new Runnable() {
public void run() {
//sentCallForTransactions = false;
//isSavedTransactions = true;
loadViews(false, true, false);
}
});
}
catch (Exception e){}
}
};
//loadOndemand.removeCallbacks(loadOnDemandRunnable);
loadOndemand.postDelayed(loadOnDemandRunnable, 5000);
}
catch (Exception e){}
}
boolean updateTriggerFromNetworkBroadcast = false;
@Override
public void loadAll()
{
//extra
if(!updateTriggerFromNetworkBroadcast) {
//
ArrayList<TransactionDetails> mySavedList = tinyDB.getTransactions(getResources().getString(R.string.pref_local_transactions) + to, TransactionDetails.class);
mySavedList.clear();
tinyDB.putTransactions(getActivity(), getContext(), getResources().getString(R.string.pref_local_transactions) + to, mySavedList);
//original
updateTriggerFromNetworkBroadcast = true;
loadOnDemand(getActivity());
}
}
AssestsActivty myAssetsActivity;
boolean firstTimeLoad = true;
String transactionsLoadedAccountName = "";
void loadViews(Boolean onResume,Boolean accountNameChanged,boolean faitCurrencyChanged) {
if ( firstTimeLoad )
{
//if(!isSavedTransactions)
//{
tableViewparent.setVisibility(View.GONE);
myTransactions = new ArrayList<>();
updateSortTableView(tableView, myTransactions);
//}
tableView.addDataClickListener(new tableViewClickListener(getContext()));
progressBar.setVisibility(View.VISIBLE);
load_more_values.setVisibility(View.GONE);
firstTimeLoad = false;
}
whiteSpaceAfterBalances.setVisibility(View.VISIBLE);
if (myAssetsActivity == null)
{
myAssetsActivity = new AssestsActivty(getContext(), to, this, application);
myAssetsActivity.registerDelegate();
}
// get transactions from sharedPref
myTransactions = getTransactionsFromSharedPref(to);
//myTransactions.clear();
//saveTransactions(myTransactions);
if ( !onResume || accountNameChanged || faitCurrencyChanged )
{
progressBar1.setVisibility(View.VISIBLE);
myAssetsActivity.loadBalances(to);
//sentCallForTransactions = false;
progressBar.setVisibility(View.VISIBLE);
load_more_values.setVisibility(View.GONE);
number_of_transactions_loaded = 0;
number_of_transactions_to_load = 20;
loadTransactions(getContext(), accountId, this, wifkey, number_of_transactions_loaded, number_of_transactions_to_load, myTransactions);
}
}
void loadBasic(boolean onResume,boolean accountNameChanged, boolean faitCurrencyChanged) {
if ( !onResume )
{
isLoading = false;
}
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
if (accountDetails.size() == 1) {
accountDetailsId = 0;
accountDetails.get(0).isSelected = true;
to = accountDetails.get(0).account_name;
accountId = accountDetails.get(0).account_id;
wifkey = accountDetails.get(0).wif_key;
showHideLifeTime(accountDetails.get(0).isLifeTime);
tinyDB.putListObject(getString(R.string.pref_wallet_accounts), accountDetails);
} else {
for (int i = 0; i < accountDetails.size(); i++) {
if (accountDetails.get(i).isSelected) {
accountDetailsId = i;
to = accountDetails.get(i).account_name;
accountId = accountDetails.get(i).account_id;
wifkey = accountDetails.get(i).wif_key;
showHideLifeTime(accountDetails.get(i).isLifeTime);
break;
}
}
}
Application.monitorAccountId = accountId;
tvAccountName.setText(to);
isLifeTime(accountId, "15");
//get_full_accounts(accountId, "17");
loadViews(onResume,accountNameChanged, faitCurrencyChanged);
}
Boolean checkIfAccountNameChange() {
//ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
String checkAccountName = "";
if (accountDetails.size() == 1) {
checkAccountName = accountDetails.get(0).account_name;
ivMultiAccArrow.setVisibility(View.GONE);
} else {
ivMultiAccArrow.setVisibility(View.VISIBLE);
for (int i = 0; i < accountDetails.size(); i++) {
if (accountDetails.get(i).isSelected) {
checkAccountName = accountDetails.get(i).account_name;
break;
}
}
}
return !checkAccountName.equals(to);
}
void onChangedAccount(){
final ArrayList<AccountDetails> accountDetailsList;
accountDetailsList = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
List<String> accountlist = new ArrayList<String>();
for (int i = 0; i < accountDetailsList.size(); i++) {
accountlist.add(accountDetailsList.get(i).account_name);
}
AlertDialog.Builder builderSingle = new AlertDialog.Builder(getContext());
builderSingle.setTitle(getString(R.string.imported_created_accounts));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
getContext(), android.R.layout.simple_list_item_1, accountlist);
builderSingle.setAdapter(
arrayAdapter,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String strName = arrayAdapter.getItem(which);
for (int i = 0; i < accountDetailsList.size(); i++) {
if (strName.equals(accountDetailsList.get(i).account_name)) {
accountDetailsList.get(i).isSelected = true;
} else {
accountDetailsList.get(i).isSelected = false;
}
}
tinyDB.putListObject(getString(R.string.pref_wallet_accounts), accountDetailsList);
Helper.storeStringSharePref(getContext(), getString(R.string.pref_account_name), strName);
onResume();
dialog.dismiss();
}
});
builderSingle.show();
}
@OnClick(R.id.ivMultiAccArrow)
public void ivOnChangedAccount(View view){
onChangedAccount();
}
@OnClick(R.id.account_name)
public void tvOnChangedAccount(View view){
onChangedAccount();
}
private void showHideLifeTime(final Boolean show) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (show) {
ivLifeTime.setVisibility(View.VISIBLE);
tvUpgradeLtm.setVisibility(View.GONE);
} else {
ivLifeTime.setVisibility(View.GONE);
tvUpgradeLtm.setVisibility(View.VISIBLE);
}
}
});
}
public void getAccountUpgradeInfo(final Activity activity, final String accountName) {
ServiceGenerator sg = new ServiceGenerator(getString(R.string.account_from_brainkey_url));
IWebService service = sg.getService(IWebService.class);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("method", "upgrade_account");
hashMap.put("account", accountName);
try {
hashMap.put("wifkey", Crypt.getInstance().decrypt_string(wifkey));
} catch (Exception e) {
}
final Call<AccountUpgrade> postingService = service.getAccountUpgrade(hashMap);
postingService.enqueue(new Callback<AccountUpgrade>() {
@Override
public void onResponse(Response<AccountUpgrade> response) {
if (response.isSuccess()) {
AccountUpgrade accountDetails = response.body();
if (accountDetails.status.equals("success")) {
updateLifeTimeModel(accountName);
hideDialog();
Toast.makeText(activity, getString(R.string.upgrade_success), Toast.LENGTH_SHORT).show();
} else {
hideDialog();
Toast.makeText(activity, getString(R.string.upgrade_failed), Toast.LENGTH_SHORT).show();
}
} else {
hideDialog();
Toast.makeText(activity, getString(R.string.upgrade_failed), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Throwable t) {
hideDialog();
Toast.makeText(activity, activity.getString(R.string.txt_no_internet_connection), Toast.LENGTH_SHORT).show();
}
});
}
public void getLtmPrice(final Activity activity, final String accountName) {
ServiceGenerator sg = new ServiceGenerator(getString(R.string.account_from_brainkey_url));
IWebService service = sg.getService(IWebService.class);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("method", "upgrade_account_fees");
hashMap.put("account", accountName);
try {
hashMap.put("wifkey", Crypt.getInstance().decrypt_string(wifkey));
} catch (Exception e) {
}
final Call<LtmFee> postingService = service.getLtmFee(hashMap);
postingService.enqueue(new Callback<LtmFee>() {
@Override
public void onResponse(Response<LtmFee> response) {
if (response.isSuccess()) {
hideDialog();
LtmFee ltmFee = response.body();
if (ltmFee.status.equals("success")) {
try {
JSONObject jsonObject = new JSONObject(ltmFee.transaction);
JSONObject jsonObject1 = jsonObject.getJSONArray("operations").getJSONArray(0).getJSONObject(1);
JSONObject jsonObject2 = jsonObject1.getJSONObject("fee");
String amount = jsonObject2.getString("amount");
//String asset_id = jsonObject2.getString("asset_id");
String temp = SupportMethods.ConvertValueintoPrecision("5", amount);
Helper.storeStringSharePref(getActivity(), "ltmAmount", temp);
} catch (Exception e) {
}
}
}
}
@Override
public void onFailure(Throwable t) {
hideDialog();
Toast.makeText(activity, activity.getString(R.string.txt_no_internet_connection), Toast.LENGTH_SHORT).show();
}
});
}
private void hideDialog() {
try {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.cancel();
}
}
}
});
}
catch (Exception e)
{}
}
private void showDialog(String title, String msg) {
if (progressDialog != null) {
if (!progressDialog.isShowing()) {
progressDialog.setTitle(title);
progressDialog.setMessage(msg);
progressDialog.show();
}
}
}
private void updateLifeTimeModel(String accountName) {
ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class);
try {
for (int i = 0; i < accountDetails.size(); i++) {
if (accountDetails.get(i).account_name.equals(accountName)) {
accountDetails.get(i).isLifeTime = true;
break;
}
}
} catch (Exception e) {
}
tinyDB.putListObject(getString(R.string.pref_wallet_accounts), accountDetails);
showHideLifeTime(true);
}
private float convertLocalizeStringToFloat(String text) {
float txtAmount_d = 0;
try {
NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
Number number = format.parse(text);
txtAmount_d = number.floatValue();
} catch (Exception e) {
try {
NumberFormat format = NumberFormat.getInstance(locale);
Number number = format.parse(text);
txtAmount_d = number.floatValue();
} catch (Exception e1) {
}
}
return txtAmount_d;
}
private double convertLocalizeStringToDouble(String text) {
double txtAmount_d = 0;
try {
NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
Number number = format.parse(text);
txtAmount_d = number.doubleValue();
} catch (Exception e) {
try {
NumberFormat format = NumberFormat.getInstance(locale);
Number number = format.parse(text);
txtAmount_d = number.doubleValue();
} catch (Exception e1) {
}
}
return txtAmount_d;
}
private int convertLocalizeStringToInt(String text) {
int txtAmount_d = 0;
try {
NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
Number number = format.parse(text);
txtAmount_d = number.intValue();
} catch (Exception e) {
try {
NumberFormat format = NumberFormat.getInstance(locale);
Number number = format.parse(text);
txtAmount_d = number.intValue();
} catch (Exception e1) {
}
}
return txtAmount_d;
}
// Boolean closed = false;
TransactionActivity myTransactionActivity;
void loadTransactions(final Context context,final String id,final AssetDelegate in ,final String wkey,final int loaded,final int toLoad, final ArrayList<TransactionDetails> alreadyLoadedTransactions)
{
// new TransactionActivity(context, id ,in , wkey , loaded , toLoad,alreadyLoadedTransactions);
//sentCallForTransactions = true;
// if(closed) {
if (myTransactionActivity == null) {
myTransactionActivity = new TransactionActivity(context, id, in, wkey, loaded, toLoad, alreadyLoadedTransactions);
} else {
//myTransactionActivity = null;
myTransactionActivity.context = null;
myTransactionActivity = new TransactionActivity(context, id, in, wkey, loaded, toLoad, alreadyLoadedTransactions);
}
// }
//new TransactionActivity(context, id ,in , wkey , loaded , toLoad);
}
/*
void loadTransactions(final Context context,final String id ,final String wkey,final int loaded,final int toLoad)
{
sentCallForTransactions = true;
new TransactionActivity(context, id ,this , wkey , loaded , toLoad);
}
*/
// final Handler handlerTransactions = new Handler();
// handlerTransactions.postDelayed(new Runnable() {
// @Override
// public void run() {
//
// if(!rcvdCallForTransactions && sentCallForTransactions) {
// new TransactionActivity(context, id ,in , wkey , loaded , toLoad);
// handlerTransactions.postDelayed(this, 20000);
// }
//
// if(!sentCallForTransactions){
// sentCallForTransactions = true;
// new TransactionActivity(context, id ,in , wkey , loaded , toLoad);
// handlerTransactions.postDelayed(this, 20000);
// }
//
// if(rcvdCallForTransactions){
// handlerTransactions.removeCallbacks(this);
// handlerTransactions.removeCallbacksAndMessages(this);
// }
//
// }
// }, 100);
// }
}
| transactions issue resolve ,done
| app/src/main/java/de/bitshares_munich/fragments/BalancesFragment.java | transactions issue resolve ,done |
|
Java | mit | 5075b476affb4053615dcd31850e9d2f6915c72e | 0 | Geforce132/SecurityCraft | package net.geforcemods.securitycraft.network.server;
import java.util.function.Supplier;
import net.geforcemods.securitycraft.SCContent;
import net.geforcemods.securitycraft.blockentities.SecurityCameraBlockEntity;
import net.geforcemods.securitycraft.blocks.SecurityCameraBlock;
import net.geforcemods.securitycraft.util.ModuleUtils;
import net.geforcemods.securitycraft.util.PlayerUtils;
import net.geforcemods.securitycraft.util.Utils;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.fmllegacy.network.NetworkEvent;
public class MountCamera
{
private BlockPos pos;
public MountCamera() {}
public MountCamera(BlockPos pos)
{
this.pos = pos;
}
public static void encode(MountCamera message, FriendlyByteBuf buf)
{
buf.writeBlockPos(message.pos);
}
public static MountCamera decode(FriendlyByteBuf buf)
{
MountCamera message = new MountCamera();
message.pos = buf.readBlockPos();
return message;
}
public static void onMessage(MountCamera message, Supplier<NetworkEvent.Context> ctx)
{
ctx.get().enqueueWork(() -> {
BlockPos pos = message.pos;
ServerPlayer player = ctx.get().getSender();
Level world = player.level;
BlockState state = world.getBlockState(pos);
if(world.isLoaded(pos) && state.getBlock() == SCContent.SECURITY_CAMERA.get() && world.getBlockEntity(pos) instanceof SecurityCameraBlockEntity te)
{
if(te.getOwner().isOwner(player) || ModuleUtils.isAllowed(te, player))
((SecurityCameraBlock)state.getBlock()).mountCamera(world, pos, player);
else
PlayerUtils.sendMessageToPlayer(player, Utils.localize(SCContent.CAMERA_MONITOR.get().getDescriptionId()), Utils.localize("messages.securitycraft:notOwned", te.getOwner().getName()), ChatFormatting.RED);
}
else
PlayerUtils.sendMessageToPlayer(player, Utils.localize(SCContent.CAMERA_MONITOR.get().getDescriptionId()), Utils.localize("messages.securitycraft:cameraMonitor.cameraNotAvailable", pos), ChatFormatting.RED);
});
ctx.get().setPacketHandled(true);
}
}
| src/main/java/net/geforcemods/securitycraft/network/server/MountCamera.java | package net.geforcemods.securitycraft.network.server;
import java.util.function.Supplier;
import net.geforcemods.securitycraft.SCContent;
import net.geforcemods.securitycraft.blockentities.SecurityCameraBlockEntity;
import net.geforcemods.securitycraft.blocks.SecurityCameraBlock;
import net.geforcemods.securitycraft.util.ModuleUtils;
import net.geforcemods.securitycraft.util.PlayerUtils;
import net.geforcemods.securitycraft.util.Utils;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.fmllegacy.network.NetworkEvent;
public class MountCamera
{
private BlockPos pos;
public MountCamera() {}
public MountCamera(BlockPos pos)
{
this.pos = pos;
}
public static void encode(MountCamera message, FriendlyByteBuf buf)
{
buf.writeBlockPos(message.pos);
}
public static MountCamera decode(FriendlyByteBuf buf)
{
MountCamera message = new MountCamera();
message.pos = buf.readBlockPos();
return message;
}
public static void onMessage(MountCamera message, Supplier<NetworkEvent.Context> ctx)
{
ctx.get().enqueueWork(() -> {
BlockPos pos = message.pos;
ServerPlayer player = ctx.get().getSender();
Level world = player.level;
BlockState state = world.getBlockState(pos);
if(world.isLoaded(pos) && state.getBlock() == SCContent.SECURITY_CAMERA.get() && world.getBlockEntity(pos) instanceof SecurityCameraBlockEntity te)
{
if(te.getOwner().isOwner(player) || ModuleUtils.isAllowed(te, player))
((SecurityCameraBlock)state.getBlock()).mountCamera(world, pos, player);
else
PlayerUtils.sendMessageToPlayer(player, Utils.localize(SCContent.CAMERA_MONITOR.get().getDescriptionId()), Utils.localize("messages.securitycraft:notOwned", pos), ChatFormatting.RED);
}
else
PlayerUtils.sendMessageToPlayer(player, Utils.localize(SCContent.CAMERA_MONITOR.get().getDescriptionId()), Utils.localize("messages.securitycraft:cameraMonitor.cameraNotAvailable", pos), ChatFormatting.RED);
});
ctx.get().setPacketHandled(true);
}
}
| fix incorrect argument in "not owned" message
| src/main/java/net/geforcemods/securitycraft/network/server/MountCamera.java | fix incorrect argument in "not owned" message |
|
Java | mit | c6416ce7e274196f6ec7f1d021980ad67bc43312 | 0 | oleg-nenashev/remoting,jenkinsci/remoting,jenkinsci/remoting,oleg-nenashev/remoting | package hudson.remoting;
import hudson.remoting.Channel.Mode;
import hudson.remoting.CommandTransport.CommandReceiver;
import org.jenkinsci.remoting.nio.NioChannelBuilder;
import org.junit.After;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import static org.junit.Assert.*;
/**
* Tests the effect of {@link ClassFilter}.
*
* <p>
* This test code targets each of the known layers where object serialization is used.
* Specifically, those are {@link ObjectInputStream} (and subtypes) created in:
*
* <ul>
* <li>{@link Capability#read(InputStream)}
* <li>{@link UserRequest#deserialize(Channel, byte[], ClassLoader)},
* <li>{@link ChannelBuilder#makeTransport(InputStream, OutputStream, Mode, Capability)}
* <li>{@link AbstractByteArrayCommandTransport#setup(Channel, CommandReceiver)}
* <li>{@link AbstractSynchronousByteArrayCommandTransport#read()}
* </ul>
*
* @author Kohsuke Kawaguchi
*/
public class ClassFilterTest implements Serializable {
/**
* North can defend itself from south but not the other way around.
*/
private transient DualSideChannelRunner runner;
private transient Channel north, south;
private static class TestFilter extends ClassFilter {
@Override
protected boolean isBlacklisted(String name) {
return name.contains("Security218");
}
}
/**
* Set up a channel pair where north side is well protected from south side but not the other way around.
*/
private void setUp() throws Exception {
setUp(new InProcessRunner() {
@Override
protected ChannelBuilder configureNorth() {
return super.configureNorth()
.withClassFilter(new TestFilter());
}
});
}
/**
* Set up a channel pair with no capacity. In the context of this test,
* the lack of chunked encoding triggers a different transport implementation, and the lack of
* multi-classloader support triggers {@link UserRequest} to select a different deserialization mechanism.
*/
private void setUpWithNoCapacity() throws Exception {
setUp(new InProcessRunner() {
@Override
protected ChannelBuilder configureNorth() {
return super.configureNorth()
.withCapability(Capability.NONE)
.withClassFilter(new TestFilter());
}
@Override
protected ChannelBuilder configureSouth() {
return super.configureSouth().withCapability(Capability.NONE);
}
});
}
private void setUp(DualSideChannelRunner runner) throws Exception {
this.runner = runner;
north = runner.start();
south = runner.getOtherSide();
clearRecord();
}
@After
public void tearDown() throws Exception {
if (runner!=null)
runner.stop(north);
}
/**
* Makes sure {@link Capability#read(InputStream)} rejects unexpected payload.
*/
@Test
public void capabilityRead() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(Mode.TEXT.wrap(baos));
oos.writeObject(new Security218("rifle"));
oos.close();
try {
Capability.read(new ByteArrayInputStream(baos.toByteArray()));
} catch (SecurityException e) {
assertEquals("Rejected: "+Security218.class.getName(), e.getMessage());
}
}
/**
* This test case targets object stream created in
* {@link UserRequest#deserialize(Channel, byte[], ClassLoader)} with multiclassloader support.
*/
@Test
public void userRequest() throws Exception {
setUp();
userRequestTestSequence();
}
/**
* Variant of {@link #userRequest()} test that targets
* {@link UserRequest#deserialize(Channel, byte[], ClassLoader)} *without* multiclassloader support.
*/
@Test
public void userRequest_singleClassLoader() throws Exception {
setUpWithNoCapacity();
userRequestTestSequence();
}
private void userRequestTestSequence() throws Exception {
// control case to prove that an attack will succeed to without filter.
fire("caesar", north);
assertTrue(getAttack().contains("caesar>south"));
clearRecord();
// the test case that should be rejected by a filter.
try {
fire("napoleon", south);
fail("Expected call to fail");
} catch (IOException e) {
String msg = toString(e);
assertTrue(msg, msg.contains("Rejected: " + Security218.class.getName()));
assertTrue(getAttack(), getAttack().isEmpty());
assertFalse(getAttack().contains("napoleon>north"));
}
}
/**
* Sends an attack payload over {@link Channel#call(Callable)}
*/
private void fire(String name, Channel from) throws Exception {
final Security218 a = new Security218(name);
from.call(new CallableBase<Void, IOException>() {
@Override
public Void call() throws IOException {
a.toString(); // this will ensure 'a' gets sent over
return null;
}
});
}
/**
* This test case targets command stream created in
* {@link AbstractSynchronousByteArrayCommandTransport#read()}, which is used
* by {@link ChunkedCommandTransport}.
*/
@Test
public void transport_chunking() throws Exception {
setUp();
commandStreamTestSequence();
}
/**
* This test case targets command stream created in
* {@link ChannelBuilder#makeTransport(InputStream, OutputStream, Mode, Capability)}
* by not having the chunking capability.
*/
@Test
public void transport_non_chunking() throws Exception {
setUpWithNoCapacity();
commandStreamTestSequence();
}
/**
* This test case targets command stream created in
* {@link AbstractByteArrayCommandTransport#setup(Channel, CommandReceiver)}
*/
@Test
public void transport_nio() throws Exception {
setUp(new NioSocketRunner() {
@Override
protected NioChannelBuilder configureNorth() {
return super.configureNorth()
.withClassFilter(new TestFilter());
}
});
commandStreamTestSequence();
}
private void commandStreamTestSequence() throws Exception {
// control case to prove that an attack will succeed to without filter.
north.send(new Security218("eisenhower"));
north.syncIO(); // any synchronous RPC call would do
assertTrue(getAttack().contains("eisenhower>south"));
clearRecord();
// the test case that should be rejected by a filter
try {
south.send(new Security218("hitler"));
north.syncIO(); // transport_chunking hangs if this is 'south.syncIO', because somehow south
// doesn't notice that the north has aborted and the connection is lost.
// this is indicative of a larger problem, but one that's not related to
// SECURITY-218 at hand, so I'm going to leave this with 'north.syncIO'
// it still achieves the effect of blocking until the command is processed by north,
// because the response from south back to north would have to come after Security218
// command.
// fail("the receiving end will abort after receiving Security218, so syncIO should fail");
// ... except for NIO, which just discards that command and keeps on
// } catch (RequestAbortedException e) {
// // other transport kills the connection
// String msg = toString(e);
// assertTrue(msg, msg.contains("Rejected: " + Security218.class.getName()));
} catch (Exception e) {
e.printStackTrace();
}
// either way, the attack payload should have been discarded before it gets deserialized
assertTrue(getAttack(), getAttack().isEmpty());
assertFalse(getAttack().contains("hitler>north"));
}
private String toString(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
return sw.toString();
}
/**
* An attack payload that leaves a trace on the receiver side if it gets read from the stream.
* Extends from {@link Command} to be able to test command stream.
*/
static class Security218 extends Command implements Serializable {
private final String attack;
public Security218(String attack) {
this.attack = attack;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
System.setProperty("attack", attack + ">" + Channel.current().getName());
}
@Override
protected void execute(Channel channel) {
// nothing to do here
}
}
private String getAttack() {
return System.getProperty("attack");
}
private void clearRecord() {
System.setProperty("attack", "");
}
} | src/test/java/hudson/remoting/ClassFilterTest.java | package hudson.remoting;
import hudson.remoting.Channel.Mode;
import hudson.remoting.CommandTransport.CommandReceiver;
import org.jenkinsci.remoting.nio.NioChannelBuilder;
import org.junit.After;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.*;
/**
* Tests the effect of {@link ClassFilter}.
*
* <p>
* This test code targets each of the known layers where object serialization is used.
* Specifically, those are {@link ObjectInputStream} (and subtypes) created in:
*
* <ul>
* <li>{@link Capability#read(InputStream)}
* <li>{@link UserRequest#deserialize(Channel, byte[], ClassLoader)},
* <li>{@link ChannelBuilder#makeTransport(InputStream, OutputStream, Mode, Capability)}
* <li>{@link AbstractByteArrayCommandTransport#setup(Channel, CommandReceiver)}
* <li>{@link AbstractSynchronousByteArrayCommandTransport#read()}
* </ul>
*
* @author Kohsuke Kawaguchi
*/
public class ClassFilterTest implements Serializable {
/**
* North can defend itself from south but not the other way around.
*/
private transient DualSideChannelRunner runner;
private transient Channel north, south;
private static class TestFilter extends ClassFilter {
@Override
protected boolean isBlacklisted(String name) {
return name.contains("Security218");
}
}
/**
* Set up a channel pair where north side is well protected from south side but not the other way around.
*/
private void setUp() throws Exception {
setUp(new InProcessRunner() {
@Override
protected ChannelBuilder configureNorth() {
return super.configureNorth()
.withClassFilter(new TestFilter());
}
});
}
/**
* Set up a channel pair with no capacity. In the context of this test,
* the lack of chunked encoding triggers a different transport implementation, and the lack of
* multi-classloader support triggers {@link UserRequest} to select a different deserialization mechanism.
*/
private void setUpWithNoCapacity() throws Exception {
setUp(new InProcessRunner() {
@Override
protected ChannelBuilder configureNorth() {
return super.configureNorth()
.withCapability(Capability.NONE)
.withClassFilter(new TestFilter());
}
@Override
protected ChannelBuilder configureSouth() {
return super.configureSouth().withCapability(Capability.NONE);
}
});
}
private void setUp(DualSideChannelRunner runner) throws Exception {
this.runner = runner;
north = runner.start();
south = runner.getOtherSide();
ATTACKS.clear();
}
@After
public void tearDown() throws Exception {
if (runner!=null)
runner.stop(north);
}
/**
* Makes sure {@link Capability#read(InputStream)} rejects unexpected payload.
*/
@Test
public void capabilityRead() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(Mode.TEXT.wrap(baos));
oos.writeObject(new Security218("rifle"));
oos.close();
try {
Capability.read(new ByteArrayInputStream(baos.toByteArray()));
} catch (SecurityException e) {
assertEquals("Rejected: "+Security218.class.getName(), e.getMessage());
}
}
/**
* This test case targets object stream created in
* {@link UserRequest#deserialize(Channel, byte[], ClassLoader)} with multiclassloader support.
*/
@Test
public void userRequest() throws Exception {
setUp();
userRequestTestSequence();
}
/**
* Variant of {@link #userRequest()} test that targets
* {@link UserRequest#deserialize(Channel, byte[], ClassLoader)} *without* multiclassloader support.
*/
@Test
public void userRequest_singleClassLoader() throws Exception {
setUpWithNoCapacity();
userRequestTestSequence();
}
private void userRequestTestSequence() throws Exception {
// control case to prove that an attack will succeed to without filter.
fire("caesar", north);
assertTrue(ATTACKS.contains("caesar>south"));
ATTACKS.clear();
// the test case that should be rejected by a filter.
try {
fire("napoleon", south);
fail("Expected call to fail");
} catch (IOException e) {
String msg = toString(e);
assertTrue(msg, msg.contains("Rejected: " + Security218.class.getName()));
assertTrue(ATTACKS.toString(), ATTACKS.isEmpty());
assertFalse(ATTACKS.contains("napoleon>north"));
}
}
/**
* Sends an attack payload over {@link Channel#call(Callable)}
*/
private void fire(String name, Channel from) throws Exception {
final Security218 a = new Security218(name);
from.call(new CallableBase<Void, IOException>() {
@Override
public Void call() throws IOException {
a.toString(); // this will ensure 'a' gets sent over
return null;
}
});
}
/**
* This test case targets command stream created in
* {@link AbstractSynchronousByteArrayCommandTransport#read()}, which is used
* by {@link ChunkedCommandTransport}.
*/
@Test
public void transport_chunking() throws Exception {
setUp();
commandStreamTestSequence();
}
/**
* This test case targets command stream created in
* {@link ChannelBuilder#makeTransport(InputStream, OutputStream, Mode, Capability)}
* by not having the chunking capability.
*/
@Test
public void transport_non_chunking() throws Exception {
setUpWithNoCapacity();
commandStreamTestSequence();
}
/**
* This test case targets command stream created in
* {@link AbstractByteArrayCommandTransport#setup(Channel, CommandReceiver)}
*/
@Test
public void transport_nio() throws Exception {
setUp(new NioSocketRunner() {
@Override
protected NioChannelBuilder configureNorth() {
return super.configureNorth()
.withClassFilter(new TestFilter());
}
});
commandStreamTestSequence();
}
private void commandStreamTestSequence() throws Exception {
// control case to prove that an attack will succeed to without filter.
north.send(new Security218("eisenhower"));
north.syncIO(); // any synchronous RPC call would do
assertTrue(ATTACKS.contains("eisenhower>south"));
ATTACKS.clear();
// the test case that should be rejected by a filter
try {
south.send(new Security218("hitler"));
north.syncIO(); // transport_chunking hangs if this is 'south.syncIO', because somehow south
// doesn't notice that the north has aborted and the connection is lost.
// this is indicative of a larger problem, but one that's not related to
// SECURITY-218 at hand, so I'm going to leave this with 'north.syncIO'
// it still achieves the effect of blocking until the command is processed by north,
// because the response from south back to north would have to come after Security218
// command.
// fail("the receiving end will abort after receiving Security218, so syncIO should fail");
// ... except for NIO, which just discards that command and keeps on
// } catch (RequestAbortedException e) {
// // other transport kills the connection
// String msg = toString(e);
// assertTrue(msg, msg.contains("Rejected: " + Security218.class.getName()));
} catch (Exception e) {
e.printStackTrace();
}
// either way, the attack payload should have been discarded before it gets deserialized
assertTrue(ATTACKS.toString(), ATTACKS.isEmpty());
assertFalse(ATTACKS.contains("hitler>north"));
}
private String toString(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
return sw.toString();
}
/**
* An attack payload that leaves a trace on the receiver side if it gets read from the stream.
* Extends from {@link Command} to be able to test command stream.
*/
static class Security218 extends Command implements Serializable {
private final String attack;
public Security218(String attack) {
this.attack = attack;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
ATTACKS.add(attack + ">" + Channel.current().getName());
}
@Override
protected void execute(Channel channel) {
// nothing to do here
}
}
/**
* Successful attacks will leave a trace here.
*/
static Set<String> ATTACKS = new HashSet<String>();
} | Storing attack record as system property
... to ensure it really is global in the whole JVM
| src/test/java/hudson/remoting/ClassFilterTest.java | Storing attack record as system property |
|
Java | mit | cd04b173541fffc3c7533c805db9263c49b08cad | 0 | jenkinsci/email-ext-plugin,jenkinsci/email-ext-plugin,jenkinsci/email-ext-plugin,jenkinsci/email-ext-plugin | package hudson.plugins.emailext.plugins.content;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import hudson.Functions;
import hudson.model.AbstractBuild;
import hudson.model.Hudson;
import hudson.model.Result;
import hudson.model.User;
import hudson.plugins.emailext.ExtendedEmailPublisher;
import hudson.plugins.emailext.ExtendedEmailPublisherDescriptor;
import hudson.scm.ChangeLogSet;
import hudson.scm.EditType;
import org.jvnet.hudson.test.HudsonTestCase;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
public class ScriptContentTest
extends HudsonTestCase
{
private ScriptContent scriptContent;
private Map<String, Object> args;
private final String osName = System.getProperty("os.name");
private final boolean osIsDarwin = osName.equals("Mac OS X") || osName.equals("Darwin");
private ExtendedEmailPublisher publisher;
@Override
public void setUp()
throws Exception
{
super.setUp();
assumeThat(osIsDarwin, is(false));
scriptContent = new ScriptContent();
args = new HashMap<String, Object>();
publisher = new ExtendedEmailPublisher();
publisher.defaultContent = "For only 10 easy payment of $69.99 , AWESOME-O 4000 can be yours!";
publisher.defaultSubject = "How would you like your very own AWESOME-O 4000?";
publisher.recipientList = "[email protected]";
Field f = ExtendedEmailPublisherDescriptor.class.getDeclaredField( "defaultBody" );
f.setAccessible( true );
f.set( ExtendedEmailPublisher.DESCRIPTOR, "Give me $4000 and I'll mail you a check for $40,000!" );
f = ExtendedEmailPublisherDescriptor.class.getDeclaredField( "defaultSubject" );
f.setAccessible( true );
f.set( ExtendedEmailPublisher.DESCRIPTOR, "Nigerian needs your help!" );
f = ExtendedEmailPublisherDescriptor.class.getDeclaredField( "recipientList" );
f.setAccessible( true );
f.set( ExtendedEmailPublisher.DESCRIPTOR, "[email protected]" );
f = ExtendedEmailPublisherDescriptor.class.getDeclaredField( "hudsonUrl" );;;;
f.setAccessible( true );
f.set( ExtendedEmailPublisher.DESCRIPTOR, "http://localhost/" );
}
public void testShouldFindScriptOnClassPath()
throws Exception
{
args.put(ScriptContent.SCRIPT_NAME_ARG, "empty-script-on-classpath.groovy");
assertEquals("HELLO WORLD!", scriptContent.getContent(mock( AbstractBuild.class ), publisher, null, args));
}
public void testShouldFindTemplateOnClassPath()
throws Exception
{
args.put(ScriptContent.SCRIPT_TEMPLATE_ARG, "empty-groovy-template-on-classpath.template");
// the template adds a newline
assertEquals("HELLO WORLD!\n", scriptContent.getContent(mock(AbstractBuild.class), publisher, null, args));
}
public void testWhenScriptNotFoundThrowFileNotFoundException()
throws Exception
{
args.put(ScriptContent.SCRIPT_NAME_ARG, "script-does-not-exist");
assertEquals("Script [script-does-not-exist] or template [groovy-html.template] was not found in $JENKINS_HOME/email-templates.",
scriptContent.getContent(mock(AbstractBuild.class), publisher, null, args));
}
public void testWhenTemplateNotFoundThrowFileNotFoundException()
throws Exception
{
args.put(ScriptContent.SCRIPT_TEMPLATE_ARG, "template-does-not-exist");
assertEquals("Script [email-ext.groovy] or template [template-does-not-exist] was not found in $JENKINS_HOME/email-templates.",
scriptContent.getContent(mock(AbstractBuild.class), publisher, null, args));
}
/**
* this is for groovy template testing
* @throws Exception
*/
public void testWithGroovyTemplate() throws Exception {
args.put(ScriptContent.SCRIPT_TEMPLATE_ARG, "groovy-sample.template");
args.put(ScriptContent.SCRIPT_INIT_ARG, false);
// mock the build
AbstractBuild build = mock(AbstractBuild.class);
when(build.getResult()).thenReturn(Result.SUCCESS);
when(build.getUrl()).thenReturn("email-test/34");
// mock changeSet
mockChangeSet(build);
// generate result from groovy template
String content = scriptContent.getContent(build, publisher, null, args);
// read expected file in resource to easy compare
String expectedFile = "hudson/plugins/emailext/templates/" + "groovy-sample.result";
InputStream in = getClass().getClassLoader().getResourceAsStream(expectedFile);
String expected = new Scanner(in).useDelimiter("\\Z").next();
// windows has a \r in each line, so make sure the comparison works correctly
if(Functions.isWindows()) {
expected = expected.replace("\r", "");
}
// remove end space before compare
assertEquals(expected.trim(), content.trim());
}
private void mockChangeSet(final AbstractBuild build) {
Mockito.when(build.getChangeSet()).thenReturn(new ChangeLogSet(build) {
@Override
public boolean isEmptySet() {
return false;
}
public Iterator iterator() {
return Arrays.asList(new Entry() {
@Override
public String getMsg() {
return "COMMIT MESSAGE";
}
@Override
public User getAuthor() {
User user = mock(User.class);
when(user.getDisplayName()).thenReturn("Kohsuke Kawaguchi");
return user;
}
@Override
public Collection<String> getAffectedPaths() {
return Arrays.asList("path1", "path2");
}
@Override
public String getMsgAnnotated() {
return getMsg();
}
@Override
public Collection<? extends AffectedFile> getAffectedFiles() {
return Arrays.asList(
new AffectedFile() {
public String getPath() {
return "path1";
}
public EditType getEditType() {
return EditType.EDIT;
}
},
new AffectedFile() {
public String getPath() {
return "path2";
}
public EditType getEditType() {
return EditType.ADD;
}
});
}
}).iterator();
}
});
}
}
| src/test/java/hudson/plugins/emailext/plugins/content/ScriptContentTest.java | package hudson.plugins.emailext.plugins.content;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import hudson.model.AbstractBuild;
import hudson.model.Hudson;
import hudson.model.Result;
import hudson.model.User;
import hudson.plugins.emailext.ExtendedEmailPublisher;
import hudson.plugins.emailext.ExtendedEmailPublisherDescriptor;
import hudson.scm.ChangeLogSet;
import hudson.scm.EditType;
import org.jvnet.hudson.test.HudsonTestCase;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
public class ScriptContentTest
extends HudsonTestCase
{
private ScriptContent scriptContent;
private Map<String, Object> args;
private final String osName = System.getProperty("os.name");
private final boolean osIsDarwin = osName.equals("Mac OS X") || osName.equals("Darwin");
private ExtendedEmailPublisher publisher;
@Override
public void setUp()
throws Exception
{
super.setUp();
assumeThat(osIsDarwin, is(false));
scriptContent = new ScriptContent();
args = new HashMap<String, Object>();
publisher = new ExtendedEmailPublisher();
publisher.defaultContent = "For only 10 easy payment of $69.99 , AWESOME-O 4000 can be yours!";
publisher.defaultSubject = "How would you like your very own AWESOME-O 4000?";
publisher.recipientList = "[email protected]";
Field f = ExtendedEmailPublisherDescriptor.class.getDeclaredField( "defaultBody" );
f.setAccessible( true );
f.set( ExtendedEmailPublisher.DESCRIPTOR, "Give me $4000 and I'll mail you a check for $40,000!" );
f = ExtendedEmailPublisherDescriptor.class.getDeclaredField( "defaultSubject" );
f.setAccessible( true );
f.set( ExtendedEmailPublisher.DESCRIPTOR, "Nigerian needs your help!" );
f = ExtendedEmailPublisherDescriptor.class.getDeclaredField( "recipientList" );
f.setAccessible( true );
f.set( ExtendedEmailPublisher.DESCRIPTOR, "[email protected]" );
f = ExtendedEmailPublisherDescriptor.class.getDeclaredField( "hudsonUrl" );;;;
f.setAccessible( true );
f.set( ExtendedEmailPublisher.DESCRIPTOR, "http://localhost/" );
}
public void testShouldFindScriptOnClassPath()
throws Exception
{
args.put(ScriptContent.SCRIPT_NAME_ARG, "empty-script-on-classpath.groovy");
assertEquals("HELLO WORLD!", scriptContent.getContent(mock( AbstractBuild.class ), publisher, null, args));
}
public void testShouldFindTemplateOnClassPath()
throws Exception
{
args.put(ScriptContent.SCRIPT_TEMPLATE_ARG, "empty-groovy-template-on-classpath.template");
// the template adds a newline
assertEquals("HELLO WORLD!\n", scriptContent.getContent(mock(AbstractBuild.class), publisher, null, args));
}
public void testWhenScriptNotFoundThrowFileNotFoundException()
throws Exception
{
args.put(ScriptContent.SCRIPT_NAME_ARG, "script-does-not-exist");
assertEquals("Script [script-does-not-exist] or template [groovy-html.template] was not found in $JENKINS_HOME/email-templates.",
scriptContent.getContent(mock(AbstractBuild.class), publisher, null, args));
}
public void testWhenTemplateNotFoundThrowFileNotFoundException()
throws Exception
{
args.put(ScriptContent.SCRIPT_TEMPLATE_ARG, "template-does-not-exist");
assertEquals("Script [email-ext.groovy] or template [template-does-not-exist] was not found in $JENKINS_HOME/email-templates.",
scriptContent.getContent(mock(AbstractBuild.class), publisher, null, args));
}
/**
* this is for groovy template testing
* @throws Exception
*/
public void testWithGroovyTemplate() throws Exception {
args.put(ScriptContent.SCRIPT_TEMPLATE_ARG, "groovy-sample.template");
args.put(ScriptContent.SCRIPT_INIT_ARG, false);
// mock the build
AbstractBuild build = mock(AbstractBuild.class);
when(build.getResult()).thenReturn(Result.SUCCESS);
when(build.getUrl()).thenReturn("email-test/34");
// mock changeSet
mockChangeSet(build);
// generate result from groovy template
String content = scriptContent.getContent(build, publisher, null, args);
// read expected file in resource to easy compare
String expectedFile = "hudson/plugins/emailext/templates/" + "groovy-sample.result";
InputStream in = getClass().getClassLoader().getResourceAsStream(expectedFile);
String expected = new Scanner(in).useDelimiter("\\Z").next();
// remove end space before compare
assertEquals(expected.trim(), content.trim());
}
private void mockChangeSet(final AbstractBuild build) {
Mockito.when(build.getChangeSet()).thenReturn(new ChangeLogSet(build) {
@Override
public boolean isEmptySet() {
return false;
}
public Iterator iterator() {
return Arrays.asList(new Entry() {
@Override
public String getMsg() {
return "COMMIT MESSAGE";
}
@Override
public User getAuthor() {
User user = mock(User.class);
when(user.getDisplayName()).thenReturn("Kohsuke Kawaguchi");
return user;
}
@Override
public Collection<String> getAffectedPaths() {
return Arrays.asList("path1", "path2");
}
@Override
public String getMsgAnnotated() {
return getMsg();
}
@Override
public Collection<? extends AffectedFile> getAffectedFiles() {
return Arrays.asList(
new AffectedFile() {
public String getPath() {
return "path1";
}
public EditType getEditType() {
return EditType.EDIT;
}
},
new AffectedFile() {
public String getPath() {
return "path2";
}
public EditType getEditType() {
return EditType.ADD;
}
});
}
}).iterator();
}
});
}
}
| Fix test for windows
| src/test/java/hudson/plugins/emailext/plugins/content/ScriptContentTest.java | Fix test for windows |
|
Java | agpl-3.0 | 05fdeb62fdc0e153e74d9ff78f23b5f8bf0d9da2 | 0 | qcri-social/AIDR,qcri-social/AIDR,qcri-social/Crisis-Computing,qcri-social/AIDR,qcri-social/AIDR,qcri-social/Crisis-Computing,qcri-social/Crisis-Computing,qcri-social/Crisis-Computing | package qa.qcri.aidr.trainer.api.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
* User: jilucas
* Date: 9/20/13
* Time: 2:35 PM
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(catalog = "aidr_predict",name = "account")
@JsonIgnoreProperties(ignoreUnknown=true)
public class Users implements Serializable {
private static final long serialVersionUID = -5527566248002296042L;
public Long getUserID() {
return userID;
}
public void setUserID(Long userID) {
this.userID = userID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Id
@Column(name = "id")
private Long userID;
@Column (name = "user_name", nullable = false)
private String name;
}
| aidr-trainer-api/src/main/java/qa/qcri/aidr/trainer/api/entity/Users.java | package qa.qcri.aidr.trainer.api.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
* User: jilucas
* Date: 9/20/13
* Time: 2:35 PM
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(catalog = "aidr_predict",name = "account")
@JsonIgnoreProperties(ignoreUnknown=true)
public class Users implements Serializable {
private static final long serialVersionUID = -5527566248002296042L;
public Long getUserID() {
return userID;
}
public void setUserID(Long userID) {
this.userID = userID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Id
@Column(name = "id")
private Long userID;
@Column (name = "name", nullable = false)
private String name;
}
| Change fieldName for user in AIDRTrainerAPI
| aidr-trainer-api/src/main/java/qa/qcri/aidr/trainer/api/entity/Users.java | Change fieldName for user in AIDRTrainerAPI |
|
Java | agpl-3.0 | a3f8cf9a43e0d6128d9b2ddbf313356f96fc3a12 | 0 | PeterWithers/temp-to-delete1,PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver,KinshipSoftware/KinOathKinshipArchiver | package nl.mpi.kinnate.gedcomimport;
import java.util.ArrayList;
/**
* Document : ImportLineStructure
* Created on : Jul 30, 2012, 9:23:36 AM
* Author : Peter Withers
*/
public abstract class ImportLineStructure {
int gedcomLevel = 0;
String currentID = null;
String entityType = null;
boolean isFileHeader = false;
boolean incompleteLine = false;
private int currentFieldIndex = 0;
protected class FieldEntry {
protected String lineContents = null;
protected String currentName = null;
protected FieldEntry(String currentName, String lineContents) throws ImportException {
if (currentName == null) {
throw new ImportException("Cannot have null names to a field.");
}
this.currentName = currentName.trim();
this.lineContents = lineContents.trim();
}
}
ArrayList<FieldEntry> fieldEntryList = new ArrayList<FieldEntry>();
public ImportLineStructure(String lineString, ArrayList<String> gedcomLevelStrings) {
}
protected void addFieldEntry(String currentName, String lineContents) throws ImportException {
fieldEntryList.add(new FieldEntry(currentName, lineContents));
}
private FieldEntry getFirst() {
currentFieldIndex = 0;
return fieldEntryList.get(currentFieldIndex);
}
protected FieldEntry getCurrent() {
return fieldEntryList.get(currentFieldIndex);
}
private FieldEntry getNext() {
currentFieldIndex++;
return fieldEntryList.get(currentFieldIndex);
}
protected boolean hasCurrent() {
return currentFieldIndex < fieldEntryList.size();
}
public String getCurrentID() throws ImportException {
if (currentID == null) {
// new Exception().printStackTrace();
throw new ImportException("CurrentID has not been set");
}
return currentID;
}
public String getCurrentName() throws ImportException {
if (getCurrent().currentName == null) {
// new Exception().printStackTrace();
throw new ImportException("CurrentName has not been set");
}
return getCurrent().currentName;
}
public int getGedcomLevel() {
return gedcomLevel;
}
public boolean hasLineContents() {
return hasCurrent() && getCurrent().lineContents != null;
}
public String getLineContents() throws ImportException {
if (!hasCurrent() || getCurrent().lineContents == null) {
// new Exception().printStackTrace();
throw new ImportException("LineContents has not been set");
}
return getCurrent().lineContents;
}
public String getEntityType() {
return entityType;
}
public boolean isFileHeader() {
return isFileHeader;
}
public boolean isContinueLine() {
return false;
}
public boolean isContinueLineBreak() {
return false;
}
public boolean isEndOfFileMarker() {
return false;
}
public boolean isIncompleteLine() {
return incompleteLine;
}
abstract boolean isRelation();
}
| desktop/src/main/java/nl/mpi/kinnate/gedcomimport/ImportLineStructure.java | package nl.mpi.kinnate.gedcomimport;
import java.util.ArrayList;
/**
* Document : ImportLineStructure
* Created on : Jul 30, 2012, 9:23:36 AM
* Author : Peter Withers
*/
public abstract class ImportLineStructure {
int gedcomLevel = 0;
String currentID = null;
String entityType = null;
boolean isFileHeader = false;
boolean incompleteLine = false;
private int currentFieldIndex = 0;
protected class FieldEntry {
protected String lineContents = null;
protected String currentName = null;
protected FieldEntry(String currentName, String lineContents) throws ImportException {
if (currentName == null) {
throw new ImportException("Cannot have null names to a field.");
}
this.currentName = currentName;
this.lineContents = lineContents;
}
}
ArrayList<FieldEntry> fieldEntryList = new ArrayList<FieldEntry>();
public ImportLineStructure(String lineString, ArrayList<String> gedcomLevelStrings) {
}
protected void addFieldEntry(String currentName, String lineContents) throws ImportException {
fieldEntryList.add(new FieldEntry(currentName, lineContents));
}
private FieldEntry getFirst() {
currentFieldIndex = 0;
return fieldEntryList.get(currentFieldIndex);
}
protected FieldEntry getCurrent() {
return fieldEntryList.get(currentFieldIndex);
}
private FieldEntry getNext() {
currentFieldIndex++;
return fieldEntryList.get(currentFieldIndex);
}
protected boolean hasCurrent() {
return currentFieldIndex < fieldEntryList.size();
}
public String getCurrentID() throws ImportException {
if (currentID == null) {
// new Exception().printStackTrace();
throw new ImportException("CurrentID has not been set");
}
return currentID;
}
public String getCurrentName() throws ImportException {
if (getCurrent().currentName == null) {
// new Exception().printStackTrace();
throw new ImportException("CurrentName has not been set");
}
return getCurrent().currentName;
}
public int getGedcomLevel() {
return gedcomLevel;
}
public boolean hasLineContents() {
return hasCurrent() && getCurrent().lineContents != null;
}
public String getLineContents() throws ImportException {
if (!hasCurrent() || getCurrent().lineContents == null) {
// new Exception().printStackTrace();
throw new ImportException("LineContents has not been set");
}
return getCurrent().lineContents;
}
public String getEntityType() {
return entityType;
}
public boolean isFileHeader() {
return isFileHeader;
}
public boolean isContinueLine() {
return false;
}
public boolean isContinueLineBreak() {
return false;
}
public boolean isEndOfFileMarker() {
return false;
}
public boolean isIncompleteLine() {
return incompleteLine;
}
abstract boolean isRelation();
}
| Started to add an importer for TIP format by making the gedcom importer more generic.
refs #2193
| desktop/src/main/java/nl/mpi/kinnate/gedcomimport/ImportLineStructure.java | Started to add an importer for TIP format by making the gedcom importer more generic. refs #2193 |
|
Java | lgpl-2.1 | 3c413b9f3dd392f2e54f1b2ce2abb10b55252fd5 | 0 | threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya | //
// $Id: DObject.java,v 1.23 2001/08/15 18:38:54 mdb Exp $
package com.threerings.cocktail.cher.dobj;
import java.lang.reflect.Field;
import java.util.ArrayList;
import com.samskivert.util.ListUtil;
import com.threerings.cocktail.cher.Log;
/**
* The distributed object forms the foundation of the cocktail system. All
* information shared among users of the system is done via distributed
* objects. A distributed object has a set of subscribers. These
* subscribers have access to the object or a proxy of the object and
* therefore have access to the data stored in the object's members at all
* times.
*
* <p> When there is any change to that data, initiated by one of the
* subscribers, an event is generated which is dispatched to all
* subscribers of the object, notifying them of that change and affecting
* that change to the copy of the object maintained at each client. In
* this way, both a respository of shared information and a mechanism for
* asynchronous notification are made available as a fundamental
* application building blocks.
*
* <p> To define what information is shared, an application creates a
* distributed object declaration which is much like a class declaration
* except that it is transformed into a proper derived class of
* <code>DObject</code> by a script. A declaration looks something like
* this:
*
* <pre>
* public dclass RoomObject
* {
* public String description;
* public int[] occupants;
* }
* </pre>
*
* which is converted into an actual Java class that looks like this:
*
* <pre>
* public class RoomObject extends DObject
* {
* public String getDescription ()
* {
* // ...
* }
*
* public void setDescription (String description)
* {
* // ...
* }
*
* public int[] getOccupants ()
* {
* // ...
* }
*
* public void setOccupants (int[] occupants)
* {
* // ...
* }
*
* public void setOccupantsAt (int index, int value)
* {
* // ...
* }
* }
* </pre>
*
* These method calls on the actual distributed object will result in the
* proper attribute change events being generated and dispatched.
*
* <p> Note that distributed object fields can only be of a limited set of
* supported types. These types are:
*
* <code><pre>
* byte, short, int, long, float, double
* Byte, Short, Integer, Long, Float, Double, String
* byte[], short[], int[], long[], float[], double[], String[]
* </pre></code>
*/
public class DObject
{
/**
* Returns the object id of this object. All objects in the system
* have a unique object id.
*/
public int getOid ()
{
return _oid;
}
/**
* Don't call this function! Go through the distributed object manager
* instead to ensure that everything is done on the proper thread.
* This function can only safely be called directly when you know you
* are operating on the omgr thread (you are in the middle of a call
* to <code>objectAvailable</code> or <code>handleEvent</code>).
*
* @see DObjectManager#subscribeToObject
*/
public void addSubscriber (Subscriber sub)
{
// only add the subscriber if they're not already there
Object[] subs = ListUtil.testAndAdd(_subs, sub);
if (subs != null) {
_subs = subs;
_scount++;
}
}
/**
* Don't call this function! Go through the distributed object manager
* instead to ensure that everything is done on the proper thread.
* This function can only safely be called directly when you know you
* are operating on the omgr thread (you are in the middle of a call
* to <code>objectAvailable</code> or <code>handleEvent</code>).
*
* @see DObjectManager#unsubscribeFromObject
*/
public void removeSubscriber (Subscriber sub)
{
if (ListUtil.clear(_subs, sub) != null) {
// if we removed something, check to see if we just removed
// the last subscriber from our list; we also want to be sure
// that we're still active otherwise there's no need to notify
// our objmgr because we don't have one
if (--_scount == 0 && _mgr != null) {
_mgr.removedLastSubscriber(this);
}
}
}
/**
* At times, an entity on the server may need to ensure that events it
* has queued up have made it through the event queue and are applied
* to their respective objects before a service may safely be
* undertaken again. To make this possible, it can acquire a lock on a
* distributed object, generate the events in question and then
* release the lock (via a call to <code>releaseLock</code>) which
* will queue up a final event, the processing of which will release
* the lock. Thus the lock will not be released until all of the
* previously generated events have been processed. If the service is
* invoked again before that lock is released, the associated call to
* <code>acquireLock</code> will fail and the code can respond
* accordingly. An object may have any number of outstanding locks as
* long as they each have a unique name.
*
* @param name the name of the lock to acquire.
*
* @return true if the lock was acquired, false if the lock was not
* acquired because it has not yet been released from a previous
* acquisition.
*
* @see #releaseLock
*/
public boolean acquireLock (String name)
{
// check for the existence of the lock in the list and add it if
// it's not already there
Object[] list = ListUtil.testAndAdd(_locks, name);
if (list == null) {
// a null list means the object was already in the list
return false;
} else {
// a non-null list means the object was added
_locks = list;
return true;
}
}
/**
* Queues up an event that when processed will release the lock of the
* specified name.
*
* @see #acquireLock
*/
public void releaseLock (String name)
{
// queue up a release lock event
ReleaseLockEvent event = new ReleaseLockEvent(_oid, name);
_mgr.postEvent(event);
}
/**
* Don't call this function! It is called by a remove lock event when
* that event is processed and shouldn't be called at any other time.
* If you mean to release a lock that was acquired with
* <code>acquireLock</code> you should be using
* <code>releaseLock</code>.
*
* @see #acquireLock
* @see #releaseLock
*/
protected void clearLock (String name)
{
// clear the lock from the list
if (ListUtil.clearEqual(_locks, name) == null) {
// complain if we didn't find the lock
Log.info("Unable to clear non-existent lock [lock=" + name +
", dobj=" + this + "].");
}
}
/**
* Requests that this distributed object be destroyed. It does so by
* queueing up an object destroyed event which the server will
* validate and process.
*/
public void destroy ()
{
_mgr.postEvent(new ObjectDestroyedEvent(_oid));
}
/**
* Checks to ensure that the specified subscriber has access to this
* object. This will be called before satisfying a subscription
* request. By default objects are accessible to all subscribers, but
* certain objects may wish to implement more fine grained access
* control.
*
* @param sub the subscriber that will subscribe to this object.
*
* @return true if the subscriber has access to the object, false if
* they do not.
*/
public boolean checkPermissions (Subscriber sub)
{
return true;
}
/**
* Checks to ensure that this event which is about to be processed,
* has the appropriate permissions. By default objects accept all
* manner of events, but certain objects may wish to implement more
* fine grained access control.
*
* @param event the event that will be dispatched, object permitting.
*
* @return true if the event is valid and should be dispatched, false
* if the event fails the permissions check and should be aborted.
*/
public boolean checkPermissions (DEvent event)
{
return true;
}
/**
* Called by the distributed object manager after it has applied an
* event to this object. This dispatches an event notification to all
* of the subscribers of this object.
*
* @param event the event that was just applied.
*/
public void notifySubscribers (DEvent event)
{
// Log.info("Dispatching event to " + _scount +
// " subscribers: " + event);
for (int i = 0; i < _scount; i++) {
Subscriber sub = (Subscriber)_subs[i];
// notify the subscriber
if (!sub.handleEvent(event, this)) {
// if they return false, we need to remove them from the
// subscriber list
_subs[i--] = null;
// if we just removed our last subscriber, we need to let
// the omgr know about it
if (--_scount == 0) {
_mgr.removedLastSubscriber(this);
}
}
}
}
/**
* Sets the named attribute to the specified value. This is only used
* by the internals of the event dispatch mechanism and should not be
* called directly by users. Use the generated attribute setter
* methods instead.
*/
public void setAttribute (String name, Object value)
throws ObjectAccessException
{
try {
getClass().getField(name).set(this, value);
} catch (Exception e) {
String errmsg = "Attribute setting failure [name=" + name +
", value=" + value + ", error=" + e + "].";
throw new ObjectAccessException(errmsg);
}
}
/**
* Looks up the named attribute and returns a reference to it. This
* should only be used by the internals of the event dispatch
* mechanism and should not be called directly by users. Use the
* generated attribute getter methods instead.
*/
public Object getAttribute (String name)
throws ObjectAccessException
{
try {
return getClass().getField(name).get(this);
} catch (Exception e) {
String errmsg = "Attribute getting failure [name=" + name +
", error=" + e + "].";
throw new ObjectAccessException(errmsg);
}
}
/**
* Returns true if this object is active and registered with the
* distributed object system. If an object is created via
* <code>DObjectManager.createObject</code> it will be active until
* such time as it is destroyed.
*/
public boolean isActive ()
{
return _mgr != null;
}
/**
* Don't call this function! It initializes this distributed object
* with the supplied distributed object manager. This is called by the
* distributed object manager when an object is created and registered
* with the system.
*
* @see DObjectManager#createObject
*/
public void setManager (DObjectManager mgr)
{
_mgr = mgr;
}
/**
* Don't call this function. It is called by the distributed object
* manager when an object is created and registered with the system.
*
* @see DObjectManager#createObject
*/
public void setOid (int oid)
{
_oid = oid;
}
/**
* Generates a string representation of this object by calling the
* overridable {@link #toString(StringBuffer)} which builds up the
* string in a manner friendly to derived classes.
*/
public String toString ()
{
StringBuffer buf = new StringBuffer();
buf.append("[");
toString(buf);
buf.append("]");
return buf.toString();
}
/**
* An extensible mechanism for generating a string representation of
* this object. Derived classes should override this method, calling
* super and then appending their own data to the supplied string
* buffer. The regular {@link #toString} function will call this
* derived function to generate its string.
*/
protected void toString (StringBuffer buf)
{
buf.append("oid=").append(_oid);
}
/**
* Called by derived instances when an attribute setter method was
* called.
*/
protected void requestAttributeChange (String name, Object value)
{
// generate an attribute changed event
DEvent event = new AttributeChangedEvent(_oid, name, value);
// and dispatch it to our dobjmgr
_mgr.postEvent(event);
}
/**
* Calls by derived instances when an oid adder method was called.
*/
protected void requestOidAdd (String name, int oid)
{
// generate an object added event
DEvent event = new ObjectAddedEvent(_oid, name, oid);
// and dispatch it to our dobjmgr
_mgr.postEvent(event);
}
/**
* Calls by derived instances when an oid remover method was called.
*/
protected void requestOidRemove (String name, int oid)
{
// generate an object removed event
DEvent event = new ObjectRemovedEvent(_oid, name, oid);
// and dispatch it to our dobjmgr
_mgr.postEvent(event);
}
/** Our object id. */
protected int _oid;
/** A reference to our object manager. */
protected DObjectManager _mgr;
/** A list of outstanding locks. */
protected Object[] _locks;
/** Our subscribers list. */
protected Object[] _subs;
/** Our subscriber count. */
protected int _scount;
}
| src/java/com/threerings/presents/dobj/DObject.java | //
// $Id: DObject.java,v 1.22 2001/08/11 00:11:53 mdb Exp $
package com.threerings.cocktail.cher.dobj;
import java.lang.reflect.Field;
import java.util.ArrayList;
import com.threerings.cocktail.cher.Log;
/**
* The distributed object forms the foundation of the cocktail system. All
* information shared among users of the system is done via distributed
* objects. A distributed object has a set of subscribers. These
* subscribers have access to the object or a proxy of the object and
* therefore have access to the data stored in the object's members at all
* times.
*
* <p> When there is any change to that data, initiated by one of the
* subscribers, an event is generated which is dispatched to all
* subscribers of the object, notifying them of that change and affecting
* that change to the copy of the object maintained at each client. In
* this way, both a respository of shared information and a mechanism for
* asynchronous notification are made available as a fundamental
* application building blocks.
*
* <p> To define what information is shared, an application creates a
* distributed object declaration which is much like a class declaration
* except that it is transformed into a proper derived class of
* <code>DObject</code> by a script. A declaration looks something like
* this:
*
* <pre>
* public dclass RoomObject
* {
* public String description;
* public int[] occupants;
* }
* </pre>
*
* which is converted into an actual Java class that looks like this:
*
* <pre>
* public class RoomObject extends DObject
* {
* public String getDescription ()
* {
* // ...
* }
*
* public void setDescription (String description)
* {
* // ...
* }
*
* public int[] getOccupants ()
* {
* // ...
* }
*
* public void setOccupants (int[] occupants)
* {
* // ...
* }
*
* public void setOccupantsAt (int index, int value)
* {
* // ...
* }
* }
* </pre>
*
* These method calls on the actual distributed object will result in the
* proper attribute change events being generated and dispatched.
*
* <p> Note that distributed object fields can only be of a limited set of
* supported types. These types are:
*
* <code><pre>
* byte, short, int, long, float, double
* Byte, Short, Integer, Long, Float, Double, String
* byte[], short[], int[], long[], float[], double[], String[]
* </pre></code>
*/
public class DObject
{
/**
* Returns the object id of this object. All objects in the system
* have a unique object id.
*/
public int getOid ()
{
return _oid;
}
/**
* Don't call this function! Go through the distributed object manager
* instead to ensure that everything is done on the proper thread.
* This function can only safely be called directly when you know you
* are operating on the omgr thread (you are in the middle of a call
* to <code>objectAvailable</code> or <code>handleEvent</code>).
*
* @see DObjectManager#subscribeToObject
*/
public void addSubscriber (Subscriber sub)
{
if (!_subscribers.contains(sub)) {
_subscribers.add(sub);
}
}
/**
* Don't call this function! Go through the distributed object manager
* instead to ensure that everything is done on the proper thread.
* This function can only safely be called directly when you know you
* are operating on the omgr thread (you are in the middle of a call
* to <code>objectAvailable</code> or <code>handleEvent</code>).
*
* @see DObjectManager#unsubscribeFromObject
*/
public void removeSubscriber (Subscriber sub)
{
if (_subscribers.remove(sub)) {
// if we removed something, check to see if we just removed
// the last subscriber from our list; we also want to be sure
// that we're still active otherwise there's no need to notify
// our objmgr because we don't have one
if (_subscribers.size() == 0 && _mgr != null) {
_mgr.removedLastSubscriber(this);
}
}
}
/**
* At times, an entity on the server may need to ensure that events it
* has queued up have made it through the event queue and are applied
* to their respective objects before a service may safely be
* undertaken again. To make this possible, it can acquire a lock on a
* distributed object, generate the events in question and then
* release the lock (via a call to <code>releaseLock</code>) which
* will queue up a final event, the processing of which will release
* the lock. Thus the lock will not be released until all of the
* previously generated events have been processed. If the service is
* invoked again before that lock is released, the associated call to
* <code>acquireLock</code> will fail and the code can respond
* accordingly. An object may have any number of outstanding locks as
* long as they each have a unique name.
*
* @param name the name of the lock to acquire.
*
* @return true if the lock was acquired, false if the lock was not
* acquired because it has not yet been released from a previous
* acquisition.
*
* @see #releaseLock
*/
public boolean acquireLock (String name)
{
// create our lock array if we haven't already. we do all this
// jockeying rather than just use something like an ArrayList to
// be memory efficient because there may be very many distributed
// objects
if (_locks == null) {
_locks = new String[2];
}
// scan the lock array to see if this lock is already acquired
int slot = -1;
for (int i = 0; i < _locks.length; i++) {
if (_locks[i] == null && slot == -1) {
// keep track of this for later
slot = i;
} else if (name.equals(_locks[i])) {
return false;
}
}
// if we didnt' find a blank slot in our previous scan, we'll have
// to expand the locks array
if (slot == -1) {
String[] locks = new String[_locks.length*2];
System.arraycopy(_locks, 0, locks, 0, _locks.length);
slot = _locks.length;
}
// place our lock in the array and let the user know that they
// acquired the lock
_locks[slot] = name;
return true;
}
/**
* Queues up an event that when processed will release the lock of the
* specified name.
*
* @see #acquireLock
*/
public void releaseLock (String name)
{
// queue up a release lock event
ReleaseLockEvent event = new ReleaseLockEvent(_oid, name);
_mgr.postEvent(event);
}
/**
* Don't call this function! It is called by a remove lock event when
* that event is processed and shouldn't be called at any other time.
* If you mean to release a lock that was acquired with
* <code>acquireLock</code> you should be using
* <code>releaseLock</code>.
*
* @see #acquireLock
* @see #releaseLock
*/
protected void clearLock (String name)
{
// track the lock index for reporting purposes
int lockidx = -1;
// scan through and clear the lock in question
if (_locks != null) {
for (int i = 0; i < _locks.length; i++) {
if (name.equals(_locks[i])) {
_locks[i] = null;
lockidx = i;
break;
}
}
}
// complain if we didn't find the lock
if (lockidx == -1) {
Log.info("Unable to clear non-existent lock [lock=" + name +
", dobj=" + this + "].");
}
}
/**
* Requests that this distributed object be destroyed. It does so by
* queueing up an object destroyed event which the server will
* validate and process.
*/
public void destroy ()
{
_mgr.postEvent(new ObjectDestroyedEvent(_oid));
}
/**
* Checks to ensure that the specified subscriber has access to this
* object. This will be called before satisfying a subscription
* request. By default objects are accessible to all subscribers, but
* certain objects may wish to implement more fine grained access
* control.
*
* @param sub the subscriber that will subscribe to this object.
*
* @return true if the subscriber has access to the object, false if
* they do not.
*/
public boolean checkPermissions (Subscriber sub)
{
return true;
}
/**
* Checks to ensure that this event which is about to be processed,
* has the appropriate permissions. By default objects accept all
* manner of events, but certain objects may wish to implement more
* fine grained access control.
*
* @param event the event that will be dispatched, object permitting.
*
* @return true if the event is valid and should be dispatched, false
* if the event fails the permissions check and should be aborted.
*/
public boolean checkPermissions (DEvent event)
{
return true;
}
/**
* Called by the distributed object manager after it has applied an
* event to this object. This dispatches an event notification to all
* of the subscribers of this object.
*
* @param event the event that was just applied.
*/
public void notifySubscribers (DEvent event)
{
// Log.info("Dispatching event to " + _subscribers.size() +
// " subscribers: " + event);
for (int i = 0; i < _subscribers.size(); i++) {
Subscriber sub = (Subscriber)_subscribers.get(i);
// notify the subscriber
if (!sub.handleEvent(event, this)) {
// if they return false, we need to remove them from the
// subscriber list
_subscribers.remove(i--);
// if we just removed our last subscriber, we need to let
// the omgr know about it
if (_subscribers.size() == 0) {
_mgr.removedLastSubscriber(this);
}
}
}
}
/**
* Sets the named attribute to the specified value. This is only used
* by the internals of the event dispatch mechanism and should not be
* called directly by users. Use the generated attribute setter
* methods instead.
*/
public void setAttribute (String name, Object value)
throws ObjectAccessException
{
try {
getClass().getField(name).set(this, value);
} catch (Exception e) {
String errmsg = "Attribute setting failure [name=" + name +
", value=" + value + ", error=" + e + "].";
throw new ObjectAccessException(errmsg);
}
}
/**
* Looks up the named attribute and returns a reference to it. This
* should only be used by the internals of the event dispatch
* mechanism and should not be called directly by users. Use the
* generated attribute getter methods instead.
*/
public Object getAttribute (String name)
throws ObjectAccessException
{
try {
return getClass().getField(name).get(this);
} catch (Exception e) {
String errmsg = "Attribute getting failure [name=" + name +
", error=" + e + "].";
throw new ObjectAccessException(errmsg);
}
}
/**
* Returns true if this object is active and registered with the
* distributed object system. If an object is created via
* <code>DObjectManager.createObject</code> it will be active until
* such time as it is destroyed.
*/
public boolean isActive ()
{
return _mgr != null;
}
/**
* Don't call this function! It initializes this distributed object
* with the supplied distributed object manager. This is called by the
* distributed object manager when an object is created and registered
* with the system.
*
* @see DObjectManager#createObject
*/
public void setManager (DObjectManager mgr)
{
_mgr = mgr;
}
/**
* Don't call this function. It is called by the distributed object
* manager when an object is created and registered with the system.
*
* @see DObjectManager#createObject
*/
public void setOid (int oid)
{
_oid = oid;
}
public String toString ()
{
StringBuffer buf = new StringBuffer();
buf.append("[");
toString(buf);
buf.append("]");
return buf.toString();
}
protected void toString (StringBuffer buf)
{
buf.append("oid=").append(_oid);
}
/**
* Called by derived instances when an attribute setter method was
* called.
*/
protected void requestAttributeChange (String name, Object value)
{
// generate an attribute changed event
DEvent event = new AttributeChangedEvent(_oid, name, value);
// and dispatch it to our dobjmgr
_mgr.postEvent(event);
}
/**
* Calls by derived instances when an oid adder method was called.
*/
protected void requestOidAdd (String name, int oid)
{
// generate an object added event
DEvent event = new ObjectAddedEvent(_oid, name, oid);
// and dispatch it to our dobjmgr
_mgr.postEvent(event);
}
/**
* Calls by derived instances when an oid remover method was called.
*/
protected void requestOidRemove (String name, int oid)
{
// generate an object removed event
DEvent event = new ObjectRemovedEvent(_oid, name, oid);
// and dispatch it to our dobjmgr
_mgr.postEvent(event);
}
protected int _oid;
protected DObjectManager _mgr;
protected ArrayList _subscribers = new ArrayList();
protected String[] _locks;
}
| Added documentation; modified internal array management to use ListUtil.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@258 542714f4-19e9-0310-aa3c-eee0fc999fb1
| src/java/com/threerings/presents/dobj/DObject.java | Added documentation; modified internal array management to use ListUtil. |
|
Java | apache-2.0 | 45f304fcb79ccb81ae514caeb64ec17ad1296e05 | 0 | opentracing-contrib/java-jdbi,opentracing-contrib/java-jdbi | package io.opentracing.contrib.jdbi;
import io.opentracing.Span;
import io.opentracing.Tracer;
import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.TimingCollector;
import java.util.Collections;
import java.util.HashMap;
/**
* OpenTracingCollector is a JDBI TimingCollector that creates OpenTracing Spans for each JDBI SQLStatement.
*
* <p>Example usage:
* <pre>{@code
* io.opentracing.Tracer tracer = ...;
* DBI dbi = ...;
*
* // One time only: bind OpenTracing to the DBI instance as a TimingCollector.
* dbi.setTimingCollector(new OpenTracingCollector(tracer));
*
* // Elsewhere, anywhere a `Handle` is available:
* Handle handle = ...;
* Span parentSpan = ...; // optional
*
* // Create statements as usual with your `handle` instance.
* Query<Map<String, Object>> statement = handle.createQuery("SELECT COUNT(*) FROM accounts");
*
* // If a parent Span is available, establish the relationship via setParent.
* OpenTracingCollector.setParent(statement, parent);
*
* // Use JDBI as per usual, and Spans will be created for every SQLStatement automatically.
* List<Map<String, Object>> results = statement.list();
* }</pre>
*/
@SuppressWarnings("WeakerAccess")
public class OpenTracingCollector implements TimingCollector {
public final static String PARENT_SPAN_ATTRIBUTE_KEY = "io.opentracing.parent";
private final Tracer tracer;
private final SpanDecorator spanDecorator;
private final ActiveSpanSource activeSpanSource;
private final TimingCollector next;
public OpenTracingCollector(Tracer tracer) {
this(tracer, SpanDecorator.DEFAULT);
}
/**
* @param tracer the OpenTracing tracer to trace JDBI calls.
* @param next a timing collector to "chain" to. When collect is called on
* this TimingCollector, collect will also be called on 'next'
*/
@SuppressWarnings("unused")
public OpenTracingCollector(Tracer tracer, TimingCollector next) {
this(tracer, SpanDecorator.DEFAULT, null, null);
}
public OpenTracingCollector(Tracer tracer, SpanDecorator spanDecorator) {
this(tracer, spanDecorator, null);
}
public OpenTracingCollector(Tracer tracer, ActiveSpanSource spanSource) {
this(tracer, SpanDecorator.DEFAULT, spanSource);
}
public OpenTracingCollector(Tracer tracer, SpanDecorator spanDecorator, ActiveSpanSource activeSpanSource) {
this(tracer, spanDecorator, activeSpanSource, null);
}
/**
* @param tracer the OpenTracing tracer to trace JDBI calls.
* @param spanDecorator the SpanDecorator used to name and decorate spans.
* @see SpanDecorator
* @param activeSpanSource a source that can provide the currently active
* span when creating a child span.
* @see ActiveSpanSource
* @param next a timing collector to "chain" to. When collect is called on
* this TimingCollector, collect will also be called on 'next'
*/
public OpenTracingCollector(Tracer tracer, SpanDecorator spanDecorator, ActiveSpanSource activeSpanSource, TimingCollector next) {
this.tracer = tracer;
this.spanDecorator = spanDecorator;
this.activeSpanSource = activeSpanSource;
this.next = next;
}
public void collect(long elapsedNanos, StatementContext statementContext) {
long nowMicros = System.currentTimeMillis() * 1000;
Tracer.SpanBuilder builder = tracer
.buildSpan(spanDecorator.generateOperationName(statementContext))
.withStartTimestamp(nowMicros - (elapsedNanos / 1000));
Span parent = (Span)statementContext.getAttribute(PARENT_SPAN_ATTRIBUTE_KEY);
if (parent == null && this.activeSpanSource != null) {
parent = this.activeSpanSource.activeSpan(statementContext);
}
if (parent != null) {
builder = builder.asChildOf(parent);
}
Span collectSpan = builder.start();
spanDecorator.decorateSpan(collectSpan, elapsedNanos, statementContext);
try {
HashMap<String, String> values = new HashMap<>();
values.put("event", "SQL query finished");
values.put("db.statement", statementContext.getRawSql());
collectSpan.log(nowMicros, values);
} finally {
collectSpan.finish(nowMicros);
}
if (next != null) {
next.collect(elapsedNanos, statementContext);
}
}
/**
* Establish an explicit parent relationship for the (child) Span associated with a SQLStatement.
*
* @param statement the JDBI SQLStatement which will act as the child of `parent`
* @param parent the parent Span for `statement`
*/
public static void setParent(SQLStatement<?> statement, Span parent) {
statement.getContext().setAttribute(PARENT_SPAN_ATTRIBUTE_KEY, parent);
}
/**
* SpanDecorator allows the OpenTracingCollector user to control the precise naming and decoration of OpenTracing
* Spans emitted by the collector.
*
* @see OpenTracingCollector#OpenTracingCollector(Tracer, SpanDecorator)
*/
public interface SpanDecorator {
SpanDecorator DEFAULT = new SpanDecorator() {
public String generateOperationName(StatementContext ctx) {
return "DBI Statement";
}
@Override
public void decorateSpan(Span jdbiSpan, long elapsedNanos, StatementContext ctx) {
// (by default, do nothing)
}
};
/**
* Transform an DBI StatementContext into an OpenTracing Span operation name.
*
* @param ctx the StatementContext passed to TimingCollector.collect()
* @return an operation name suitable for the associated OpenTracing Span
*/
String generateOperationName(StatementContext ctx);
/**
* Decorate the given span with additional tags or logs. Implementations may or may not need to refer
* to the StatementContext.
*
* @param jdbiSpan the JDBI Span to decorate (before `finish` is called)
* @param elapsedNanos the elapsedNanos passed to TimingCollector.collect()
* @param ctx the StatementContext passed to TimingCollector.collect()
*/
void decorateSpan(Span jdbiSpan, long elapsedNanos, StatementContext ctx);
}
/**
* An abstract API that allows the OpenTracingCollector to customize how parent Spans are discovered.
*
* For instance, if Spans are stored in a thread-local variable, an ActiveSpanSource could access them like so:
* <p>Example usage:
* <pre>{@code
* public class SomeClass {
* // Thread local variable containing each thread's ID
* private static final ThreadLocal<Span> activeSpan =
* new ThreadLocal<Span>() {
* protected Integer initialValue() {
* return null;
* }
* };
* };
*
* ... elsewhere ...
* ActiveSpanSource spanSource = new ActiveSpanSource() {
* public Span activeSpan(StatementContext ctx) {
* // (In this example we ignore `ctx` entirely)
* return activeSpan.get();
* }
* };
* OpenTracingCollector otColl = new OpenTracingCollector(tracer, spanSource);
* ...
* }</pre>
*/
public interface ActiveSpanSource {
/**
* Get the active Span (to use as a parent for any DBI Spans). Implementations may or may not need to refer
* to the StatementContext.
*
* @param ctx the StatementContext that needs to be collected and traced
* @return the currently active Span (for this thread, etc), or null if no such Span could be found.
*/
Span activeSpan(StatementContext ctx);
}
}
| src/main/java/io/opentracing/contrib/jdbi/OpenTracingCollector.java | package io.opentracing.contrib.jdbi;
import io.opentracing.Span;
import io.opentracing.Tracer;
import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.TimingCollector;
import java.util.Collections;
import java.util.HashMap;
/**
* OpenTracingCollector is a JDBI TimingCollector that creates OpenTracing Spans for each JDBI SQLStatement.
*
* <p>Example usage:
* <pre>{@code
* io.opentracing.Tracer tracer = ...;
* DBI dbi = ...;
*
* // One time only: bind OpenTracing to the DBI instance as a TimingCollector.
* dbi.setTimingCollector(new OpenTracingCollector(tracer));
*
* // Elsewhere, anywhere a `Handle` is available:
* Handle handle = ...;
* Span parentSpan = ...; // optional
*
* // Create statements as usual with your `handle` instance.
* Query<Map<String, Object>> statement = handle.createQuery("SELECT COUNT(*) FROM accounts");
*
* // If a parent Span is available, establish the relationship via setParent.
* OpenTracingCollector.setParent(statement, parent);
*
* // Use JDBI as per usual, and Spans will be created for every SQLStatement automatically.
* List<Map<String, Object>> results = statement.list();
* }</pre>
*/
@SuppressWarnings("WeakerAccess")
public class OpenTracingCollector implements TimingCollector {
public final static String PARENT_SPAN_ATTRIBUTE_KEY = "io.opentracing.parent";
private final Tracer tracer;
private final SpanDecorator spanDecorator;
private final ActiveSpanSource activeSpanSource;
private final TimingCollector next;
public OpenTracingCollector(Tracer tracer) {
this(tracer, SpanDecorator.DEFAULT);
}
/**
* @param tracer the OpenTracing tracer to trace JDBI calls.
* @param next a timing collector to "chain" to. When collect is called on
* this TimingCollector, collect will also be called on 'next'
*/
@SuppressWarnings("unused")
public OpenTracingCollector(Tracer tracer, TimingCollector next) {
this(tracer, SpanDecorator.DEFAULT, null, null);
}
public OpenTracingCollector(Tracer tracer, SpanDecorator spanDecorator) {
this(tracer, spanDecorator, null);
}
public OpenTracingCollector(Tracer tracer, ActiveSpanSource spanSource) {
this(tracer, SpanDecorator.DEFAULT, spanSource);
}
public OpenTracingCollector(Tracer tracer, SpanDecorator spanDecorator, ActiveSpanSource activeSpanSource) {
this(tracer, spanDecorator, activeSpanSource, null);
}
/**
* @param tracer the OpenTracing tracer to trace JDBI calls.
* @param spanDecorator the SpanDecorator used to name and decorate spans.
* @see SpanDecorator
* @param activeSpanSource a source that can provide the currently active
* span when creating a child span.
* @see ActiveSpanSource
* @param next a timing collector to "chain" to. When collect is called on
* this TimingCollector, collect will also be called on 'next'
*/
public OpenTracingCollector(Tracer tracer, SpanDecorator spanDecorator, ActiveSpanSource activeSpanSource, TimingCollector next) {
this.tracer = tracer;
this.spanDecorator = spanDecorator;
this.activeSpanSource = activeSpanSource;
this.next = next;
}
public void collect(long elapsedNanos, StatementContext statementContext) {
long nowMicros = System.currentTimeMillis() * 1000;
Tracer.SpanBuilder builder = tracer
.buildSpan(spanDecorator.generateOperationName(statementContext))
.withStartTimestamp(nowMicros - (elapsedNanos / 1000));
Span parent = (Span)statementContext.getAttribute(PARENT_SPAN_ATTRIBUTE_KEY);
if (parent == null && this.activeSpanSource != null) {
parent = this.activeSpanSource.activeSpan(statementContext);
}
if (parent != null) {
builder = builder.asChildOf(parent);
}
Span collectSpan = builder.start();
spanDecorator.decorateSpan(collectSpan, elapsedNanos, statementContext);
try {
HashMap<String, String> values = new HashMap<>();
values.put("event", "SQL query finished");
values.put("sql", statementContext.getRawSql());
collectSpan.log(nowMicros, values);
} finally {
collectSpan.finish(nowMicros);
}
if (next != null) {
next.collect(elapsedNanos, statementContext);
}
}
/**
* Establish an explicit parent relationship for the (child) Span associated with a SQLStatement.
*
* @param statement the JDBI SQLStatement which will act as the child of `parent`
* @param parent the parent Span for `statement`
*/
public static void setParent(SQLStatement<?> statement, Span parent) {
statement.getContext().setAttribute(PARENT_SPAN_ATTRIBUTE_KEY, parent);
}
/**
* SpanDecorator allows the OpenTracingCollector user to control the precise naming and decoration of OpenTracing
* Spans emitted by the collector.
*
* @see OpenTracingCollector#OpenTracingCollector(Tracer, SpanDecorator)
*/
public interface SpanDecorator {
SpanDecorator DEFAULT = new SpanDecorator() {
public String generateOperationName(StatementContext ctx) {
return "DBI Statement";
}
@Override
public void decorateSpan(Span jdbiSpan, long elapsedNanos, StatementContext ctx) {
// (by default, do nothing)
}
};
/**
* Transform an DBI StatementContext into an OpenTracing Span operation name.
*
* @param ctx the StatementContext passed to TimingCollector.collect()
* @return an operation name suitable for the associated OpenTracing Span
*/
String generateOperationName(StatementContext ctx);
/**
* Decorate the given span with additional tags or logs. Implementations may or may not need to refer
* to the StatementContext.
*
* @param jdbiSpan the JDBI Span to decorate (before `finish` is called)
* @param elapsedNanos the elapsedNanos passed to TimingCollector.collect()
* @param ctx the StatementContext passed to TimingCollector.collect()
*/
void decorateSpan(Span jdbiSpan, long elapsedNanos, StatementContext ctx);
}
/**
* An abstract API that allows the OpenTracingCollector to customize how parent Spans are discovered.
*
* For instance, if Spans are stored in a thread-local variable, an ActiveSpanSource could access them like so:
* <p>Example usage:
* <pre>{@code
* public class SomeClass {
* // Thread local variable containing each thread's ID
* private static final ThreadLocal<Span> activeSpan =
* new ThreadLocal<Span>() {
* protected Integer initialValue() {
* return null;
* }
* };
* };
*
* ... elsewhere ...
* ActiveSpanSource spanSource = new ActiveSpanSource() {
* public Span activeSpan(StatementContext ctx) {
* // (In this example we ignore `ctx` entirely)
* return activeSpan.get();
* }
* };
* OpenTracingCollector otColl = new OpenTracingCollector(tracer, spanSource);
* ...
* }</pre>
*/
public interface ActiveSpanSource {
/**
* Get the active Span (to use as a parent for any DBI Spans). Implementations may or may not need to refer
* to the StatementContext.
*
* @param ctx the StatementContext that needs to be collected and traced
* @return the currently active Span (for this thread, etc), or null if no such Span could be found.
*/
Span activeSpan(StatementContext ctx);
}
}
| Align field names according to https://github.com/opentracing/specification/blob/master/semantic_conventions.md
| src/main/java/io/opentracing/contrib/jdbi/OpenTracingCollector.java | Align field names according to https://github.com/opentracing/specification/blob/master/semantic_conventions.md |
|
Java | apache-2.0 | 66b24fda075c51d77b5aa581ad339f37371e326b | 0 | killjoy1221/MnM-Utils | package mnm.mods.util;
import net.minecraftforge.fml.common.FMLCommonHandler;
import com.mumfrey.liteloader.core.LiteLoader;
public class TweakTools {
/**
* Returns whether LiteLoader is currently loaded.
*
* @return True if it's loaded
*/
public static boolean isLiteLoaderLoaded() {
boolean loaded = false;
try {
loaded = LiteLoader.getInstance() != null;
} catch (Throwable t) {
}
return loaded;
}
/**
* Returns whether FML is currently loaded.
*
* @return True if it's loaded
*/
public static boolean isFMLLoaded() {
boolean loaded = false;
if (ForgeUtils.FML_INSTALLED) {
loaded = FMLCommonHandler.instance() != null;
}
return loaded;
}
}
| src/main/java/mnm/mods/util/TweakTools.java | package mnm.mods.util;
import java.util.Iterator;
import java.util.List;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
public class TweakTools {
/**
* Returns whether LiteLoader is loaded into LaunchWrapper.
*
* @return True if it's loaded
*/
public static boolean isLiteLoaderLoaded() {
return isTweakLoaded("com.mumfrey.liteloader.launch.LiteLoaderTweaker");
}
/**
* Returns whether FML is loaded into LaunchWrapper.
*
* @return True if it's loaded
*/
public static boolean isFMLLoaded() {
return isTweakLoaded("net.minecraftforge.fml.common.launcher.FMLTweaker");
}
/**
* Gets if a given tweak is loaded into LaunchWrapper.
*
* @param name The fully qualified class name
* @return True if it's loaded
*/
public static boolean isTweakLoaded(String name) {
boolean load = false;
@SuppressWarnings("unchecked")
List<ITweaker> tweakers = (List<ITweaker>) Launch.blackboard.get("Tweaks");
// Iterate through the tweaks and check the class name
Iterator<ITweaker> iter = tweakers.iterator();
while (!load && iter.hasNext()) {
ITweaker tweak = iter.next();
String className = tweak.getClass().getName();
load = className.equals(name);
}
return load;
}
}
| Make the tweak tools actually useful. Fix always returning false because the Tweaks list is empty.
| src/main/java/mnm/mods/util/TweakTools.java | Make the tweak tools actually useful. Fix always returning false because the Tweaks list is empty. |
|
Java | apache-2.0 | d26e1362fc2aa5977fe80b85cc0171de00531839 | 0 | wisdom-framework/wisdom-myth | /*
* #%L
* Wisdom-Framework
* %%
* Copyright (C) 2013 - 2014 Wisdom Framework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.wisdom.myth;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.wisdom.maven.Constants;
import org.wisdom.maven.WatchingException;
import org.wisdom.maven.mojos.AbstractWisdomWatcherMojo;
import org.wisdom.maven.node.NPM;
import org.wisdom.maven.utils.WatcherUtils;
import java.io.File;
import java.util.Collection;
import static org.wisdom.maven.node.NPM.npm;
/**
* A Mojo extending Wisdom to support <a href="http://www.myth.io/">Myth CSS</a>.
* It watches CSS files from 'src/main/resources/assets' and 'src/main/assets' and process them using Myth. If the
* CSS file is already present in the destination directories (and more recent than the original file),
* it processes these one, letting this plugin work seamlessly with the Wisdom CSS features.
* <p/>
* Less files are not processed.
*/
@Mojo(name = "compile-myth", threadSafe = false,
requiresDependencyResolution = ResolutionScope.COMPILE,
requiresProject = true,
defaultPhase = LifecyclePhase.COMPILE)
public class MythMojo extends AbstractWisdomWatcherMojo implements Constants {
private static final String MYTH_NPM_NAME = "myth";
private File internalSources;
private File destinationForInternals;
private File externalSources;
private File destinationForExternals;
@Parameter(defaultValue = "0.3.4")
String version;
private NPM myth;
/**
* Executes the plugin. It compiles all CSS files from the assets directories and process them using Myth.
*
* @throws MojoExecutionException happens when a CSS file cannot be processed correctly
*/
@Override
public void execute() throws MojoExecutionException {
this.internalSources = new File(basedir, MAIN_RESOURCES_DIR);
this.destinationForInternals = new File(buildDirectory, "classes");
this.externalSources = new File(basedir, ASSETS_SRC_DIR);
this.destinationForExternals = new File(getWisdomRootDirectory(), ASSETS_DIR);
myth = npm(this, MYTH_NPM_NAME, version);
try {
if (internalSources.isDirectory()) {
getLog().info("Compiling CSS files with Myth from " + internalSources.getAbsolutePath());
Collection<File> files = FileUtils.listFiles(internalSources, new String[]{"css"}, true);
for (File file : files) {
if (file.isFile()) {
process(file);
}
}
}
if (externalSources.isDirectory()) {
getLog().info("Compiling CSS files with Myth from " + externalSources.getAbsolutePath());
Collection<File> files = FileUtils.listFiles(externalSources, new String[]{"css"}, true);
for (File file : files) {
if (file.isFile()) {
process(file);
}
}
}
} catch (WatchingException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
/**
* Checks whether the given file should be processed or not.
*
* @param file the file
* @return {@literal true} if the file must be handled, {@literal false} otherwise
*/
@Override
public boolean accept(File file) {
return
(WatcherUtils.isInDirectory(file, WatcherUtils.getInternalAssetsSource(basedir))
|| (WatcherUtils.isInDirectory(file, WatcherUtils.getExternalAssetsSource(basedir)))
)
&& WatcherUtils.hasExtension(file, "css");
}
/**
* A file is created - process it.
*
* @param file the file
* @return {@literal true} as the pipeline should continue
* @throws WatchingException if the processing failed
*/
@Override
public boolean fileCreated(File file) throws WatchingException {
process(file);
return true;
}
/**
* Processes the CSS file.
*
* @param input the input file
* @throws WatchingException if the file cannot be processed
*/
private void process(File input) throws WatchingException {
// We are going to process a CSS file using Myth.
// First, determine which file we must process, indeed, the file may already have been copies to the
// destination directory
File destination = getOutputCSSFile(input);
// Create the destination folder.
if (!destination.getParentFile().isDirectory()) {
destination.getParentFile().mkdirs();
}
// If the destination file is more recent (or equally recent) than the input file, process that one
if (destination.isFile() && destination.lastModified() >= input.lastModified()) {
getLog().info("Processing " + destination.getAbsolutePath() + " instead of " + input.getAbsolutePath() +
" - the file was already processed");
input = destination;
}
// Now execute Myth
try {
int exit = myth.execute("myth", input.getAbsolutePath(), destination.getAbsolutePath());
getLog().debug("Myth execution exiting with status: " + exit);
} catch (MojoExecutionException e) {
throw new WatchingException("An error occurred during Myth processing of " + input.getAbsolutePath(), e);
}
}
/**
* A file is updated - process it.
*
* @param file the file
* @return {@literal true} as the pipeline should continue
* @throws WatchingException if the processing failed
*/
@Override
public boolean fileUpdated(File file) throws WatchingException {
process(file);
return true;
}
/**
* A file is deleted - delete the output.
*
* @param file the file
* @return {@literal true} as the pipeline should continue
*/
@Override
public boolean fileDeleted(File file) {
File theFile = getOutputCSSFile(file);
FileUtils.deleteQuietly(theFile);
return true;
}
/**
* Computes the name of the CSS file to generate (in target) from the given CSS file (from sources).
*
* @param input the input file
* @return the output file
*/
private File getOutputCSSFile(File input) {
File source;
File destination;
if (input.getAbsolutePath().startsWith(internalSources.getAbsolutePath())) {
source = internalSources;
destination = destinationForInternals;
} else {
source = externalSources;
destination = destinationForExternals;
}
String path = input.getParentFile().getAbsolutePath().substring(source.getAbsolutePath().length());
return new File(destination, path + "/" + input.getName());
}
}
| src/main/java/org/wisdom/myth/MythMojo.java | /*
* #%L
* Wisdom-Framework
* %%
* Copyright (C) 2013 - 2014 Wisdom Framework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.wisdom.myth;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.wisdom.maven.Constants;
import org.wisdom.maven.WatchingException;
import org.wisdom.maven.mojos.AbstractWisdomWatcherMojo;
import org.wisdom.maven.node.NPM;
import org.wisdom.maven.utils.WatcherUtils;
import java.io.File;
import java.util.Collection;
import static org.wisdom.maven.node.NPM.npm;
/**
* A Mojo extending Wisdom to support <a href="http://www.myth.io/">Myth CSS</a>.
* It watches CSS files from 'src/main/resources/assets' and 'src/main/assets' and process them using Myth. If the
* CSS file is already present in the destination directories (and more recent than the original file),
* it processes these one, letting this plugin work seamlessly with the Wisdom CSS features.
* <p/>
* Less files are not processed.
*/
@Mojo(name = "compile-myth", threadSafe = false,
requiresDependencyResolution = ResolutionScope.COMPILE,
requiresProject = true,
defaultPhase = LifecyclePhase.COMPILE)
public class MythMojo extends AbstractWisdomWatcherMojo implements Constants {
private static final String MYTH_NPM_NAME = "myth";
private File internalSources;
private File destinationForInternals;
private File externalSources;
private File destinationForExternals;
@Parameter(defaultValue = "0.3.4")
String version;
private NPM myth;
/**
* Executes the plugin. It compiles all CSS files from the assets directories and process them using Myth.
*
* @throws MojoExecutionException happens when a CSS file cannot be processed correctly
*/
@Override
public void execute() throws MojoExecutionException {
this.internalSources = new File(basedir, MAIN_RESOURCES_DIR);
this.destinationForInternals = new File(buildDirectory, "classes");
this.externalSources = new File(basedir, ASSETS_SRC_DIR);
this.destinationForExternals = new File(getWisdomRootDirectory(), ASSETS_DIR);
myth = npm(this, MYTH_NPM_NAME, version);
try {
if (internalSources.isDirectory()) {
getLog().info("Compiling CSS files with Myth from " + internalSources.getAbsolutePath());
Collection<File> files = FileUtils.listFiles(internalSources, new String[]{"css"}, true);
for (File file : files) {
if (file.isFile()) {
process(file);
}
}
}
if (externalSources.isDirectory()) {
getLog().info("Compiling CSS files with Myth from " + externalSources.getAbsolutePath());
Collection<File> files = FileUtils.listFiles(externalSources, new String[]{"css"}, true);
for (File file : files) {
if (file.isFile()) {
process(file);
}
}
}
} catch (WatchingException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
/**
* Checks whether the given file should be processed or not.
*
* @param file the file
* @return {@literal true} if the file must be handled, {@literal false} otherwise
*/
@Override
public boolean accept(File file) {
return
(WatcherUtils.isInDirectory(file, WatcherUtils.getInternalAssetsSource(basedir))
|| (WatcherUtils.isInDirectory(file, WatcherUtils.getExternalAssetsSource(basedir)))
)
&& WatcherUtils.hasExtension(file, "css");
}
/**
* A file is created - process it.
*
* @param file the file
* @return {@literal true} as the pipeline should continue
* @throws WatchingException if the processing failed
*/
@Override
public boolean fileCreated(File file) throws WatchingException {
process(file);
return true;
}
/**
* Processes the CSS file.
*
* @param input the input file
* @throws WatchingException if the file cannot be processed
*/
private void process(File input) throws WatchingException {
// We are going to process a CSS file using Myth.
// First, determine which file we must process, indeed, the file may already have been copies to the
// destination directory
File destination = getOutputCSSFile(input);
// Create the destination folder.
if (!destination.getParentFile().isDirectory()) {
destination.getParentFile().mkdirs();
}
// If the destination file is more recent (or equally recent) than the input file, process that one
if (destination.isFile() && destination.lastModified() >= input.lastModified()) {
getLog().info("Processing " + destination.getAbsolutePath() + " instead of " + input.getAbsolutePath() +
" - the file was already processed");
input = destination;
}
// Now execute Myth
try {
int exit = myth.execute("myth", input.getAbsolutePath(), destination.getAbsolutePath());
getLog().debug("Myth execution exiting with " + exit + " status");
} catch (MojoExecutionException e) {
throw new WatchingException("An error occurred during Myth processing of " + input.getAbsolutePath(), e);
}
}
/**
* A file is updated - process it.
*
* @param file the file
* @return {@literal true} as the pipeline should continue
* @throws WatchingException if the processing failed
*/
@Override
public boolean fileUpdated(File file) throws WatchingException {
process(file);
return true;
}
/**
* A file is deleted - delete the output.
*
* @param file the file
* @return {@literal true} as the pipeline should continue
*/
@Override
public boolean fileDeleted(File file) {
File theFile = getOutputCSSFile(file);
FileUtils.deleteQuietly(theFile);
return true;
}
/**
* Computes the name of the CSS file to generate (in target) from the given CSS file (from sources).
*
* @param input the input file
* @return the output file
*/
private File getOutputCSSFile(File input) {
File source;
File destination;
if (input.getAbsolutePath().startsWith(internalSources.getAbsolutePath())) {
source = internalSources;
destination = destinationForInternals;
} else {
source = externalSources;
destination = destinationForExternals;
}
String path = input.getParentFile().getAbsolutePath().substring(source.getAbsolutePath().length());
return new File(destination, path + "/" + input.getName());
}
}
| Improve debug message.
Signed-off-by: Clement Escoffier <[email protected]>
| src/main/java/org/wisdom/myth/MythMojo.java | Improve debug message. |
|
Java | apache-2.0 | 71d2d31fe6d95aaa2aa05b10c2f48e56cf5ff01e | 0 | dimamo5/Terasology,AWildBeard/Terasology,mertserezli/Terasology,MarcinSc/Terasology,Nanoware/Terasology,MovingBlocks/Terasology,kartikey0303/Terasology,Nanoware/Terasology,Nanoware/Terasology,Malanius/Terasology,MarcinSc/Terasology,Josharias/Terasology,frankpunx/Terasology,frankpunx/Terasology,Halamix2/Terasology,indianajohn/Terasology,dannyzhou98/Terasology,sceptross/Terasology,Vizaxo/Terasology,AWildBeard/Terasology,DPirate/Terasology,Josharias/Terasology,Vizaxo/Terasology,indianajohn/Terasology,kartikey0303/Terasology,dannyzhou98/Terasology,Halamix2/Terasology,dimamo5/Terasology,DPirate/Terasology,flo/Terasology,MovingBlocks/Terasology,kaen/Terasology,kaen/Terasology,MovingBlocks/Terasology,Malanius/Terasology,flo/Terasology,mertserezli/Terasology,sceptross/Terasology | /*
* Copyright 2014 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.world.generation;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.world.generator.plugin.WorldGeneratorPluginLibrary;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Immortius
*/
public class WorldBuilder {
private static final Logger logger = LoggerFactory.getLogger(WorldBuilder.class);
private final List<FacetProvider> providersList = Lists.newArrayList();
private final Set<Class<? extends WorldFacet>> facetCalculationInProgress = Sets.newHashSet();
private final List<WorldRasterizer> rasterizers = Lists.newArrayList();
private final List<EntityProvider> entityProviders = new ArrayList<>();
private int seaLevel = 32;
private Long seed;
private WorldGeneratorPluginLibrary pluginLibrary;
public WorldBuilder(WorldGeneratorPluginLibrary pluginLibrary) {
this.pluginLibrary = pluginLibrary;
}
public WorldBuilder addProvider(FacetProvider provider) {
providersList.add(provider);
return this;
}
public WorldBuilder addRasterizer(WorldRasterizer rasterizer) {
rasterizers.add(rasterizer);
return this;
}
public WorldBuilder addEntities(EntityProvider entityProvider) {
entityProviders.add(entityProvider);
return this;
}
public WorldBuilder addPlugins() {
pluginLibrary.instantiateAllOfType(FacetProviderPlugin.class).forEach(this::addProvider);
pluginLibrary.instantiateAllOfType(WorldRasterizerPlugin.class).forEach(this::addRasterizer);
return this;
}
/**
* @param level the sea level, measured in blocks
* @return this
*/
public WorldBuilder setSeaLevel(int level) {
this.seaLevel = level;
return this;
}
public void setSeed(long seed) {
this.seed = seed;
}
public World build() {
// TODO: ensure the required providers are present
if (seed == null) {
throw new IllegalStateException("Seed has not been set");
}
for (FacetProvider provider : providersList) {
provider.setSeed(seed);
}
ListMultimap<Class<? extends WorldFacet>, FacetProvider> providerChains = determineProviderChains();
return new WorldImpl(providerChains, rasterizers, entityProviders, determineBorders(providerChains), seaLevel);
}
private Map<Class<? extends WorldFacet>, Border3D> determineBorders(ListMultimap<Class<? extends WorldFacet>, FacetProvider> providerChains) {
Map<Class<? extends WorldFacet>, Border3D> borders = Maps.newHashMap();
for (Class<? extends WorldFacet> facet : providerChains.keySet()) {
ensureBorderCalculatedForFacet(facet, providerChains, borders);
}
return borders;
}
private void ensureBorderCalculatedForFacet(Class<? extends WorldFacet> facet, ListMultimap<Class<? extends WorldFacet>, FacetProvider> providerChains,
Map<Class<? extends WorldFacet>, Border3D> borders) {
if (!borders.containsKey(facet)) {
Border3D border = new Border3D(0, 0, 0);
for (FacetProvider facetProvider : providerChains.values()) {
// Find all facets that require it
Requires requires = facetProvider.getClass().getAnnotation(Requires.class);
if (requires != null) {
for (Facet requiredFacet : requires.value()) {
if (requiredFacet.value() == facet) {
Produces produces = facetProvider.getClass().getAnnotation(Produces.class);
Updates updates = facetProvider.getClass().getAnnotation(Updates.class);
FacetBorder requiredBorder = requiredFacet.border();
if (produces != null) {
for (Class<? extends WorldFacet> producedFacet : produces.value()) {
ensureBorderCalculatedForFacet(producedFacet, providerChains, borders);
Border3D borderForProducedFacet = borders.get(producedFacet);
border = border.maxWith(
borderForProducedFacet.getTop() + requiredBorder.top(),
borderForProducedFacet.getBottom() + requiredBorder.bottom(),
borderForProducedFacet.getSides() + requiredBorder.sides());
}
}
if (updates != null) {
for (Facet producedFacetAnnotation : updates.value()) {
Class<? extends WorldFacet> producedFacet = producedFacetAnnotation.value();
FacetBorder borderForFacetAnnotation = producedFacetAnnotation.border();
ensureBorderCalculatedForFacet(producedFacet, providerChains, borders);
Border3D borderForProducedFacet = borders.get(producedFacet);
border = border.maxWith(
borderForProducedFacet.getTop() + requiredBorder.top() + borderForFacetAnnotation.top(),
borderForProducedFacet.getBottom() + requiredBorder.bottom() + borderForFacetAnnotation.bottom(),
borderForProducedFacet.getSides() + requiredBorder.sides() + borderForFacetAnnotation.sides());
}
}
}
}
}
}
borders.put(facet, border);
}
}
private ListMultimap<Class<? extends WorldFacet>, FacetProvider> determineProviderChains() {
ListMultimap<Class<? extends WorldFacet>, FacetProvider> result = ArrayListMultimap.create();
Set<Class<? extends WorldFacet>> facets = Sets.newHashSet();
for (FacetProvider provider : providersList) {
Produces produces = provider.getClass().getAnnotation(Produces.class);
if (produces != null) {
facets.addAll(Arrays.asList(produces.value()));
}
Updates updates = provider.getClass().getAnnotation(Updates.class);
if (updates != null) {
for (Facet facet : updates.value()) {
facets.add(facet.value());
}
}
}
for (Class<? extends WorldFacet> facet : facets) {
determineProviderChainFor(facet, result);
}
return result;
}
private void determineProviderChainFor(Class<? extends WorldFacet> facet, ListMultimap<Class<? extends WorldFacet>, FacetProvider> result) {
if (result.containsKey(facet)) {
return;
}
if (!facetCalculationInProgress.add(facet)) {
throw new RuntimeException("Circular dependency detected when calculating facet provider ordering for " + facet);
}
Set<FacetProvider> orderedProviders = Sets.newLinkedHashSet();
// first add all @Produces facet providers
for (FacetProvider provider : providersList) {
if (producesFacet(provider, facet)) {
Requires requirements = provider.getClass().getAnnotation(Requires.class);
if (requirements != null) {
for (Facet requirement : requirements.value()) {
determineProviderChainFor(requirement.value(), result);
orderedProviders.addAll(result.get(requirement.value()));
}
}
orderedProviders.add(provider);
}
}
// then add all @Updates facet providers
for (FacetProvider provider : providersList) {
if (updatesFacet(provider, facet)) {
Requires requirements = provider.getClass().getAnnotation(Requires.class);
if (requirements != null) {
for (Facet requirement : requirements.value()) {
determineProviderChainFor(requirement.value(), result);
orderedProviders.addAll(result.get(requirement.value()));
}
}
orderedProviders.add(provider);
}
}
result.putAll(facet, orderedProviders);
facetCalculationInProgress.remove(facet);
}
private boolean producesFacet(FacetProvider provider, Class<? extends WorldFacet> facet) {
Produces produces = provider.getClass().getAnnotation(Produces.class);
if (produces != null && Arrays.asList(produces.value()).contains(facet)) {
return true;
}
return false;
}
private boolean updatesFacet(FacetProvider provider, Class<? extends WorldFacet> facet) {
Updates updates = provider.getClass().getAnnotation(Updates.class);
if (updates != null) {
for (Facet updatedFacet : updates.value()) {
if (updatedFacet.value() == facet) {
return true;
}
}
}
return false;
}
public FacetedWorldConfigurator createConfigurator() {
List<ConfigurableFacetProvider> configurables = new ArrayList<>();
for (FacetProvider facetProvider : providersList) {
if (facetProvider instanceof ConfigurableFacetProvider) {
configurables.add((ConfigurableFacetProvider) facetProvider);
}
}
FacetedWorldConfigurator worldConfigurator = new FacetedWorldConfigurator(configurables);
return worldConfigurator;
}
}
| engine/src/main/java/org/terasology/world/generation/WorldBuilder.java | /*
* Copyright 2014 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.world.generation;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.world.generator.plugin.WorldGeneratorPluginLibrary;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Immortius
*/
public class WorldBuilder {
private static final Logger logger = LoggerFactory.getLogger(WorldBuilder.class);
private final List<FacetProvider> providersList = Lists.newArrayList();
private final Set<Class<? extends WorldFacet>> facetCalculationInProgress = Sets.newHashSet();
private final List<WorldRasterizer> rasterizers = Lists.newArrayList();
private final List<EntityProvider> entityProviders = new ArrayList<>();
private int seaLevel = 32;
private Long seed;
private WorldGeneratorPluginLibrary pluginLibrary;
public WorldBuilder(WorldGeneratorPluginLibrary pluginLibrary) {
this.pluginLibrary = pluginLibrary;
}
public WorldBuilder addProvider(FacetProvider provider) {
providersList.add(provider);
return this;
}
public WorldBuilder addRasterizer(WorldRasterizer rasterizer) {
rasterizers.add(rasterizer);
return this;
}
public WorldBuilder addEntities(EntityProvider entityProvider) {
entityProviders.add(entityProvider);
return this;
}
public WorldBuilder addPlugins() {
pluginLibrary.instantiateAllOfType(FacetProviderPlugin.class).forEach(this::addProvider);
pluginLibrary.instantiateAllOfType(WorldRasterizerPlugin.class).forEach(this::addRasterizer);
return this;
}
/**
* @param level the sea level, measured in blocks
* @return this
*/
public WorldBuilder setSeaLevel(int level) {
this.seaLevel = level;
return this;
}
public void setSeed(long seed) {
this.seed = seed;
}
public World build() {
// TODO: ensure the required providers are present
if (seed == null) {
throw new IllegalStateException("Seed has not been set");
}
for (FacetProvider provider : providersList) {
provider.setSeed(seed);
}
ListMultimap<Class<? extends WorldFacet>, FacetProvider> providerChains = determineProviderChains();
return new WorldImpl(providerChains, rasterizers, entityProviders, determineBorders(providerChains), seaLevel);
}
private Map<Class<? extends WorldFacet>, Border3D> determineBorders(ListMultimap<Class<? extends WorldFacet>, FacetProvider> providerChains) {
Map<Class<? extends WorldFacet>, Border3D> borders = Maps.newHashMap();
for (Class<? extends WorldFacet> facet : providerChains.keySet()) {
ensureBorderCalculatedForFacet(facet, providerChains, borders);
}
return borders;
}
private void ensureBorderCalculatedForFacet(Class<? extends WorldFacet> facet, ListMultimap<Class<? extends WorldFacet>, FacetProvider> providerChains,
Map<Class<? extends WorldFacet>, Border3D> borders) {
if (!borders.containsKey(facet)) {
Border3D border = new Border3D(0, 0, 0);
for (FacetProvider facetProvider : providerChains.values()) {
// Find all facets that require it
Requires requires = facetProvider.getClass().getAnnotation(Requires.class);
if (requires != null) {
for (Facet requiredFacet : requires.value()) {
if (requiredFacet.value() == facet) {
Produces produces = facetProvider.getClass().getAnnotation(Produces.class);
Updates updates = facetProvider.getClass().getAnnotation(Updates.class);
FacetBorder requiredBorder = requiredFacet.border();
if (produces != null) {
for (Class<? extends WorldFacet> producedFacet : produces.value()) {
ensureBorderCalculatedForFacet(producedFacet, providerChains, borders);
Border3D borderForProducedFacet = borders.get(producedFacet);
border = border.maxWith(
borderForProducedFacet.getTop() + requiredBorder.top(),
borderForProducedFacet.getBottom() + requiredBorder.bottom(),
borderForProducedFacet.getSides() + requiredBorder.sides());
}
}
if (updates != null) {
for (Facet producedFacetAnnotation : updates.value()) {
Class<? extends WorldFacet> producedFacet = producedFacetAnnotation.value();
FacetBorder borderForFacetAnnotation = producedFacetAnnotation.border();
ensureBorderCalculatedForFacet(producedFacet, providerChains, borders);
Border3D borderForProducedFacet = borders.get(producedFacet);
border = border.maxWith(
borderForProducedFacet.getTop() + requiredBorder.top() + borderForFacetAnnotation.top(),
borderForProducedFacet.getBottom() + requiredBorder.bottom() + borderForFacetAnnotation.bottom(),
borderForProducedFacet.getSides() + requiredBorder.sides() + borderForFacetAnnotation.sides());
}
}
}
}
}
}
borders.put(facet, border);
}
}
private ListMultimap<Class<? extends WorldFacet>, FacetProvider> determineProviderChains() {
ListMultimap<Class<? extends WorldFacet>, FacetProvider> result = ArrayListMultimap.create();
Set<Class<? extends WorldFacet>> facets = Sets.newHashSet();
for (FacetProvider provider : providersList) {
Produces produces = provider.getClass().getAnnotation(Produces.class);
if (produces != null) {
facets.addAll(Arrays.asList(produces.value()));
}
Updates updates = provider.getClass().getAnnotation(Updates.class);
if (updates != null) {
for (Facet facet : updates.value()) {
facets.add(facet.value());
}
}
}
for (Class<? extends WorldFacet> facet : facets) {
determineProviderChainFor(facet, result);
}
return result;
}
private void determineProviderChainFor(Class<? extends WorldFacet> facet, ListMultimap<Class<? extends WorldFacet>, FacetProvider> result) {
if (result.containsKey(facet)) {
return;
}
if (!facetCalculationInProgress.add(facet)) {
throw new RuntimeException("Circular dependency detected when calculating facet provider ordering for " + facet);
}
Set<FacetProvider> orderedProviders = Sets.newLinkedHashSet();
for (FacetProvider provider : providersList) {
if (producesFacet(provider, facet)) {
Requires requirements = provider.getClass().getAnnotation(Requires.class);
if (requirements != null) {
for (Facet requirement : requirements.value()) {
determineProviderChainFor(requirement.value(), result);
orderedProviders.addAll(result.get(requirement.value()));
}
}
orderedProviders.add(provider);
}
}
result.putAll(facet, orderedProviders);
facetCalculationInProgress.remove(facet);
}
private boolean producesFacet(FacetProvider provider, Class<? extends WorldFacet> facet) {
Produces produces = provider.getClass().getAnnotation(Produces.class);
if (produces != null && Arrays.asList(produces.value()).contains(facet)) {
return true;
}
Updates updates = provider.getClass().getAnnotation(Updates.class);
if (updates != null) {
for (Facet updatedFacet : updates.value()) {
if (updatedFacet.value() == facet) {
return true;
}
}
}
return false;
}
public FacetedWorldConfigurator createConfigurator() {
List<ConfigurableFacetProvider> configurables = new ArrayList<>();
for (FacetProvider facetProvider : providersList) {
if (facetProvider instanceof ConfigurableFacetProvider) {
configurables.add((ConfigurableFacetProvider) facetProvider);
}
}
FacetedWorldConfigurator worldConfigurator = new FacetedWorldConfigurator(configurables);
return worldConfigurator;
}
}
| Add updating providers after producing providers
| engine/src/main/java/org/terasology/world/generation/WorldBuilder.java | Add updating providers after producing providers |
|
Java | apache-2.0 | 9babc4c5e6176f5145ee2553f7b644aa47e61b92 | 0 | ctgriffiths/twister,ctgriffiths/twister,Luxoft/Twister,Luxoft/Twister,ctgriffiths/twister,Luxoft/Twister,ctgriffiths/twister,Luxoft/Twister,Luxoft/Twister,Luxoft/Twister,ctgriffiths/twister,Luxoft/Twister,ctgriffiths/twister | /*
File: applet.java ; This file is part of Twister.
Copyright (C) 2012 , Luxoft
Authors: Andrei Costachi <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import javax.swing.JPanel;
import javax.swing.JEditorPane;
import javax.swing.event.HyperlinkListener;
import java.net.URL;
import javax.swing.event.HyperlinkEvent;
import javax.swing.text.html.HTMLFrameHyperlinkEvent;
public class Browser{
public JEditorPane displayEditorPane;
public Browser(){
displayEditorPane = new JEditorPane();
displayEditorPane.setContentType("text/html");
displayEditorPane.setEditable(false);
try{displayEditorPane.setPage(new URL("http://"+Repository.host+":"+Repository.getHTTPServerPort()));}
catch(Exception e){System.out.println("could not get "+Repository.host+":"+Repository.getHTTPServerPort());}
displayEditorPane.addHyperlinkListener(new HyperlinkListener(){
public void hyperlinkUpdate(HyperlinkEvent e){
HyperlinkEvent.EventType eventType = e.getEventType();
if(eventType == HyperlinkEvent.EventType.ACTIVATED){
if(!(e instanceof HTMLFrameHyperlinkEvent)){
try{displayEditorPane.setPage(e.getURL());}
catch(Exception ex){System.out.println("Could not get to:"+e.getURL());}}}}});}} | src/client/userinterface/java/src/Browser.java | /*
File: Browser.java ; This file is part of Twister.
Copyright (C) 2012 , Luxoft
Authors: Andrei Costachi <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import javax.swing.JPanel;
import javax.swing.JEditorPane;
import javax.swing.event.HyperlinkListener;
import java.net.URL;
import javax.swing.event.HyperlinkEvent;
import javax.swing.text.html.HTMLFrameHyperlinkEvent;
public class Browser {
public JEditorPane displayEditorPane;
public Browser() {
displayEditorPane = new JEditorPane();
displayEditorPane.setContentType("text/html");
displayEditorPane.setEditable(false);
try {
displayEditorPane.setPage(new URL("http://" + Repository.host + ":"
+ Repository.getHTTPServerPort()));
} catch (Exception e) {
System.out.println("could not get " + Repository.host + ":"
+ Repository.getHTTPServerPort());
}
displayEditorPane.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
HyperlinkEvent.EventType eventType = e.getEventType();
if (eventType == HyperlinkEvent.EventType.ACTIVATED) {
if (!(e instanceof HTMLFrameHyperlinkEvent)) {
try {
displayEditorPane.setPage(e.getURL());
} catch (Exception ex) {
System.out.println("Could not get to:" + e.getURL());
}
}
}
}
});
}
}
| latest version
| src/client/userinterface/java/src/Browser.java | latest version |
|
Java | apache-2.0 | 4e3e63e8c54fe67835d0d358a5cdcedf50b5623b | 0 | jeffmaury/mina,apache/mina,yangzhongj/mina,apache/mina,weijiangzhu/mina,universsky/mina,Vicky01200059/mina,Vicky01200059/mina,dongjiaqiang/mina,weijiangzhu/mina,mway08/mina,yangzhongj/mina,mway08/mina,dongjiaqiang/mina,universsky/mina | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.mina.common;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An {@link IoProcessor} pool that distributes {@link IoSession}s into one or more
* {@link IoProcessor}s. Most current transport implementations use this pool internally
* to perform better in a multi-core environment, and therefore, you won't need to
* use this pool directly unless you are running multiple {@link IoService}s in the
* same JVM.
* <p>
* If you are running multiple {@link IoService}s, you could want to share the pool
* among all services. To do so, you can create a new {@link SimpleIoProcessorPool}
* instance by yourself and provide the pool as a constructor parameter when you
* create the services.
* <p>
* This pool uses Java reflection API to create multiple {@link IoProcessor} instances.
* It tries to instantiate the processor in the following order:
* <ol>
* <li>A public constructor with one {@link ExecutorService} parameter.</li>
* <li>A public constructor with one {@link Executor} parameter.</li>
* <li>A public default constructor</li>
* </ol>
* The following is an example for the NIO socket transport:
* <pre><code>
* // Create a shared pool.
* SimpleIoProcessorPool<NioSession> pool =
* new SimpleIoProcessorPool<NioSession>(NioProcessor.class, 16);
*
* // Create two services that share the same pool.
* SocketAcceptor acceptor = new NioSocketAcceptor(pool);
* SocketConnector connector = new NioSocketConnector(pool);
*
* ...
*
* // Release related resources.
* connector.dispose();
* acceptor.dispose();
* pool.dispose();
* </code></pre>
*
* @author The Apache MINA Project ([email protected])
* @version $Rev$, $Date$
*
* @param <T> the type of the {@link IoSession} to be managed by the specified
* {@link IoProcessor}.
*/
public class SimpleIoProcessorPool<T extends AbstractIoSession> implements IoProcessor<T> {
private static final int DEFAULT_SIZE = Runtime.getRuntime().availableProcessors() + 1;
private static final AttributeKey PROCESSOR = new AttributeKey(SimpleIoProcessorPool.class, "processor");
private final Logger logger = LoggerFactory.getLogger(getClass());
private final IoProcessor<T>[] pool;
private final AtomicInteger processorDistributor = new AtomicInteger();
private final Executor executor;
private final boolean createdExecutor;
private final Object disposalLock = new Object();
private volatile boolean disposing;
private volatile boolean disposed;
public SimpleIoProcessorPool(Class<? extends IoProcessor<T>> processorType) {
this(processorType, null, DEFAULT_SIZE);
}
public SimpleIoProcessorPool(Class<? extends IoProcessor<T>> processorType, int size) {
this(processorType, null, size);
}
public SimpleIoProcessorPool(Class<? extends IoProcessor<T>> processorType, Executor executor) {
this(processorType, executor, DEFAULT_SIZE);
}
@SuppressWarnings("unchecked")
public SimpleIoProcessorPool(Class<? extends IoProcessor<T>> processorType, Executor executor, int size) {
if (processorType == null) {
throw new NullPointerException("processorType");
}
if (size <= 0) {
throw new IllegalArgumentException(
"size: " + size + " (expected: positive integer)");
}
if (executor == null) {
this.executor = executor = Executors.newCachedThreadPool();
this.createdExecutor = true;
} else {
this.executor = executor;
this.createdExecutor = false;
}
pool = new IoProcessor[size];
boolean success = false;
try {
for (int i = 0; i < pool.length; i ++) {
IoProcessor<T> processor = null;
// Try to create a new processor with a proper constructor.
try {
try {
processor = processorType.getConstructor(ExecutorService.class).newInstance(executor);
} catch (NoSuchMethodException e) {
// To the next step...
}
if (processor == null) {
try {
processor = processorType.getConstructor(Executor.class).newInstance(executor);
} catch (NoSuchMethodException e) {
// To the next step...
}
}
if (processor == null) {
try {
processor = processorType.getConstructor().newInstance();
} catch (NoSuchMethodException e) {
// To the next step...
}
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeIoException(
"Failed to create a new instance of " + processorType.getName(), e);
}
// Raise an exception if no proper constructor is found.
if (processor == null) {
throw new IllegalArgumentException(
String.valueOf(processorType) + " must have a public constructor " +
"with one " + ExecutorService.class.getSimpleName() + " parameter, " +
"a public constructor with one " + Executor.class.getSimpleName() +
" parameter or a public default constructor.");
}
pool[i] = processor;
}
success = true;
} finally {
if (!success) {
dispose();
}
}
}
public final void add(T session) {
getProcessor(session).add(session);
}
public final void flush(T session) {
getProcessor(session).flush(session);
}
public final void remove(T session) {
getProcessor(session).remove(session);
}
public final void updateTrafficMask(T session) {
getProcessor(session).updateTrafficMask(session);
}
public boolean isDisposed() {
return disposed;
}
public boolean isDisposing() {
return disposing;
}
public final void dispose() {
if (disposed) {
return;
}
synchronized (disposalLock) {
if (!disposing) {
disposing = true;
for (int i = pool.length - 1; i >= 0; i --) {
if (pool[i] == null || pool[i].isDisposing()) {
continue;
}
try {
pool[i].dispose();
} catch (Exception e) {
logger.warn(
"Failed to dispose a " +
pool[i].getClass().getSimpleName() +
" at index " + i + ".", e);
} finally {
pool[i] = null;
}
}
if (createdExecutor) {
((ExecutorService) executor).shutdown();
}
}
}
disposed = true;
}
@SuppressWarnings("unchecked")
private IoProcessor<T> getProcessor(T session) {
IoProcessor<T> p = (IoProcessor<T>) session.getAttribute(PROCESSOR);
if (p == null) {
p = nextProcessor();
IoProcessor<T> oldp =
(IoProcessor<T>) session.setAttributeIfAbsent(PROCESSOR, p);
if (oldp != null) {
p = oldp;
}
}
return p;
}
private IoProcessor<T> nextProcessor() {
checkDisposal();
return pool[Math.abs(processorDistributor.getAndIncrement()) % pool.length];
}
private void checkDisposal() {
if (disposed) {
throw new IllegalStateException("A disposed processor cannot be accessed.");
}
}
}
| core/src/main/java/org/apache/mina/common/SimpleIoProcessorPool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.mina.common;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An {@link IoProcessor} pool that distributes {@link IoSession}s into one or more
* {@link IoProcessor}s. Most current transport implementations use this pool internally
* to perform better in a multi-core environment, and therefore, you won't need to
* use this pool directly unless you are running multiple {@link IoService}s in the
* same JVM.
* <p>
* If you are running multiple {@link IoService}s, you could want to share the pool
* among all services. To do so, you can create a new {@link SimpleIoProcessorPool}
* instance by yourself and provide the pool as a constructor parameter when you
* create the services.
* <p>
* This pool uses Java reflection API to create multiple {@link IoProcessor} instances.
* It tries to instantiate the processor in the following order:
* <ol>
* <li>A public constructor with one {@link ExecutorService} parameter.</li>
* <li>A public constructor with one {@link Executor} parameter.</li>
* <li>A public default constructor</li>
* </ol>
* The following is an example for the NIO socket transport:
* <pre><code>
* // Create a shared pool.
* SimpleIoProcessorPool<NioSession> pool =
* new SimpleIoProcessorPool<NioSession>(NioProcessor.class, 16);
*
* // Create two services that share the same pool.
* SocketAcceptor acceptor = new NioSocketAcceptor(pool);
* SocketConnector connector = new NioSocketConnector(pool);
*
* ...
*
* // Release related resources.
* connector.dispose();
* acceptor.dispose();
* pool.dispose();
* </code></pre>
*
* @author The Apache MINA Project ([email protected])
* @version $Rev$, $Date$
*
* @param <T> the type of the {@link IoSession} to be managed by the specified
* {@link IoProcessor}.
*/
public class SimpleIoProcessorPool<T extends AbstractIoSession> implements IoProcessor<T> {
private static final int DEFAULT_SIZE = Runtime.getRuntime().availableProcessors() + 1;
private static final AttributeKey PROCESSOR = new AttributeKey(SimpleIoProcessorPool.class, "processor");
private final Logger logger = LoggerFactory.getLogger(getClass());
private final IoProcessor<T>[] pool;
private final AtomicInteger processorDistributor = new AtomicInteger();
private final Executor executor;
private final boolean createdExecutor;
private final Object disposalLock = new Object();
private volatile boolean disposing;
private volatile boolean disposed;
public SimpleIoProcessorPool(Class<? extends IoProcessor<T>> processorType) {
this(processorType, null, DEFAULT_SIZE);
}
public SimpleIoProcessorPool(Class<? extends IoProcessor<T>> processorType, int size) {
this(processorType, null, size);
}
public SimpleIoProcessorPool(Class<? extends IoProcessor<T>> processorType, Executor executor) {
this(processorType, executor, DEFAULT_SIZE);
}
@SuppressWarnings("unchecked")
public SimpleIoProcessorPool(Class<? extends IoProcessor<T>> processorType, Executor executor, int size) {
if (processorType == null) {
throw new NullPointerException("processorType");
}
if (size <= 0) {
throw new IllegalArgumentException(
"size: " + size + " (expected: positive integer)");
}
if (executor == null) {
this.executor = executor = Executors.newCachedThreadPool();
this.createdExecutor = true;
} else {
this.executor = executor;
this.createdExecutor = false;
}
pool = new IoProcessor[size];
boolean success = false;
try {
for (int i = 0; i < pool.length; i ++) {
IoProcessor<T> processor = null;
// Try to create a new processor with a proper constructor.
try {
try {
processor = processorType.getConstructor(ExecutorService.class).newInstance(executor);
} catch (NoSuchMethodException e) {
// To the next step...
}
if (processor == null) {
try {
processor = processorType.getConstructor(Executor.class).newInstance(executor);
} catch (NoSuchMethodException e) {
// To the next step...
}
}
if (processor == null) {
try {
processor = processorType.getConstructor().newInstance();
} catch (NoSuchMethodException e) {
// To the next step...
}
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeIoException(
"Failed to create a new instance of " + processorType.getName(), e);
}
// Raise an exception if no proper constructor is found.
if (processor == null) {
throw new IllegalArgumentException(
String.valueOf(processorType) + " must have a public constructor " +
"with one " + ExecutorService.class.getSimpleName() + " parameter, " +
"a public constructor with one " + Executor.class.getSimpleName() +
" parameter or a public default constructor.");
}
pool[i] = processor;
}
success = true;
} finally {
if (!success) {
dispose();
}
}
}
public final void add(T session) {
getProcessor(session).add(session);
}
public final void flush(T session) {
getProcessor(session).flush(session);
}
public final void remove(T session) {
getProcessor(session).remove(session);
}
public final void updateTrafficMask(T session) {
getProcessor(session).updateTrafficMask(session);
}
public boolean isDisposed() {
return disposed;
}
public boolean isDisposing() {
return disposing;
}
public final void dispose() {
if (disposed) {
return;
}
synchronized (disposalLock) {
if (!disposing) {
disposing = true;
for (int i = pool.length - 1; i >= 0; i --) {
if (pool[i] == null) {
continue;
}
try {
pool[i].dispose();
} catch (Exception e) {
logger.warn(
"Failed to dispose a " +
pool[i].getClass().getSimpleName() +
" at index " + i + ".", e);
} finally {
pool[i] = null;
}
}
if (createdExecutor) {
((ExecutorService) executor).shutdown();
}
}
}
disposed = true;
}
@SuppressWarnings("unchecked")
private IoProcessor<T> getProcessor(T session) {
IoProcessor<T> p = (IoProcessor<T>) session.getAttribute(PROCESSOR);
if (p == null) {
p = nextProcessor();
IoProcessor<T> oldp =
(IoProcessor<T>) session.setAttributeIfAbsent(PROCESSOR, p);
if (oldp != null) {
p = oldp;
}
}
return p;
}
private IoProcessor<T> nextProcessor() {
checkDisposal();
return pool[Math.abs(processorDistributor.getAndIncrement()) % pool.length];
}
private void checkDisposal() {
if (disposed) {
throw new IllegalStateException("A disposed processor cannot be accessed.");
}
}
}
| Fixed a dead lock which occurs when IoService.dispose() is invoked from an IoHandler
git-svn-id: b7022df5c975f24f6cce374a8cf09e1bba3b7a2e@609876 13f79535-47bb-0310-9956-ffa450edef68
| core/src/main/java/org/apache/mina/common/SimpleIoProcessorPool.java | Fixed a dead lock which occurs when IoService.dispose() is invoked from an IoHandler |
|
Java | apache-2.0 | 6cf864f244b5ba047b7faaa48f1acbbb6e6e10c9 | 0 | kelemen/JTrim,kelemen/JTrim | package org.jtrim.access;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.ReentrantLock;
import org.jtrim.collections.ArraysEx;
import org.jtrim.collections.CollectionsEx;
import org.jtrim.collections.RefLinkedList;
import org.jtrim.collections.RefList;
import org.jtrim.concurrent.TaskScheduler;
import org.jtrim.utils.ExceptionHelper;
/**
* An implementation of {@code AccessManager} which can manage
* {@link HierarchicalRight hierarchical rights}.
*
* <h3>Rights</h3>
* This implementation uses hierarchical rights so requesting a right will
* need that subrights are also available for the requested use. The value
* {@code null} is not considered to be a valid hierarchical right.
* See {@link HierarchicalRight} for further details on hierarchical rights.
*
* <h3>Events</h3>
* This implementation can notify clients if a right becomes available or
* unavailable. These notification events are submitted to a user specified
* {@link java.util.concurrent.Executor Executor}, so clients can define
* where the events execute but cannot define on what thread these events
* are submitted to this {@code Executor}. They maybe scheduled on the thread
* used by the {@code Executor} of the {@link AccessToken AccessTokens} or
* in the call stack of caller of a methods of this class. Although is not
* possible to determine which event is submitted on which thread, these events
* will be submitted in the order they occurred.
* <P>
* Note that the listener may not be notified of some of the changes in the
* state of a right if states change fast. That is if a right enters a specific
* state previous (not yet reported) changes in the state is not required to
* be reported by this implementation. For example if a certain right becomes
* {@link AccessState#UNAVAILABLE unavailable} it may have been already in
* lots of previous states not reported.
* <P>
* When an event is reported, listeners must assume that every subright of
* the specified right is in the reported state and the state of those
* subrights will not be reported.
* <P>
* Note that no events will be reported before a new {@code AccessToken} is
* requested so it is possible to initialize the specified listener
* with the newly created instance of this {@code AccessManager} immediately
* after constructing the {@code AccessManager}.
*
* <h3>Thread safety</h3>
* This class is thread-safe without any further synchronization. Note however
* that although thread-safe, this implementation will not scale well with
* multiple processors.
* <h4>Synchronization transparency</h4>
* The methods of this class are not <I>synchronization transparent</I>
* because they may notify the specified
* {@link AccessStateListener right state listener}. In case
* scheduling the events of the changes in right states is
* <I>synchronization transparent</I> then the methods of this class are also
* <I>synchronization transparent</I>. Note that in most case you cannot
* assume this and can only rely on that they do not block indefinitely.
*
* @param <IDType> the type of the request ID (see
* {@link AccessRequest#getRequestID()})
*
* @see HierarchicalRight
* @author Kelemen Attila
*/
public final class HierarchicalAccessManager<IDType>
implements
AccessManager<IDType, HierarchicalRight> {
private final ReentrantLock mainLock;
private final Executor taskExecutor;
private final AccessTree<AccessTokenImpl<IDType>> readTree;
private final AccessTree<AccessTokenImpl<IDType>> writeTree;
private final TaskScheduler eventScheduler;
private final AccessStateListener<HierarchicalRight> stateListener;
/**
* Creates a new {@code HierarchicalAccessManager} which will not notify
* clients of changes in the states of rights. The instance created
* by this constructor is slightly more efficient than using
* {@link #HierarchicalAccessManager(java.util.concurrent.Executor, java.util.concurrent.Executor, org.jtrim.access.AccessStateListener) HierarchicalAccessManager(Executor, Executor, AccessStateListener)}
* When creating a new instance all rights are considered to be in the
* {@link AccessState#AVAILABLE available} state. Rights will remain in this
* state until a new {@code AccessToken} is requested.
*
* @param taskExecutor the default {@code Executor} of
* {@link AccessToken AccessTokens} created by this {@code AccessManager}.
* Tasks submitted to these {@code AccessToken}s will execute on this
* {@code Executor}. This argument cannot be {@code null}.
*
* @throws NullPointerException thrown if the specified {@code Executor}
* is {@code null}
*/
public HierarchicalAccessManager(Executor taskExecutor) {
ExceptionHelper.checkNotNullArgument(taskExecutor, "taskExecutor");
this.mainLock = new ReentrantLock();
this.stateListener = null;
this.eventScheduler = null;
this.taskExecutor = taskExecutor;
this.readTree = new AccessTree<>();
this.writeTree = new AccessTree<>();
}
/**
* Creates a new {@code HierarchicalAccessManager} which will notify
* clients of changes in the states of rights.
* When creating a new instance all rights are considered to be in the
* {@link AccessState#AVAILABLE available} state. Rights will remain in this
* state until a new {@code AccessToken} is requested and the listener
* will not be notified until such request was made.
*
* @param taskExecutor the {@code Executor} of the
* {@link AccessToken AccessTokens} created by this {@code AccessManager}.
* Tasks submitted to these {@code AccessToken}s will execute on this
* {@code Executor}. This argument cannot be {@code null}.
* @param eventExecutor the {@code Executor} to which events of changes in
* the state of rights are submitted to. This argument cannot be
* {@code null}.
* @param stateListener the listener which will be notified of changes in
* the state of rights. This argument cannot be {@code null}.
*
* @throws NullPointerException thrown if any of the arguments is
* {@code null}
*/
public HierarchicalAccessManager(
Executor taskExecutor,
Executor eventExecutor,
AccessStateListener<HierarchicalRight> stateListener) {
ExceptionHelper.checkNotNullArgument(taskExecutor, "taskExecutor");
ExceptionHelper.checkNotNullArgument(eventExecutor, "eventExecutor");
ExceptionHelper.checkNotNullArgument(stateListener, "stateListener");
this.mainLock = new ReentrantLock();
this.stateListener = stateListener;
this.eventScheduler = new TaskScheduler(eventExecutor);
this.taskExecutor = taskExecutor;
this.readTree = new AccessTree<>();
this.writeTree = new AccessTree<>();
}
/**
* Returns the shared tokens of the specified tokens without returning
* the same token twice (using "==" for comparison).
*
* @param <V> the type of the request ID
* @param tokens the tokens of which the shared tokens are to be returned.
* This argument cannot be {@code null}.
*/
private static <V> Set<AccessToken<V>> getUniqueSharedTokens(
Collection<AccessTokenImpl<V>> tokens) {
Set<AccessToken<V>> result = CollectionsEx.newIdentityHashSet(tokens.size());
for (AccessTokenImpl<V> token: tokens) {
AccessToken<V> sharedToken = token.getSharedToken();
if (sharedToken != null) {
result.add(sharedToken);
}
}
return result;
}
private static <V> Set<V> createSet(Collection<? extends V> collection) {
Set<V> result = CollectionsEx.newIdentityHashSet(collection.size());
result.addAll(collection);
return result;
}
/**
* Collects the rights which can be found in the {@code source} collection
* considering subrights as well.
*
* @param source the rights in which the new rights are to be searched
* @param toAdd the rights to be searched in {@code source}
* @param result the found rights will be added to this set
*/
private static void addIfHasRight(
Collection<? extends HierarchicalRight> source,
Collection<? extends HierarchicalRight> toAdd,
Set<? super HierarchicalRight> result) {
RightTreeBuilder rightTree = new RightTreeBuilder();
rightTree.addRights(source);
for (HierarchicalRight right: toAdd) {
if (rightTree.hasRight(right)) {
result.add(right);
}
}
}
/**
* Schedules all the events of the specified states.
* This method must not be called if the events are not requested to be
* forwarded by the client.
* <P>
* Events must be {@link #dispatchEvents() dispatched} after this call.
*/
private void scheduleEvents(
Collection<? extends HierarchicalRight> unavailable,
Collection<? extends HierarchicalRight> readOnly,
Collection<? extends HierarchicalRight> available) {
assert stateListener != null && eventScheduler != null;
if (unavailable.isEmpty() && readOnly.isEmpty() && available.isEmpty()) {
return;
}
final HierarchicalAccessManager<?> thisManager = this;
List<Runnable> tasks = new LinkedList<>();
for (final HierarchicalRight right: unavailable) {
tasks.add(new Runnable() {
@Override
public void run() {
stateListener.onEnterState(thisManager, right, AccessState.UNAVAILABLE);
}
});
}
for (final HierarchicalRight right: readOnly) {
tasks.add(new Runnable() {
@Override
public void run() {
stateListener.onEnterState(thisManager, right, AccessState.READONLY);
}
});
}
for (final HierarchicalRight right: available) {
tasks.add(new Runnable() {
@Override
public void run() {
stateListener.onEnterState(thisManager, right, AccessState.AVAILABLE);
}
});
}
eventScheduler.scheduleTasks(tasks);
}
/**
* Submits state change events if the client requested to do so.
*/
private void dispatchEvents() {
assert !mainLock.isHeldByCurrentThread();
if (eventScheduler != null) {
eventScheduler.dispatchTasks();
}
}
/**
* Schedules events for right downgrades. That is:
* <ul>
* <li>unavailable -> readonly</li>
* <li>unavailable -> available</li>
* <li>readonly -> available </li>
* </ul>
* Only tokens that were specified in the arguments are considered.
* This method must be called for every token which terminated.
*
* @param token the token which terminated so some of its rights might
* need to be downgraded.
* @param removedReadRightsTree the rights that were removed from
* {@code readTree} because the specified token was terminated
* @param removedWriteRightsTree the rights that were removed from
* {@code writeTree} because the specified token was terminated
*/
private void scheduleRightDowngrade(
AccessTokenImpl<IDType> token,
RightTreeBuilder removedReadRightsTree,
RightTreeBuilder removedWriteRightsTree) {
if (stateListener == null) {
return;
}
assert mainLock.isHeldByCurrentThread();
AccessRequest<? extends IDType, ? extends HierarchicalRight> request;
Collection<? extends HierarchicalRight> readRights;
Collection<? extends HierarchicalRight> writeRights;
request = token.getRequest();
readRights = request.getReadRights();
writeRights = request.getWriteRights();
Collection<HierarchicalRight> removedReadRights; // Read -> Available
Collection<HierarchicalRight> downgradedWriteRights; // Write -> Read
Collection<HierarchicalRight> removedWriteRights; // Read -> Available
removedReadRights = removedReadRightsTree.getRights();
removedWriteRights = removedWriteRightsTree.getRights();
Iterator<HierarchicalRight> itr;
itr = removedReadRights.iterator();
while (itr.hasNext()) {
HierarchicalRight right = itr.next();
if (writeTree.hasRight(right)) {
itr.remove();
}
}
downgradedWriteRights = CollectionsEx.newHashSet(removedWriteRights.size());
itr = removedWriteRights.iterator();
while (itr.hasNext()) {
HierarchicalRight right = itr.next();
if (readTree.hasRight(right)) {
itr.remove();
downgradedWriteRights.add(right);
}
}
// removedReadRights: Read -> Available
// downgradedWriteRights: Write -> Read
// removedWriteRights: Read -> Available
Set<HierarchicalRight> available;
available = CollectionsEx.newHashSet(readRights.size() + writeRights.size());
Set<HierarchicalRight> readOnly;
readOnly = CollectionsEx.newHashSet(writeRights.size());
addIfHasRight(removedReadRights, readRights, available);
addIfHasRight(removedWriteRights, writeRights, available);
addIfHasRight(downgradedWriteRights, writeRights, readOnly);
scheduleEvents(
Collections.<HierarchicalRight>emptySet(),
readOnly,
available);
}
/**
* Removes the rights associated with the specified token and eventually
* will notify the listener. This method is called right after the specified
* token has terminated.
*
* @param token the token which terminated
*/
private void removeToken(AccessTokenImpl<IDType> token) {
AccessRequest<? extends IDType, ? extends HierarchicalRight> request;
Collection<? extends HierarchicalRight> readRights;
Collection<? extends HierarchicalRight> writeRights;
request = token.getRequest();
readRights = request.getReadRights();
writeRights = request.getWriteRights();
RightTreeBuilder removedReadRightsBuilder = new RightTreeBuilder();
RightTreeBuilder removedWriteRightsBuilder = new RightTreeBuilder();
mainLock.lock();
try {
for (RefList.ElementRef<AccessTokenImpl<IDType>> index: token.getTokenIndexes()) {
index.remove();
}
readTree.cleanupRights(readRights, removedReadRightsBuilder);
writeTree.cleanupRights(writeRights, removedWriteRightsBuilder);
scheduleRightDowngrade(token,
removedReadRightsBuilder,
removedWriteRightsBuilder);
} finally {
mainLock.unlock();
}
assert !mainLock.isHeldByCurrentThread();
dispatchEvents();
}
/**
* Returns a listener for a specified token which will call
* {@link #removeToken(org.jtrim.access.HierarchicalAccessManager.AccessTokenImpl) removeToken}
* after the token has terminated.
*
* @param token the token which will be removed by the returned listener.
* @return the listener which will remove the rights of the specified token
* when that token terminates
*/
private AccessListener getTokenListener(final AccessTokenImpl<IDType> token) {
return new AccessListener() {
@Override
public void onLostAccess() {
removeToken(token);
}
};
}
/**
* Add the rights associated with the specified token to {@code readTree}
* and {@code writeTree}. This method will eventually notify the listener
* if a right has changed state.
*
* @param token the token which rights must be added to the internal right
* trees. This argument is used only so that rights can be associated with
* with the token.
* @param request the right request which was requested by the client
* these rights are associated with the specified token
* @return the references of the rights in the internal right trees of
* the specified tokens. These references must be removed after
* the token terminates.
*/
private Collection<RefList.ElementRef<AccessTokenImpl<IDType>>> addRigths(
AccessTokenImpl<IDType> token,
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
assert mainLock.isHeldByCurrentThread();
Collection<RefList.ElementRef<AccessTokenImpl<IDType>>> result;
result = new LinkedList<>();
Collection<? extends HierarchicalRight> readRights = request.getReadRights();
Collection<? extends HierarchicalRight> writeRights = request.getWriteRights();
Set<HierarchicalRight> newReadRights = CollectionsEx.newHashSet(readRights.size());
Set<HierarchicalRight> newWriteRights = CollectionsEx.newHashSet(writeRights.size());
readTree.addRights(token, readRights, result, newReadRights);
writeTree.addRights(token, writeRights, result, newWriteRights);
if (stateListener != null) {
newReadRights.removeAll(newWriteRights);
scheduleEvents(
newWriteRights,
newReadRights,
Collections.<HierarchicalRight>emptySet());
}
return result;
}
/**
* This method returns the tokens conflicting with the specified request.
*
* @param request the request which is checked for conflicts
* @param result the conflicting tokens will be added to this collection
*/
private void getBlockingTokensList(
AccessRequest<? extends IDType, ? extends HierarchicalRight> request,
Collection<? super AccessTokenImpl<IDType>> result) {
assert mainLock.isHeldByCurrentThread();
Collection<? extends HierarchicalRight> readRights = request.getReadRights();
Collection<? extends HierarchicalRight> writeRights = request.getWriteRights();
getBlockingTokensList(readRights, writeRights, result);
}
/**
* This method returns the tokens conflicting with the specified request.
*
* @param requestedReadRights the requested read rights checked for
* conflicts
* @param requestedWriteRights the requested write rights checked for
* conflicts
* @param result the conflicting tokens will be added to this collection
*/
private void getBlockingTokensList(
Collection<? extends HierarchicalRight> requestedReadRights,
Collection<? extends HierarchicalRight> requestedWriteRights,
Collection<? super AccessTokenImpl<IDType>> result) {
assert mainLock.isHeldByCurrentThread();
readTree.getBlockingTokens(requestedWriteRights, result);
writeTree.getBlockingTokens(requestedReadRights, result);
writeTree.getBlockingTokens(requestedWriteRights, result);
}
/**
* {@inheritDoc }
*/
@Override
public Collection<AccessToken<IDType>> getBlockingTokens(
Collection<? extends HierarchicalRight> requestedReadRights,
Collection<? extends HierarchicalRight> requestedWriteRights) {
List<AccessTokenImpl<IDType>> blockingTokens = new LinkedList<>();
mainLock.lock();
try {
getBlockingTokensList(requestedReadRights, requestedWriteRights,
blockingTokens);
} finally {
mainLock.unlock();
}
return getUniqueSharedTokens(blockingTokens);
}
/**
* {@inheritDoc }
*/
@Override
public boolean isAvailable(
Collection<? extends HierarchicalRight> requestedReadRights,
Collection<? extends HierarchicalRight> requestedWriteRights) {
mainLock.lock();
try {
if (readTree.hasBlockingTokens(requestedWriteRights)) {
return true;
}
if (writeTree.hasBlockingTokens(requestedReadRights)) {
return true;
}
if (writeTree.hasBlockingTokens(requestedWriteRights)) {
return true;
}
} finally {
mainLock.unlock();
}
return false;
}
/**
* {@inheritDoc }
*/
@Override
public AccessResult<IDType> tryGetAccess(
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
return tryGetAccess(taskExecutor, request);
}
/**
* {@inheritDoc }
*/
@Override
public AccessResult<IDType> tryGetAccess(
ExecutorService executor,
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
return tryGetAccess((Executor)executor, request);
}
private AccessResult<IDType> tryGetAccess(
Executor executor,
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
AccessTokenImpl<IDType> token;
token = new AccessTokenImpl<>(executor, request);
AccessListener tokenListener = getTokenListener(token);
List<AccessTokenImpl<IDType>> blockingTokens = new LinkedList<>();
mainLock.lock();
try {
getBlockingTokensList(request, blockingTokens);
if (blockingTokens.isEmpty()) {
Collection<RefList.ElementRef<AccessTokenImpl<IDType>>> tokenIndexes;
tokenIndexes = addRigths(token, request);
token.init(tokenListener, tokenIndexes);
}
} finally {
mainLock.unlock();
}
assert !mainLock.isHeldByCurrentThread();
dispatchEvents();
if (blockingTokens.isEmpty()) {
token.setSharedToken(token);
return new AccessResult<>(token);
}
else {
return new AccessResult<>(getUniqueSharedTokens(blockingTokens));
}
}
/**
* {@inheritDoc }
*/
@Override
public AccessResult<IDType> getScheduledAccess(
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
return getScheduledAccess(taskExecutor, request);
}
/**
* {@inheritDoc }
*/
@Override
public AccessResult<IDType> getScheduledAccess(
ExecutorService executor,
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
return getScheduledAccess((Executor)executor, request);
}
private AccessResult<IDType> getScheduledAccess(
Executor executor,
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
AccessTokenImpl<IDType> token;
token = new AccessTokenImpl<>(executor, request);
AccessListener tokenListener = getTokenListener(token);
List<AccessToken<IDType>> blockingTokens = new LinkedList<>();
mainLock.lock();
try {
getBlockingTokensList(request, blockingTokens);
Collection<RefList.ElementRef<AccessTokenImpl<IDType>>> tokenIndexes;
tokenIndexes = addRigths(token, request);
token.init(tokenListener, tokenIndexes);
} finally {
mainLock.unlock();
}
assert !mainLock.isHeldByCurrentThread();
dispatchEvents();
Set<AccessToken<IDType>> blockingTokenSet = createSet(blockingTokens);
AccessToken<IDType> scheduledToken;
scheduledToken = new ScheduledAccessToken<>(token, blockingTokenSet);
token.setSharedToken(scheduledToken);
return new AccessResult<>(scheduledToken, blockingTokenSet);
}
/**
* This tree represents a collection of rights. The graph should be
* considered to be a directed graph were edges point from the parent
* to children. A path in this graph represents a hierarchical right where
* the edges are the parts of this hierarchical right in order.
* Vertices of the graph contains tokens and these tokens mean that
* the right up to the point of this vertex is associated with these
* tokens. Note that since these rights are hierarchical this implies that
* the token also represents all the subrights (even if subrights
* do not contain the token explicitly).
*/
private static class AccessTree<TokenType extends AccessToken<?>> {
private final RefList<TokenType> tokens;
private final Map<Object, AccessTree<TokenType>> subTrees; // the edges
public AccessTree() {
this.subTrees = new HashMap<>();
this.tokens = new RefLinkedList<>();
}
private AccessTree<TokenType> getSubTree(Object key) {
AccessTree<TokenType> result = subTrees.get(key);
if (result == null) {
result = new AccessTree<>();
subTrees.put(key, result);
}
return result;
}
private boolean isEmpty() {
if (!tokens.isEmpty()) {
return false;
}
for (AccessTree<TokenType> subTree: subTrees.values()) {
if (!subTree.isEmpty()) {
return false;
}
}
return true;
}
/**
* Removes all of this tree's subtrees which do not contain tokens.
* This means that after this call every leaf element of this graph
* will contain at least a single token unless there no tokens in this
* tree at all. In which case every subtree will be removed:
* {@code subTrees.size()} will return 0.
* <P>
* This method will also return all the modifications it did. That
* is it will return the rights which were removed from this tree.
* <P>
* A right is not considered to part of the tree if there are no tokens
* in its vertex. (Notice that actually a vertex defines a right:
* the edges up to the vertex)
*
* @param treeRight the removed rights will be prefixed with this
* hierarchical right
* @param modifications the modifications will be added to this
* builder
*/
private void cleanupTree(
HierarchicalRight treeRight,
RightTreeBuilder modifications) {
Iterator<Map.Entry<Object, AccessTree<TokenType>>> itr;
itr = subTrees.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<Object, AccessTree<TokenType>> sub;
sub = itr.next();
if (sub.getValue().isEmpty()) {
HierarchicalRight right;
right = HierarchicalRight.createWithParent(
treeRight, sub.getKey());
modifications.addRight(right);
itr.remove();
}
}
}
/**
* Finds a subtree of this tree specified by a hierarchical right
* and will clean up that tree: {@link #cleanupTree cleanupTree}.
*
* @param right the specified subtree to be cleaned
* @param modifications the rights that were removed from
* this tree (those no longer had any tokens) will be added to
* this builder
*/
public void cleanupRight(
HierarchicalRight right,
RightTreeBuilder modifications) {
AccessTree<TokenType> previousTree = this;
AccessTree<TokenType> currentTree = this;
List<Object> rights = right.getRights();
int rightIndex = 0;
for (Object subRight: rights) {
previousTree = currentTree;
currentTree = currentTree.subTrees.get(subRight);
rightIndex++;
if (currentTree == null) {
break;
}
}
if (currentTree != null) {
HierarchicalRight treeRight;
treeRight = right.getParentRight(rights.size() - rightIndex);
previousTree.cleanupTree(treeRight, modifications);
}
}
public void cleanupRights(
Collection<? extends HierarchicalRight> rights,
RightTreeBuilder modifications) {
for (HierarchicalRight right: rights) {
cleanupRight(right, modifications);
}
}
public void getBlockingTokens(
Collection<? extends HierarchicalRight> rights,
Collection<? super TokenType> result) {
for (HierarchicalRight right: rights) {
getBlockingTokens(right, result);
}
}
public boolean hasBlockingTokens(
Collection<? extends HierarchicalRight> rights) {
for (HierarchicalRight right: rights) {
if (hasBlockingTokens(right)) {
return true;
}
}
return false;
}
/**
* Returns the tokens that are conflicting with the specified rights
* in this tree.
*
* @param right the right checked for conflicts
* @param result conflicting tokens will be added to this collection
*/
public void getBlockingTokens(
HierarchicalRight right,
Collection<? super TokenType> result) {
AccessTree<TokenType> currentTree = this;
for (Object subRight: right.getRights()) {
result.addAll(currentTree.tokens);
currentTree = currentTree.subTrees.get(subRight);
if (currentTree == null) {
break;
}
}
if (currentTree != null) {
result.addAll(currentTree.tokens);
}
}
/**
* Returns {@code true} if there are conflicting tokens with the
* specified rights in this tree.
*
* @param right the right checked for conflicts
* @return {@code true} if there is at least one conflicting token with
* the given right, {@code false} otherwise
*/
public boolean hasBlockingTokens(HierarchicalRight right) {
AccessTree<TokenType> currentTree = this;
for (Object subRight: right.getRights()) {
if (!currentTree.tokens.isEmpty()) {
return true;
}
currentTree = currentTree.subTrees.get(subRight);
if (currentTree == null) {
return false;
}
}
return !currentTree.tokens.isEmpty();
}
public void addRights(
TokenType token,
Collection<? extends HierarchicalRight> rights,
Collection<RefList.ElementRef<TokenType>> resultRefs,
Collection<? super HierarchicalRight> modifications) {
for (HierarchicalRight right: rights) {
addRight(token, right, resultRefs, modifications);
}
}
/**
* Adds a specific right to this tree.
*
* @param token the token which is associated with the specified rights
* @param right the right to be added to this tree
* @param resultRefs the references which can be removed
* to remove the references of the specified token added to this tree
* @param modifications the specified right will be added to this
* collection if adding the specified right required a new vertex
* to be created
*/
public void addRight(
TokenType token,
HierarchicalRight right,
Collection<RefList.ElementRef<TokenType>> resultRefs,
Collection<? super HierarchicalRight> modifications) {
AccessTree<TokenType> currentTree = this;
for (Object subRight: right.getRights()) {
currentTree = currentTree.getSubTree(subRight);
}
if (currentTree.tokens.isEmpty()) {
modifications.add(right);
}
resultRefs.add(currentTree.tokens.addLastGetReference(token));
}
/**
* Checks whether the specified right is contained (or one of its parent
* right is contained) in this tree or not.
*
* @param right the right to be checked
* @return {@code true} if the specified right is in the tree.
* {@code false} otherwise
*/
public boolean hasRight(HierarchicalRight right) {
List<Object> rightList = right.getRights();
AccessTree<TokenType> currentTree = this;
for (Object rightElement: rightList) {
if (!currentTree.tokens.isEmpty()) {
return true;
}
currentTree = currentTree.subTrees.get(rightElement);
if (currentTree == null) {
return false;
}
}
return currentTree != null
? !currentTree.tokens.isEmpty()
: false;
}
/**
* Returns all the rights contained in this tree.
* The rights will be prefixed with the specified parent rights.
*
* @param parent the prefix of the returned rights.
* @param result the (prefixed) rights will be added to this collection.
* @return the right represented by {@code parent}. This is simply
* a performance hack, so we do not always need to create new arrays.
*/
public HierarchicalRight getRights(Object[] parents,
Collection<HierarchicalRight> result) {
HierarchicalRight thisRight;
if (!subTrees.isEmpty()) {
Object[] rightList = new Object[parents.length + 1];
System.arraycopy(parents, 0, rightList, 0, parents.length);
HierarchicalRight aChildRight = null;
int lastIndex = parents.length;
for (Map.Entry<Object, AccessTree<TokenType>> treeEdge:
subTrees.entrySet()) {
rightList[lastIndex] = treeEdge.getKey();
aChildRight = treeEdge.getValue().getRights(rightList, result);
}
// Note that subTrees is not empty, so aChildRight != null
thisRight = aChildRight.getParentRight();
}
else {
thisRight = HierarchicalRight.create(parents);
}
if (!tokens.isEmpty()) {
result.add(thisRight);
}
return thisRight;
}
/**
* Returns all the rights contained in this tree.
*
* @param result the rights will be added to this collection.
*/
public void getRights(Collection<HierarchicalRight> result) {
getRights(new Object[0], result);
}
}
/**
* The access token which stores references of the tokens in
* {@code readTree} and {@code writeTree}, so these references can
* be removed after this token terminates. This implementation
* simply relies on the {@link GenericAccessToken}.
*/
private static class AccessTokenImpl<IDType> extends DelegatedAccessToken<IDType> {
private final AccessRequest<? extends IDType, ? extends HierarchicalRight> request;
private List<RefList.ElementRef<AccessTokenImpl<IDType>>> tokenIndexes;
private volatile AccessToken<IDType> sharedToken;
/**
* Initializes this token with a {@code null} shared token and an
* empty list of token references in the right trees.
* <P>
* {@link #setSharedToken(org.jtrim.access.AccessToken) setSharedToken}
* and
* {@link #init(org.jtrim.access.AccessListener, java.util.Collection) init}
* must be called before returning this token to the client.
*
* @param taskExecutor the executor to which tasks will be submitted to.
* @param request the right request which requested this token to
* be created
*/
public AccessTokenImpl(
Executor taskExecutor,
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
super(new GenericAccessToken<>(request.getRequestID(),
taskExecutor));
this.request = request;
this.tokenIndexes = Collections.emptyList();
this.sharedToken = null;
}
/**
* Returns the reference of the token which was returned to the user.
*
* @return the shared token
*/
public AccessToken<IDType> getSharedToken() {
return sharedToken;
}
/**
* Sets the token which was returned to the user. This is important
* because when conflicting tokens need to be returned we must provide
* the same tokens that were returned to the user. This is the case
* with scheduled tokens where we do not return this token but
* wrap it with a {@link ScheduledAccessToken}. If we were to return
* this instance as conflicting token, the client could abuse that
* reference by submitting task to it circumventing the protection
* of {@code ScheduledAccessToken}.
* <P>
* This method must be called exactly once before returning the
* requested token to the client.
*
* @param sharedToken the token actually returned to the client
*/
public void setSharedToken(AccessToken<IDType> sharedToken) {
assert this.sharedToken == null && sharedToken != null;
this.sharedToken = sharedToken;
}
/**
* Sets the access listeners and the references to this token in the
* right trees.
* <P>
* This method must be called exactly once before returning the
* requested token to the client.
*
* @param listener the listener which will be notified when this
* token terminates
* @param tokenIndexes the references to this token in the right trees.
*/
public void init(
AccessListener listener,
Collection<RefList.ElementRef<AccessTokenImpl<IDType>>> tokenIndexes) {
if (tokenIndexes != null) {
this.tokenIndexes = new ArrayList<>(tokenIndexes);
}
if (listener != null) {
wrappedToken.addAccessListener(listener);
}
}
public AccessRequest<? extends IDType, ? extends HierarchicalRight> getRequest() {
return request;
}
public List<RefList.ElementRef<AccessTokenImpl<IDType>>> getTokenIndexes() {
return tokenIndexes;
}
}
/**
* Stores a collection of hierarchical rights. This class was designed to
* collect some hierarchical rights then return the minimal number of rights
* the represents these rights and does not represent other rights.
* So adding a subright of a right that is already contained in this right
* collection must not modify the set of rights stored and adding
* a new right must remove any previously stored subright from this tree.
*/
private static class RightTreeBuilder {
private final RightTree root;
private boolean empty; // true if no right is stored in this tree
private boolean completeTree; // true if every right is part of this tree
// The expression "!empy || !completeTree" must always be true.
// If either "empty" or "completeTree" is true, "root" is ignored.
public RightTreeBuilder() {
this.root = new RightTree();
this.completeTree = false;
this.empty = true;
}
public void addRights(Collection<? extends HierarchicalRight> rights) {
for (HierarchicalRight right: rights) {
addRight(right);
}
}
public void addRight(HierarchicalRight right) {
if (completeTree) {
return;
}
if (!right.isUniversal()) {
root.addRight(right);
}
else {
completeTree = true;
root.clearTree();
}
empty = false;
}
public RightTree getTree() {
return empty ? null : root;
}
public boolean hasRight(HierarchicalRight right) {
return completeTree
? true
: root.hasRight(right);
}
public Collection<HierarchicalRight> getRights() {
return completeTree
? Collections.<HierarchicalRight>emptySet()
: root.getRights();
}
}
/**
* This class actually stores the rights of {@link RightTreeBuilder}.
* This implementation similar to {@link AccessTree} but is more simple
* and there are no token references; an existence of leaf a vertex in the
* graph implies the existence of the hierarchical right and its subrights
* defined by this vertex.
*/
private static class RightTree {
private final Map<Object, RightTree> children;
public RightTree() {
this.children = new HashMap<>();
}
private void getRights(
Object[] parentList,
List<HierarchicalRight> result) {
if (children.isEmpty()) {
result.add(HierarchicalRight.create(parentList));
return;
}
Object[] nextParentList;
nextParentList = Arrays.copyOf(parentList, parentList.length + 1);
for (Map.Entry<Object, RightTree> child: children.entrySet()) {
nextParentList[nextParentList.length - 1] = child.getKey();
child.getValue().getRights(nextParentList, result);
}
}
public Collection<HierarchicalRight> getRights() {
if (children.isEmpty()) {
return Collections.emptySet();
}
List<HierarchicalRight> resultList = new LinkedList<>();
getRights(ArraysEx.EMPTY_OBJECT_ARRAY, resultList);
return resultList;
}
private RightTree getSubTree(Object key) {
RightTree result = children.get(key);
if (result == null) {
result = new RightTree();
children.put(key, result);
}
return result;
}
public void clearTree() {
children.clear();
}
public void addRight(HierarchicalRight right) {
List<Object> rights = right.getRights();
Object firstRight = rights.get(0);
RightTree currentTree = children.get(firstRight);
if (currentTree == null) {
// Create a new path
currentTree = new RightTree();
children.put(firstRight, currentTree);
for (Object subRight: rights.subList(1, rights.size())) {
currentTree = currentTree.getSubTree(subRight);
}
}
else {
// Cut path if necessary
for (Object subRight: rights.subList(1, rights.size())) {
currentTree = currentTree.children.get(subRight);
if (currentTree == null) {
break;
}
}
if (currentTree != null) {
currentTree.clearTree();
}
}
}
public boolean hasRight(HierarchicalRight right) {
if (children.isEmpty()) {
return false;
}
RightTree currentTree = this;
List<Object> rightList = right.getRights();
for (Object rightElement: rightList) {
// The parent right is contained in this tree
if (currentTree.children.isEmpty()) {
return true;
}
currentTree = currentTree.children.get(rightElement);
if (currentTree == null) {
return false;
}
}
return currentTree.children.isEmpty();
}
}
/**
* Returns the rights that are currently in use: there are not terminated
* {@link AccessToken AccessTokens} associated with these rights.
* <P>
* This method was designed for monitoring only and cannot be used
* for synchronization control.
* <P>
* Note this method will return a disjunct sets for the read and write
* rights.
*
* <h5>Thread safety</h5>
* Note that although this method is thread-safe, the rights may change
* right after this method returns, so they may not be up-to-date.
* <h6>Synchronization transparency</h6>
* This method is <I>synchronization transparent</I>.
*
* @param readRights the rights that are currently used for "reading" will
* be added to this collection. These rights can be requested for reading.
* No rights will be added more than once. This argument cannot be
* {@code null}.
* @param writeRights the rights that are currently used for "writing"
* (i.e.: they are used exclusively) will be added to this collection.
* No rights will be added more than once.
*
* @throws NullPointerException thrown if on of the arguments is
* {@code null}
*/
public void getRights(
Collection<HierarchicalRight> readRights,
Collection<HierarchicalRight> writeRights) {
ExceptionHelper.checkNotNullArgument(readRights, "readRights");
ExceptionHelper.checkNotNullArgument(writeRights, "writeRights");
mainLock.lock();
try {
readTree.getRights(readRights);
writeTree.getRights(writeRights);
} finally {
mainLock.unlock();
}
}
/**
* Returns the string representation of this access manager in no
* particular format. The string representation will contain the rights
* currently in use.
* <P>
* This method is intended to be used for debugging only.
*
* @return the string representation of this object in no particular format.
* This method never returns {@code null}.
*/
@Override
public String toString() {
List<HierarchicalRight> readRights = new LinkedList<>();
List<HierarchicalRight> writeRights = new LinkedList<>();
getRights(readRights, writeRights);
return "HierarchicalAccessManager{"
+ "read rights=" + readRights
+ ", write rights=" + writeRights + '}';
}
}
| jtrim-gui/src/main/java/org/jtrim/access/HierarchicalAccessManager.java | package org.jtrim.access;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import org.jtrim.collections.ArraysEx;
import org.jtrim.collections.CollectionsEx;
import org.jtrim.collections.RefLinkedList;
import org.jtrim.collections.RefList;
import org.jtrim.concurrent.TaskScheduler;
import org.jtrim.utils.ExceptionHelper;
/**
* An implementation of {@code AccessManager} which can manage
* {@link HierarchicalRight hierarchical rights}.
*
* <h3>Rights</h3>
* This implementation uses hierarchical rights so requesting a right will
* need that subrights are also available for the requested use. The value
* {@code null} is not considered to be a valid hierarchical right.
* See {@link HierarchicalRight} for further details on hierarchical rights.
*
* <h3>Events</h3>
* This implementation can notify clients if a right becomes available or
* unavailable. These notification events are submitted to a user specified
* {@link java.util.concurrent.Executor Executor}, so clients can define
* where the events execute but cannot define on what thread these events
* are submitted to this {@code Executor}. They maybe scheduled on the thread
* used by the {@code Executor} of the {@link AccessToken AccessTokens} or
* in the call stack of caller of a methods of this class. Although is not
* possible to determine which event is submitted on which thread, these events
* will be submitted in the order they occurred.
* <P>
* Note that the listener may not be notified of some of the changes in the
* state of a right if states change fast. That is if a right enters a specific
* state previous (not yet reported) changes in the state is not required to
* be reported by this implementation. For example if a certain right becomes
* {@link AccessState#UNAVAILABLE unavailable} it may have been already in
* lots of previous states not reported.
* <P>
* When an event is reported, listeners must assume that every subright of
* the specified right is in the reported state and the state of those
* subrights will not be reported.
* <P>
* Note that no events will be reported before a new {@code AccessToken} is
* requested so it is possible to initialize the specified listener
* with the newly created instance of this {@code AccessManager} immediately
* after constructing the {@code AccessManager}.
*
* <h3>Thread safety</h3>
* This class is thread-safe without any further synchronization. Note however
* that although thread-safe, this implementation will not scale well with
* multiple processors.
* <h4>Synchronization transparency</h4>
* The methods of this class are not <I>synchronization transparent</I>
* because they may notify the specified
* {@link AccessStateListener right state listener}. In case
* scheduling the events of the changes in right states is
* <I>synchronization transparent</I> then the methods of this class are also
* <I>synchronization transparent</I>. Note that in most case you cannot
* assume this and can only rely on that they do not block indefinitely.
*
* @param <IDType> the type of the request ID (see
* {@link AccessRequest#getRequestID()})
*
* @see HierarchicalRight
* @author Kelemen Attila
*/
public final class HierarchicalAccessManager<IDType>
implements
AccessManager<IDType, HierarchicalRight> {
private final ReentrantLock mainLock;
private final Executor taskExecutor;
private final AccessTree<AccessTokenImpl<IDType>> readTree;
private final AccessTree<AccessTokenImpl<IDType>> writeTree;
private final AtomicReference<ListenerRef> stateListenerRef;
/**
* Creates a new {@code HierarchicalAccessManager} which will not notify
* clients of changes in the states of rights. The instance created
* by this constructor is slightly more efficient than using
* {@link #HierarchicalAccessManager(java.util.concurrent.Executor, java.util.concurrent.Executor, org.jtrim.access.AccessStateListener) HierarchicalAccessManager(Executor, Executor, AccessStateListener)}
* When creating a new instance all rights are considered to be in the
* {@link AccessState#AVAILABLE available} state. Rights will remain in this
* state until a new {@code AccessToken} is requested.
* <P>
* Note that the right state listener can be set later by the
* {@link #setAccessStateListener(AccessStateListener) setAccessStateListener}
* method.
*
* @param taskExecutor the default {@code Executor} of
* {@link AccessToken AccessTokens} created by this {@code AccessManager}.
* Tasks submitted to these {@code AccessToken}s will execute on this
* {@code Executor}. This argument cannot be {@code null}.
*
* @throws NullPointerException thrown if the specified {@code Executor}
* is {@code null}
*/
public HierarchicalAccessManager(Executor taskExecutor) {
ExceptionHelper.checkNotNullArgument(taskExecutor, "taskExecutor");
this.mainLock = new ReentrantLock();
this.stateListenerRef = new AtomicReference<>(null);
this.taskExecutor = taskExecutor;
this.readTree = new AccessTree<>();
this.writeTree = new AccessTree<>();
}
/**
* Creates a new {@code HierarchicalAccessManager} which will notify
* clients of changes in the states of rights.
* When creating a new instance all rights are considered to be in the
* {@link AccessState#AVAILABLE available} state. Rights will remain in this
* state until a new {@code AccessToken} is requested and the listener
* will not be notified until such request was made.
*
* @param taskExecutor the {@code Executor} of the
* {@link AccessToken AccessTokens} created by this {@code AccessManager}.
* Tasks submitted to these {@code AccessToken}s will execute on this
* {@code Executor}. This argument cannot be {@code null}.
* @param eventExecutor the {@code Executor} to which events of changes in
* the state of rights are submitted to. This argument cannot be
* {@code null}.
* @param stateListener the listener which will be notified of changes in
* the state of rights. This argument cannot be {@code null}.
*
* @throws NullPointerException thrown if any of the arguments is
* {@code null}
*/
public HierarchicalAccessManager(
Executor taskExecutor,
Executor eventExecutor,
AccessStateListener<HierarchicalRight> stateListener) {
ExceptionHelper.checkNotNullArgument(taskExecutor, "taskExecutor");
this.mainLock = new ReentrantLock();
this.stateListenerRef = new AtomicReference<>(new ListenerRef(eventExecutor, stateListener));
this.taskExecutor = taskExecutor;
this.readTree = new AccessTree<>();
this.writeTree = new AccessTree<>();
}
/**
* Sets the listener which is to be notified when a state of right changes.
* That is, whenever a certain becomes available, read-only or not
* available.
* <P>
* This method may only be called at most once and only if the state
* listener has not been set at construction time.
*
* @param eventExecutor the {@code Executor} to which events of changes in
* the state of rights are submitted to. This argument cannot be
* {@code null}.
* @param stateListener the listener which will be notified of changes in
* the state of rights. This argument cannot be {@code null}.
*
* @throws NullPointerException thrown if any of the arguments is
* {@code null}
*/
public void setAccessStateListener(
Executor eventExecutor,
AccessStateListener<HierarchicalRight> stateListener) {
ListenerRef newStateListener = new ListenerRef(eventExecutor, stateListener);
if (!stateListenerRef.compareAndSet(null, newStateListener)) {
throw new IllegalStateException("The state listener was already set.");
}
}
/**
* Returns the shared tokens of the specified tokens without returning
* the same token twice (using "==" for comparison).
*
* @param <V> the type of the request ID
* @param tokens the tokens of which the shared tokens are to be returned.
* This argument cannot be {@code null}.
*/
private static <V> Set<AccessToken<V>> getUniqueSharedTokens(
Collection<AccessTokenImpl<V>> tokens) {
Set<AccessToken<V>> result = CollectionsEx.newIdentityHashSet(tokens.size());
for (AccessTokenImpl<V> token: tokens) {
AccessToken<V> sharedToken = token.getSharedToken();
if (sharedToken != null) {
result.add(sharedToken);
}
}
return result;
}
private static <V> Set<V> createSet(Collection<? extends V> collection) {
Set<V> result = CollectionsEx.newIdentityHashSet(collection.size());
result.addAll(collection);
return result;
}
/**
* Collects the rights which can be found in the {@code source} collection
* considering subrights as well.
*
* @param source the rights in which the new rights are to be searched
* @param toAdd the rights to be searched in {@code source}
* @param result the found rights will be added to this set
*/
private static void addIfHasRight(
Collection<? extends HierarchicalRight> source,
Collection<? extends HierarchicalRight> toAdd,
Set<? super HierarchicalRight> result) {
RightTreeBuilder rightTree = new RightTreeBuilder();
rightTree.addRights(source);
for (HierarchicalRight right: toAdd) {
if (rightTree.hasRight(right)) {
result.add(right);
}
}
}
/**
* Schedules all the events of the specified states.
* This method must not be called if the events are not requested to be
* forwarded by the client.
* <P>
* Events must be {@link #dispatchEvents() dispatched} after this call.
*/
private void scheduleEvents(
Collection<? extends HierarchicalRight> unavailable,
Collection<? extends HierarchicalRight> readOnly,
Collection<? extends HierarchicalRight> available) {
ListenerRef listenerRef = stateListenerRef.get();
assert listenerRef != null;
if (unavailable.isEmpty() && readOnly.isEmpty() && available.isEmpty()) {
return;
}
final HierarchicalAccessManager<?> thisManager = this;
final AccessStateListener<HierarchicalRight> stateListener = listenerRef.getStateListener();
List<Runnable> tasks = new LinkedList<>();
for (final HierarchicalRight right: unavailable) {
tasks.add(new Runnable() {
@Override
public void run() {
stateListener.onEnterState(thisManager, right, AccessState.UNAVAILABLE);
}
});
}
for (final HierarchicalRight right: readOnly) {
tasks.add(new Runnable() {
@Override
public void run() {
stateListener.onEnterState(thisManager, right, AccessState.READONLY);
}
});
}
for (final HierarchicalRight right: available) {
tasks.add(new Runnable() {
@Override
public void run() {
stateListener.onEnterState(thisManager, right, AccessState.AVAILABLE);
}
});
}
listenerRef.getTaskScheduler().scheduleTasks(tasks);
}
/**
* Submits state change events if the client requested to do so.
*/
private void dispatchEvents() {
assert !mainLock.isHeldByCurrentThread();
ListenerRef listenerRef = stateListenerRef.get();
if (listenerRef != null) {
listenerRef.getTaskScheduler().dispatchTasks();
}
}
/**
* Schedules events for right downgrades. That is:
* <ul>
* <li>unavailable -> readonly</li>
* <li>unavailable -> available</li>
* <li>readonly -> available </li>
* </ul>
* Only tokens that were specified in the arguments are considered.
* This method must be called for every token which terminated.
*
* @param token the token which terminated so some of its rights might
* need to be downgraded.
* @param removedReadRightsTree the rights that were removed from
* {@code readTree} because the specified token was terminated
* @param removedWriteRightsTree the rights that were removed from
* {@code writeTree} because the specified token was terminated
*/
private void scheduleRightDowngrade(
AccessTokenImpl<IDType> token,
RightTreeBuilder removedReadRightsTree,
RightTreeBuilder removedWriteRightsTree) {
if (stateListenerRef.get() == null) {
return;
}
assert mainLock.isHeldByCurrentThread();
AccessRequest<? extends IDType, ? extends HierarchicalRight> request;
Collection<? extends HierarchicalRight> readRights;
Collection<? extends HierarchicalRight> writeRights;
request = token.getRequest();
readRights = request.getReadRights();
writeRights = request.getWriteRights();
Collection<HierarchicalRight> removedReadRights; // Read -> Available
Collection<HierarchicalRight> downgradedWriteRights; // Write -> Read
Collection<HierarchicalRight> removedWriteRights; // Read -> Available
removedReadRights = removedReadRightsTree.getRights();
removedWriteRights = removedWriteRightsTree.getRights();
Iterator<HierarchicalRight> itr;
itr = removedReadRights.iterator();
while (itr.hasNext()) {
HierarchicalRight right = itr.next();
if (writeTree.hasRight(right)) {
itr.remove();
}
}
downgradedWriteRights = CollectionsEx.newHashSet(removedWriteRights.size());
itr = removedWriteRights.iterator();
while (itr.hasNext()) {
HierarchicalRight right = itr.next();
if (readTree.hasRight(right)) {
itr.remove();
downgradedWriteRights.add(right);
}
}
// removedReadRights: Read -> Available
// downgradedWriteRights: Write -> Read
// removedWriteRights: Read -> Available
Set<HierarchicalRight> available;
available = CollectionsEx.newHashSet(readRights.size() + writeRights.size());
Set<HierarchicalRight> readOnly;
readOnly = CollectionsEx.newHashSet(writeRights.size());
addIfHasRight(removedReadRights, readRights, available);
addIfHasRight(removedWriteRights, writeRights, available);
addIfHasRight(downgradedWriteRights, writeRights, readOnly);
scheduleEvents(
Collections.<HierarchicalRight>emptySet(),
readOnly,
available);
}
/**
* Removes the rights associated with the specified token and eventually
* will notify the listener. This method is called right after the specified
* token has terminated.
*
* @param token the token which terminated
*/
private void removeToken(AccessTokenImpl<IDType> token) {
AccessRequest<? extends IDType, ? extends HierarchicalRight> request;
Collection<? extends HierarchicalRight> readRights;
Collection<? extends HierarchicalRight> writeRights;
request = token.getRequest();
readRights = request.getReadRights();
writeRights = request.getWriteRights();
RightTreeBuilder removedReadRightsBuilder = new RightTreeBuilder();
RightTreeBuilder removedWriteRightsBuilder = new RightTreeBuilder();
mainLock.lock();
try {
for (RefList.ElementRef<AccessTokenImpl<IDType>> index: token.getTokenIndexes()) {
index.remove();
}
readTree.cleanupRights(readRights, removedReadRightsBuilder);
writeTree.cleanupRights(writeRights, removedWriteRightsBuilder);
scheduleRightDowngrade(token,
removedReadRightsBuilder,
removedWriteRightsBuilder);
} finally {
mainLock.unlock();
}
assert !mainLock.isHeldByCurrentThread();
dispatchEvents();
}
/**
* Returns a listener for a specified token which will call
* {@link #removeToken(org.jtrim.access.HierarchicalAccessManager.AccessTokenImpl) removeToken}
* after the token has terminated.
*
* @param token the token which will be removed by the returned listener.
* @return the listener which will remove the rights of the specified token
* when that token terminates
*/
private AccessListener getTokenListener(final AccessTokenImpl<IDType> token) {
return new AccessListener() {
@Override
public void onLostAccess() {
removeToken(token);
}
};
}
/**
* Add the rights associated with the specified token to {@code readTree}
* and {@code writeTree}. This method will eventually notify the listener
* if a right has changed state.
*
* @param token the token which rights must be added to the internal right
* trees. This argument is used only so that rights can be associated with
* with the token.
* @param request the right request which was requested by the client
* these rights are associated with the specified token
* @return the references of the rights in the internal right trees of
* the specified tokens. These references must be removed after
* the token terminates.
*/
private Collection<RefList.ElementRef<AccessTokenImpl<IDType>>> addRigths(
AccessTokenImpl<IDType> token,
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
assert mainLock.isHeldByCurrentThread();
Collection<RefList.ElementRef<AccessTokenImpl<IDType>>> result;
result = new LinkedList<>();
Collection<? extends HierarchicalRight> readRights = request.getReadRights();
Collection<? extends HierarchicalRight> writeRights = request.getWriteRights();
Set<HierarchicalRight> newReadRights = CollectionsEx.newHashSet(readRights.size());
Set<HierarchicalRight> newWriteRights = CollectionsEx.newHashSet(writeRights.size());
readTree.addRights(token, readRights, result, newReadRights);
writeTree.addRights(token, writeRights, result, newWriteRights);
if (stateListenerRef.get() != null) {
newReadRights.removeAll(newWriteRights);
scheduleEvents(
newWriteRights,
newReadRights,
Collections.<HierarchicalRight>emptySet());
}
return result;
}
/**
* This method returns the tokens conflicting with the specified request.
*
* @param request the request which is checked for conflicts
* @param result the conflicting tokens will be added to this collection
*/
private void getBlockingTokensList(
AccessRequest<? extends IDType, ? extends HierarchicalRight> request,
Collection<? super AccessTokenImpl<IDType>> result) {
assert mainLock.isHeldByCurrentThread();
Collection<? extends HierarchicalRight> readRights = request.getReadRights();
Collection<? extends HierarchicalRight> writeRights = request.getWriteRights();
getBlockingTokensList(readRights, writeRights, result);
}
/**
* This method returns the tokens conflicting with the specified request.
*
* @param requestedReadRights the requested read rights checked for
* conflicts
* @param requestedWriteRights the requested write rights checked for
* conflicts
* @param result the conflicting tokens will be added to this collection
*/
private void getBlockingTokensList(
Collection<? extends HierarchicalRight> requestedReadRights,
Collection<? extends HierarchicalRight> requestedWriteRights,
Collection<? super AccessTokenImpl<IDType>> result) {
assert mainLock.isHeldByCurrentThread();
readTree.getBlockingTokens(requestedWriteRights, result);
writeTree.getBlockingTokens(requestedReadRights, result);
writeTree.getBlockingTokens(requestedWriteRights, result);
}
/**
* {@inheritDoc }
*/
@Override
public Collection<AccessToken<IDType>> getBlockingTokens(
Collection<? extends HierarchicalRight> requestedReadRights,
Collection<? extends HierarchicalRight> requestedWriteRights) {
List<AccessTokenImpl<IDType>> blockingTokens = new LinkedList<>();
mainLock.lock();
try {
getBlockingTokensList(requestedReadRights, requestedWriteRights,
blockingTokens);
} finally {
mainLock.unlock();
}
return getUniqueSharedTokens(blockingTokens);
}
/**
* {@inheritDoc }
*/
@Override
public boolean isAvailable(
Collection<? extends HierarchicalRight> requestedReadRights,
Collection<? extends HierarchicalRight> requestedWriteRights) {
mainLock.lock();
try {
if (readTree.hasBlockingTokens(requestedWriteRights)) {
return true;
}
if (writeTree.hasBlockingTokens(requestedReadRights)) {
return true;
}
if (writeTree.hasBlockingTokens(requestedWriteRights)) {
return true;
}
} finally {
mainLock.unlock();
}
return false;
}
/**
* {@inheritDoc }
*/
@Override
public AccessResult<IDType> tryGetAccess(
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
return tryGetAccess(taskExecutor, request);
}
/**
* {@inheritDoc }
*/
@Override
public AccessResult<IDType> tryGetAccess(
ExecutorService executor,
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
return tryGetAccess((Executor)executor, request);
}
private AccessResult<IDType> tryGetAccess(
Executor executor,
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
AccessTokenImpl<IDType> token;
token = new AccessTokenImpl<>(executor, request);
AccessListener tokenListener = getTokenListener(token);
List<AccessTokenImpl<IDType>> blockingTokens = new LinkedList<>();
mainLock.lock();
try {
getBlockingTokensList(request, blockingTokens);
if (blockingTokens.isEmpty()) {
Collection<RefList.ElementRef<AccessTokenImpl<IDType>>> tokenIndexes;
tokenIndexes = addRigths(token, request);
token.init(tokenListener, tokenIndexes);
}
} finally {
mainLock.unlock();
}
assert !mainLock.isHeldByCurrentThread();
dispatchEvents();
if (blockingTokens.isEmpty()) {
token.setSharedToken(token);
return new AccessResult<>(token);
}
else {
return new AccessResult<>(getUniqueSharedTokens(blockingTokens));
}
}
/**
* {@inheritDoc }
*/
@Override
public AccessResult<IDType> getScheduledAccess(
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
return getScheduledAccess(taskExecutor, request);
}
/**
* {@inheritDoc }
*/
@Override
public AccessResult<IDType> getScheduledAccess(
ExecutorService executor,
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
return getScheduledAccess((Executor)executor, request);
}
private AccessResult<IDType> getScheduledAccess(
Executor executor,
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
AccessTokenImpl<IDType> token;
token = new AccessTokenImpl<>(executor, request);
AccessListener tokenListener = getTokenListener(token);
List<AccessToken<IDType>> blockingTokens = new LinkedList<>();
mainLock.lock();
try {
getBlockingTokensList(request, blockingTokens);
Collection<RefList.ElementRef<AccessTokenImpl<IDType>>> tokenIndexes;
tokenIndexes = addRigths(token, request);
token.init(tokenListener, tokenIndexes);
} finally {
mainLock.unlock();
}
assert !mainLock.isHeldByCurrentThread();
dispatchEvents();
Set<AccessToken<IDType>> blockingTokenSet = createSet(blockingTokens);
AccessToken<IDType> scheduledToken;
scheduledToken = new ScheduledAccessToken<>(token, blockingTokenSet);
token.setSharedToken(scheduledToken);
return new AccessResult<>(scheduledToken, blockingTokenSet);
}
/**
* This tree represents a collection of rights. The graph should be
* considered to be a directed graph were edges point from the parent
* to children. A path in this graph represents a hierarchical right where
* the edges are the parts of this hierarchical right in order.
* Vertices of the graph contains tokens and these tokens mean that
* the right up to the point of this vertex is associated with these
* tokens. Note that since these rights are hierarchical this implies that
* the token also represents all the subrights (even if subrights
* do not contain the token explicitly).
*/
private static class AccessTree<TokenType extends AccessToken<?>> {
private final RefList<TokenType> tokens;
private final Map<Object, AccessTree<TokenType>> subTrees; // the edges
public AccessTree() {
this.subTrees = new HashMap<>();
this.tokens = new RefLinkedList<>();
}
private AccessTree<TokenType> getSubTree(Object key) {
AccessTree<TokenType> result = subTrees.get(key);
if (result == null) {
result = new AccessTree<>();
subTrees.put(key, result);
}
return result;
}
private boolean isEmpty() {
if (!tokens.isEmpty()) {
return false;
}
for (AccessTree<TokenType> subTree: subTrees.values()) {
if (!subTree.isEmpty()) {
return false;
}
}
return true;
}
/**
* Removes all of this tree's subtrees which do not contain tokens.
* This means that after this call every leaf element of this graph
* will contain at least a single token unless there no tokens in this
* tree at all. In which case every subtree will be removed:
* {@code subTrees.size()} will return 0.
* <P>
* This method will also return all the modifications it did. That
* is it will return the rights which were removed from this tree.
* <P>
* A right is not considered to part of the tree if there are no tokens
* in its vertex. (Notice that actually a vertex defines a right:
* the edges up to the vertex)
*
* @param treeRight the removed rights will be prefixed with this
* hierarchical right
* @param modifications the modifications will be added to this
* builder
*/
private void cleanupTree(
HierarchicalRight treeRight,
RightTreeBuilder modifications) {
Iterator<Map.Entry<Object, AccessTree<TokenType>>> itr;
itr = subTrees.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<Object, AccessTree<TokenType>> sub;
sub = itr.next();
if (sub.getValue().isEmpty()) {
HierarchicalRight right;
right = HierarchicalRight.createWithParent(
treeRight, sub.getKey());
modifications.addRight(right);
itr.remove();
}
}
}
/**
* Finds a subtree of this tree specified by a hierarchical right
* and will clean up that tree: {@link #cleanupTree cleanupTree}.
*
* @param right the specified subtree to be cleaned
* @param modifications the rights that were removed from
* this tree (those no longer had any tokens) will be added to
* this builder
*/
public void cleanupRight(
HierarchicalRight right,
RightTreeBuilder modifications) {
AccessTree<TokenType> previousTree = this;
AccessTree<TokenType> currentTree = this;
List<Object> rights = right.getRights();
int rightIndex = 0;
for (Object subRight: rights) {
previousTree = currentTree;
currentTree = currentTree.subTrees.get(subRight);
rightIndex++;
if (currentTree == null) {
break;
}
}
if (currentTree != null) {
HierarchicalRight treeRight;
treeRight = right.getParentRight(rights.size() - rightIndex);
previousTree.cleanupTree(treeRight, modifications);
}
}
public void cleanupRights(
Collection<? extends HierarchicalRight> rights,
RightTreeBuilder modifications) {
for (HierarchicalRight right: rights) {
cleanupRight(right, modifications);
}
}
public void getBlockingTokens(
Collection<? extends HierarchicalRight> rights,
Collection<? super TokenType> result) {
for (HierarchicalRight right: rights) {
getBlockingTokens(right, result);
}
}
public boolean hasBlockingTokens(
Collection<? extends HierarchicalRight> rights) {
for (HierarchicalRight right: rights) {
if (hasBlockingTokens(right)) {
return true;
}
}
return false;
}
/**
* Returns the tokens that are conflicting with the specified rights
* in this tree.
*
* @param right the right checked for conflicts
* @param result conflicting tokens will be added to this collection
*/
public void getBlockingTokens(
HierarchicalRight right,
Collection<? super TokenType> result) {
AccessTree<TokenType> currentTree = this;
for (Object subRight: right.getRights()) {
result.addAll(currentTree.tokens);
currentTree = currentTree.subTrees.get(subRight);
if (currentTree == null) {
break;
}
}
if (currentTree != null) {
result.addAll(currentTree.tokens);
}
}
/**
* Returns {@code true} if there are conflicting tokens with the
* specified rights in this tree.
*
* @param right the right checked for conflicts
* @return {@code true} if there is at least one conflicting token with
* the given right, {@code false} otherwise
*/
public boolean hasBlockingTokens(HierarchicalRight right) {
AccessTree<TokenType> currentTree = this;
for (Object subRight: right.getRights()) {
if (!currentTree.tokens.isEmpty()) {
return true;
}
currentTree = currentTree.subTrees.get(subRight);
if (currentTree == null) {
return false;
}
}
return !currentTree.tokens.isEmpty();
}
public void addRights(
TokenType token,
Collection<? extends HierarchicalRight> rights,
Collection<RefList.ElementRef<TokenType>> resultRefs,
Collection<? super HierarchicalRight> modifications) {
for (HierarchicalRight right: rights) {
addRight(token, right, resultRefs, modifications);
}
}
/**
* Adds a specific right to this tree.
*
* @param token the token which is associated with the specified rights
* @param right the right to be added to this tree
* @param resultRefs the references which can be removed
* to remove the references of the specified token added to this tree
* @param modifications the specified right will be added to this
* collection if adding the specified right required a new vertex
* to be created
*/
public void addRight(
TokenType token,
HierarchicalRight right,
Collection<RefList.ElementRef<TokenType>> resultRefs,
Collection<? super HierarchicalRight> modifications) {
AccessTree<TokenType> currentTree = this;
for (Object subRight: right.getRights()) {
currentTree = currentTree.getSubTree(subRight);
}
if (currentTree.tokens.isEmpty()) {
modifications.add(right);
}
resultRefs.add(currentTree.tokens.addLastGetReference(token));
}
/**
* Checks whether the specified right is contained (or one of its parent
* right is contained) in this tree or not.
*
* @param right the right to be checked
* @return {@code true} if the specified right is in the tree.
* {@code false} otherwise
*/
public boolean hasRight(HierarchicalRight right) {
List<Object> rightList = right.getRights();
AccessTree<TokenType> currentTree = this;
for (Object rightElement: rightList) {
if (!currentTree.tokens.isEmpty()) {
return true;
}
currentTree = currentTree.subTrees.get(rightElement);
if (currentTree == null) {
return false;
}
}
return currentTree != null
? !currentTree.tokens.isEmpty()
: false;
}
/**
* Returns all the rights contained in this tree.
* The rights will be prefixed with the specified parent rights.
*
* @param parent the prefix of the returned rights.
* @param result the (prefixed) rights will be added to this collection.
* @return the right represented by {@code parent}. This is simply
* a performance hack, so we do not always need to create new arrays.
*/
public HierarchicalRight getRights(Object[] parents,
Collection<HierarchicalRight> result) {
HierarchicalRight thisRight;
if (!subTrees.isEmpty()) {
Object[] rightList = new Object[parents.length + 1];
System.arraycopy(parents, 0, rightList, 0, parents.length);
HierarchicalRight aChildRight = null;
int lastIndex = parents.length;
for (Map.Entry<Object, AccessTree<TokenType>> treeEdge:
subTrees.entrySet()) {
rightList[lastIndex] = treeEdge.getKey();
aChildRight = treeEdge.getValue().getRights(rightList, result);
}
// Note that subTrees is not empty, so aChildRight != null
thisRight = aChildRight.getParentRight();
}
else {
thisRight = HierarchicalRight.create(parents);
}
if (!tokens.isEmpty()) {
result.add(thisRight);
}
return thisRight;
}
/**
* Returns all the rights contained in this tree.
*
* @param result the rights will be added to this collection.
*/
public void getRights(Collection<HierarchicalRight> result) {
getRights(new Object[0], result);
}
}
/**
* The access token which stores references of the tokens in
* {@code readTree} and {@code writeTree}, so these references can
* be removed after this token terminates. This implementation
* simply relies on the {@link GenericAccessToken}.
*/
private static class AccessTokenImpl<IDType> extends DelegatedAccessToken<IDType> {
private final AccessRequest<? extends IDType, ? extends HierarchicalRight> request;
private List<RefList.ElementRef<AccessTokenImpl<IDType>>> tokenIndexes;
private volatile AccessToken<IDType> sharedToken;
/**
* Initializes this token with a {@code null} shared token and an
* empty list of token references in the right trees.
* <P>
* {@link #setSharedToken(org.jtrim.access.AccessToken) setSharedToken}
* and
* {@link #init(org.jtrim.access.AccessListener, java.util.Collection) init}
* must be called before returning this token to the client.
*
* @param taskExecutor the executor to which tasks will be submitted to.
* @param request the right request which requested this token to
* be created
*/
public AccessTokenImpl(
Executor taskExecutor,
AccessRequest<? extends IDType, ? extends HierarchicalRight> request) {
super(new GenericAccessToken<>(request.getRequestID(),
taskExecutor));
this.request = request;
this.tokenIndexes = Collections.emptyList();
this.sharedToken = null;
}
/**
* Returns the reference of the token which was returned to the user.
*
* @return the shared token
*/
public AccessToken<IDType> getSharedToken() {
return sharedToken;
}
/**
* Sets the token which was returned to the user. This is important
* because when conflicting tokens need to be returned we must provide
* the same tokens that were returned to the user. This is the case
* with scheduled tokens where we do not return this token but
* wrap it with a {@link ScheduledAccessToken}. If we were to return
* this instance as conflicting token, the client could abuse that
* reference by submitting task to it circumventing the protection
* of {@code ScheduledAccessToken}.
* <P>
* This method must be called exactly once before returning the
* requested token to the client.
*
* @param sharedToken the token actually returned to the client
*/
public void setSharedToken(AccessToken<IDType> sharedToken) {
assert this.sharedToken == null && sharedToken != null;
this.sharedToken = sharedToken;
}
/**
* Sets the access listeners and the references to this token in the
* right trees.
* <P>
* This method must be called exactly once before returning the
* requested token to the client.
*
* @param listener the listener which will be notified when this
* token terminates
* @param tokenIndexes the references to this token in the right trees.
*/
public void init(
AccessListener listener,
Collection<RefList.ElementRef<AccessTokenImpl<IDType>>> tokenIndexes) {
if (tokenIndexes != null) {
this.tokenIndexes = new ArrayList<>(tokenIndexes);
}
if (listener != null) {
wrappedToken.addAccessListener(listener);
}
}
public AccessRequest<? extends IDType, ? extends HierarchicalRight> getRequest() {
return request;
}
public List<RefList.ElementRef<AccessTokenImpl<IDType>>> getTokenIndexes() {
return tokenIndexes;
}
}
/**
* Stores a collection of hierarchical rights. This class was designed to
* collect some hierarchical rights then return the minimal number of rights
* the represents these rights and does not represent other rights.
* So adding a subright of a right that is already contained in this right
* collection must not modify the set of rights stored and adding
* a new right must remove any previously stored subright from this tree.
*/
private static class RightTreeBuilder {
private final RightTree root;
private boolean empty; // true if no right is stored in this tree
private boolean completeTree; // true if every right is part of this tree
// The expression "!empy || !completeTree" must always be true.
// If either "empty" or "completeTree" is true, "root" is ignored.
public RightTreeBuilder() {
this.root = new RightTree();
this.completeTree = false;
this.empty = true;
}
public void addRights(Collection<? extends HierarchicalRight> rights) {
for (HierarchicalRight right: rights) {
addRight(right);
}
}
public void addRight(HierarchicalRight right) {
if (completeTree) {
return;
}
if (!right.isUniversal()) {
root.addRight(right);
}
else {
completeTree = true;
root.clearTree();
}
empty = false;
}
public RightTree getTree() {
return empty ? null : root;
}
public boolean hasRight(HierarchicalRight right) {
return completeTree
? true
: root.hasRight(right);
}
public Collection<HierarchicalRight> getRights() {
return completeTree
? Collections.<HierarchicalRight>emptySet()
: root.getRights();
}
}
/**
* This class actually stores the rights of {@link RightTreeBuilder}.
* This implementation similar to {@link AccessTree} but is more simple
* and there are no token references; an existence of leaf a vertex in the
* graph implies the existence of the hierarchical right and its subrights
* defined by this vertex.
*/
private static class RightTree {
private final Map<Object, RightTree> children;
public RightTree() {
this.children = new HashMap<>();
}
private void getRights(
Object[] parentList,
List<HierarchicalRight> result) {
if (children.isEmpty()) {
result.add(HierarchicalRight.create(parentList));
return;
}
Object[] nextParentList;
nextParentList = Arrays.copyOf(parentList, parentList.length + 1);
for (Map.Entry<Object, RightTree> child: children.entrySet()) {
nextParentList[nextParentList.length - 1] = child.getKey();
child.getValue().getRights(nextParentList, result);
}
}
public Collection<HierarchicalRight> getRights() {
if (children.isEmpty()) {
return Collections.emptySet();
}
List<HierarchicalRight> resultList = new LinkedList<>();
getRights(ArraysEx.EMPTY_OBJECT_ARRAY, resultList);
return resultList;
}
private RightTree getSubTree(Object key) {
RightTree result = children.get(key);
if (result == null) {
result = new RightTree();
children.put(key, result);
}
return result;
}
public void clearTree() {
children.clear();
}
public void addRight(HierarchicalRight right) {
List<Object> rights = right.getRights();
Object firstRight = rights.get(0);
RightTree currentTree = children.get(firstRight);
if (currentTree == null) {
// Create a new path
currentTree = new RightTree();
children.put(firstRight, currentTree);
for (Object subRight: rights.subList(1, rights.size())) {
currentTree = currentTree.getSubTree(subRight);
}
}
else {
// Cut path if necessary
for (Object subRight: rights.subList(1, rights.size())) {
currentTree = currentTree.children.get(subRight);
if (currentTree == null) {
break;
}
}
if (currentTree != null) {
currentTree.clearTree();
}
}
}
public boolean hasRight(HierarchicalRight right) {
if (children.isEmpty()) {
return false;
}
RightTree currentTree = this;
List<Object> rightList = right.getRights();
for (Object rightElement: rightList) {
// The parent right is contained in this tree
if (currentTree.children.isEmpty()) {
return true;
}
currentTree = currentTree.children.get(rightElement);
if (currentTree == null) {
return false;
}
}
return currentTree.children.isEmpty();
}
}
/**
* Returns the rights that are currently in use: there are not terminated
* {@link AccessToken AccessTokens} associated with these rights.
* <P>
* This method was designed for monitoring only and cannot be used
* for synchronization control.
* <P>
* Note this method will return a disjunct sets for the read and write
* rights.
*
* <h5>Thread safety</h5>
* Note that although this method is thread-safe, the rights may change
* right after this method returns, so they may not be up-to-date.
* <h6>Synchronization transparency</h6>
* This method is <I>synchronization transparent</I>.
*
* @param readRights the rights that are currently used for "reading" will
* be added to this collection. These rights can be requested for reading.
* No rights will be added more than once. This argument cannot be
* {@code null}.
* @param writeRights the rights that are currently used for "writing"
* (i.e.: they are used exclusively) will be added to this collection.
* No rights will be added more than once.
*
* @throws NullPointerException thrown if on of the arguments is
* {@code null}
*/
public void getRights(
Collection<HierarchicalRight> readRights,
Collection<HierarchicalRight> writeRights) {
ExceptionHelper.checkNotNullArgument(readRights, "readRights");
ExceptionHelper.checkNotNullArgument(writeRights, "writeRights");
mainLock.lock();
try {
readTree.getRights(readRights);
writeTree.getRights(writeRights);
} finally {
mainLock.unlock();
}
}
/**
* Returns the string representation of this access manager in no
* particular format. The string representation will contain the rights
* currently in use.
* <P>
* This method is intended to be used for debugging only.
*
* @return the string representation of this object in no particular format.
* This method never returns {@code null}.
*/
@Override
public String toString() {
List<HierarchicalRight> readRights = new LinkedList<>();
List<HierarchicalRight> writeRights = new LinkedList<>();
getRights(readRights, writeRights);
return "HierarchicalAccessManager{"
+ "read rights=" + readRights
+ ", write rights=" + writeRights + '}';
}
private static class ListenerRef {
private final TaskScheduler taskScheduler;
private final AccessStateListener<HierarchicalRight> stateListener;
public ListenerRef(
Executor eventExecutor,
AccessStateListener<HierarchicalRight> stateListener) {
ExceptionHelper.checkNotNullArgument(eventExecutor, "eventExecutor");
ExceptionHelper.checkNotNullArgument(stateListener, "stateListener");
this.taskScheduler = new TaskScheduler(eventExecutor);
this.stateListener = stateListener;
}
public AccessStateListener<HierarchicalRight> getStateListener() {
return stateListener;
}
public TaskScheduler getTaskScheduler() {
return taskScheduler;
}
}
}
| Revert "AccessStateListener for HierarchicalAccessManager can be specified later."
This reverts commit ecf4ad7cd2a142e513da00ba6984ee200a96f741.
There is no longer a reason to allow to set the AccessStateListener later.
Conflicts:
jtrim-gui/src/main/java/org/jtrim/access/HierarchicalAccessManager.java
| jtrim-gui/src/main/java/org/jtrim/access/HierarchicalAccessManager.java | Revert "AccessStateListener for HierarchicalAccessManager can be specified later." |
|
Java | apache-2.0 | 81df3514824d3a65302e311df3c277ed813f1f7d | 0 | babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble | // JxpConverter.java
package ed.appserver.templates;
import java.util.*;
import ed.util.*;
public class JxpConverter extends HtmlLikeConverter {
public JxpConverter(){
this( false );
}
public JxpConverter( boolean dotHtmlMode ){
super( dotHtmlMode ? ".html" : ".jxp" ,
dotHtmlMode ? _codeTagsHtml : _codeTagsJxp );
_dotHtmlMode = dotHtmlMode;
}
protected void start( Generator g ){
if ( _dotHtmlMode )
g.append( "var obj = arguments[0];\n" );
}
protected Generator createGenerator( Template t , State s ){
return new MyGenerator( s );
}
protected String getNewName( Template t ){
return t.getName().replaceAll( "\\.(jxp|html)+$" , "_$1.js" );
}
protected void gotCode( Generator g , CodeMarker cm , String code ){
if ( cm._startTag.equals( "<%=" ) ){
g.append( "print( " );
g.append( code );
g.append( " );\n" );
return;
}
if ( cm._startTag.equals( "<%" ) ){
g.append( code );
g.append( "\n" );
return;
}
if ( cm._startTag.equals( "$" ) ){
g.append( "print( " );
g.append( "obj." );
g.append( code );
g.append( ");\n" );
return;
}
throw new RuntimeException( "can't handle : " + cm._startTag );
}
protected boolean gotStartTag( Generator gg , String tag , State state ){
MyGenerator g = (MyGenerator)gg;
TagEnd te = null;
try {
if ( state.peek() == '?' ){
state.next();
state.eatWhiteSpace();
int end = getJSTokenEnd( state.data , state.pos );
StringBuilder cond = new StringBuilder();
while ( state.pos < end )
cond.append( state.next() );
g.append( "if ( " + cond + " ){\n" );
te = new TagEnd( " }\n" , true );
return false;
}
final String[] macro = _tags.get( tag );
if ( macro != null ){
String open = macro[0];
String close = macro[1];
int tokenNumbers = 1;
String restOfTag = state.readRestOfTag();
while ( restOfTag.length() > 0 ){
while ( restOfTag.length() > 0 &&
Character.isWhitespace( restOfTag.charAt( 0 ) ) )
restOfTag = restOfTag.substring( 1 );
if ( restOfTag.length() == 0 )
break;
int end = getJSTokenEnd( restOfTag , 0 );
final String token = restOfTag.substring( 0 , end ).trim();
restOfTag = restOfTag.substring( end ).trim();
if ( token.length() == 0 )
break;
open = open.replaceAll( "\\$" + tokenNumbers , token );
tokenNumbers++;
}
g.append( open );
te = new TagEnd( close , false );
return true;
}
return false;
}
finally {
g.tagPush( tag , te );
}
}
protected boolean gotEndTag( Generator gg , String tag , State state ){
state.readRestOfTag();
MyGenerator g = (MyGenerator)gg;
TagEnd te = g.tagPop( tag );
if ( te == null || te._printTag )
gotText( g , "</" + tag + ">" );
if ( te != null )
g.append( te._code );
return true;
}
protected void gotText( Generator g , String text ){
String lines[] = text.split( "[\r\n]+" );
for ( String line : lines ){
line = StringUtil.replace( line , "\\" , "\\\\" );
line = StringUtil.replace( line , "\"" , "\\\"" );
g.append( "print( \"" + line + "\\n\" );\n" );
}
}
static int getJSTokenEnd( String data , final int start ){
int parens = 0;
int end = start;
for ( ; end < data.length(); end++ ){
char temp = data.charAt( end );
if ( temp == '(' ){
parens++;
continue;
}
if ( temp == ')' ){
parens--;
continue;
}
if ( parens > 0 )
continue;
if ( Character.isLetterOrDigit( temp )
|| temp == '.'
|| temp == '_' )
continue;
if ( Character.isWhitespace( temp ) )
return end;
if ( temp == '\''
|| temp == ';'
|| temp == '#'
|| temp == '<'
|| temp == '>'
|| temp == '"'
|| temp == ':' )
return end;
}
return end;
}
class TagEnd {
TagEnd( String code , boolean printTag ){
_code = code;
_printTag = printTag;
}
final String _code;
final boolean _printTag;
}
class MyGenerator extends Generator {
MyGenerator( State s ){
super( s );
}
void tagPush( String tag , TagEnd te ){
tag = tag.toLowerCase();
Stack<TagEnd> s = _tagToStack.get( tag );
if ( s == null ){
s = new Stack<TagEnd>();
_tagToStack.put( tag , s );
}
s.push( te );
}
TagEnd tagPop( String tag ){
tag = tag.toLowerCase();
Stack<TagEnd> s = _tagToStack.get( tag );
if ( s == null )
return null;
if ( s.size() == 0 )
return null;
return s.pop();
}
final Map<String,Stack<TagEnd>> _tagToStack = new HashMap<String,Stack<TagEnd>>();
}
final boolean _dotHtmlMode;
static List<CodeMarker> _codeTagsJxp = new ArrayList<CodeMarker>();
static List<CodeMarker> _codeTagsHtml = new ArrayList<CodeMarker>();
static {
_codeTagsJxp.add( new CodeMarker( "<%=" , "%>" ) );
_codeTagsJxp.add( new CodeMarker( "<%" , "%>" ) );
_codeTagsHtml.addAll( _codeTagsJxp );
_codeTagsHtml.add( new CodeMarker( "$" , null ){
int findEnd( String data , int start ){
return getJSTokenEnd( data , start );
}
} );
}
static Map<String,String[]> _tags = Collections.synchronizedMap( new StringMap<String[]>() );
static {
_tags.put( "if" , new String[]{
" if ( $1 ){ " , " } "
} );
_tags.put( "forin" , new String[]{
" for ( $1 in $2 ){\n " , "\n } \n "
} );
_tags.put( "forarray" , new String[]{
" for ( var $3=0; $3 < $2 .length; $3 ++ ){\n var $1 = $2[$3]; \n " , " \n } \n "
} );
}
}
| src/main/ed/appserver/templates/JxpConverter.java | // JxpConverter.java
package ed.appserver.templates;
import java.util.*;
import ed.util.*;
public class JxpConverter extends HtmlLikeConverter {
public JxpConverter(){
this( false );
}
public JxpConverter( boolean dotHtmlMode ){
super( dotHtmlMode ? ".html" : ".jxp" ,
dotHtmlMode ? _codeTagsHtml : _codeTagsJxp );
_dotHtmlMode = dotHtmlMode;
}
protected void start( Generator g ){
if ( _dotHtmlMode )
g.append( "var obj = arguments[0];\n" );
}
protected Generator createGenerator( Template t , State s ){
return new MyGenerator( s );
}
protected String getNewName( Template t ){
return t.getName().replaceAll( "\\.(jxp|html)+$" , "_$1.js" );
}
protected void gotCode( Generator g , CodeMarker cm , String code ){
if ( cm._startTag.equals( "<%=" ) ){
g.append( "print( " );
g.append( code );
g.append( " );\n" );
return;
}
if ( cm._startTag.equals( "<%" ) ){
g.append( code );
g.append( "\n" );
return;
}
if ( cm._startTag.equals( "$" ) ){
g.append( "print( " );
g.append( "obj." );
g.append( code );
g.append( ");\n" );
return;
}
throw new RuntimeException( "can't handle : " + cm._startTag );
}
protected boolean gotStartTag( Generator gg , String tag , State state ){
MyGenerator g = (MyGenerator)gg;
TagEnd te = null;
try {
if ( state.peek() == '?' ){
state.next();
state.eatWhiteSpace();
int end = getJSTokenEnd( state.data , state.pos );
StringBuilder cond = new StringBuilder();
while ( state.pos < end )
cond.append( state.next() );
g.append( "if ( " + cond + " ){\n" );
te = new TagEnd( " }\n" , true );
return false;
}
final String[] macro = _tags.get( tag );
if ( macro != null ){
String open = macro[0];
String close = macro[1];
int tokenNumbers = 1;
String restOfTag = state.readRestOfTag();
while ( restOfTag.length() > 0 ){
while ( restOfTag.length() > 0 &&
Character.isWhitespace( restOfTag.charAt( 0 ) ) )
restOfTag = restOfTag.substring( 1 );
if ( restOfTag.length() == 0 )
break;
int end = getJSTokenEnd( restOfTag , 0 );
final String token = restOfTag.substring( 0 , end ).trim();
restOfTag = restOfTag.substring( end ).trim();
if ( token.length() == 0 )
break;
open = open.replaceAll( "\\$" + tokenNumbers , token );
tokenNumbers++;
}
g.append( open );
te = new TagEnd( close , false );
return true;
}
return false;
}
finally {
g.tagPush( tag , te );
}
}
protected boolean gotEndTag( Generator gg , String tag , State state ){
state.readRestOfTag();
MyGenerator g = (MyGenerator)gg;
TagEnd te = g.tagPop( tag );
if ( te == null || te._printTag )
gotText( g , "</" + tag + ">" );
if ( te != null )
g.append( te._code );
return true;
}
protected void gotText( Generator g , String text ){
String lines[] = text.split( "[\r\n]+" );
for ( String line : lines ){
line = StringUtil.replace( line , "\\" , "\\\\" );
line = StringUtil.replace( line , "\"" , "\\\"" );
g.append( "print( \"" + line + "\" );\n" );
}
}
static int getJSTokenEnd( String data , final int start ){
int parens = 0;
int end = start;
for ( ; end < data.length(); end++ ){
char temp = data.charAt( end );
if ( temp == '(' ){
parens++;
continue;
}
if ( temp == ')' ){
parens--;
continue;
}
if ( parens > 0 )
continue;
if ( Character.isLetterOrDigit( temp )
|| temp == '.'
|| temp == '_' )
continue;
if ( Character.isWhitespace( temp ) )
return end;
if ( temp == '\''
|| temp == ';'
|| temp == '#'
|| temp == '<'
|| temp == '>'
|| temp == '"'
|| temp == ':' )
return end;
}
return end;
}
class TagEnd {
TagEnd( String code , boolean printTag ){
_code = code;
_printTag = printTag;
}
final String _code;
final boolean _printTag;
}
class MyGenerator extends Generator {
MyGenerator( State s ){
super( s );
}
void tagPush( String tag , TagEnd te ){
tag = tag.toLowerCase();
Stack<TagEnd> s = _tagToStack.get( tag );
if ( s == null ){
s = new Stack<TagEnd>();
_tagToStack.put( tag , s );
}
s.push( te );
}
TagEnd tagPop( String tag ){
tag = tag.toLowerCase();
Stack<TagEnd> s = _tagToStack.get( tag );
if ( s == null )
return null;
if ( s.size() == 0 )
return null;
return s.pop();
}
final Map<String,Stack<TagEnd>> _tagToStack = new HashMap<String,Stack<TagEnd>>();
}
final boolean _dotHtmlMode;
static List<CodeMarker> _codeTagsJxp = new ArrayList<CodeMarker>();
static List<CodeMarker> _codeTagsHtml = new ArrayList<CodeMarker>();
static {
_codeTagsJxp.add( new CodeMarker( "<%=" , "%>" ) );
_codeTagsJxp.add( new CodeMarker( "<%" , "%>" ) );
_codeTagsHtml.addAll( _codeTagsJxp );
_codeTagsHtml.add( new CodeMarker( "$" , null ){
int findEnd( String data , int start ){
return getJSTokenEnd( data , start );
}
} );
}
static Map<String,String[]> _tags = Collections.synchronizedMap( new StringMap<String[]>() );
static {
_tags.put( "if" , new String[]{
" if ( $1 ){ " , " } "
} );
_tags.put( "forin" , new String[]{
" for ( $1 in $2 ){\n " , "\n } \n "
} );
_tags.put( "forarray" , new String[]{
" for ( var $3=0; $3 < $2 .length; $3 ++ ){\n var $1 = $2[$3]; \n " , " \n } \n "
} );
}
}
| newlines are sometimes handy
| src/main/ed/appserver/templates/JxpConverter.java | newlines are sometimes handy |
|
Java | apache-2.0 | 1349fa56f8ebc16942d3d14c1cca75a87b20a6cd | 0 | simplicitesoftware/heroku-template | package com.simplicite.tomcat;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.catalina.startup.Tomcat;
public class Launcher {
private int port = 8080;
private String rootPath = "webapps/ROOT";
public Launcher(String rootPath) throws Exception {
String port = System.getenv("TOMCAT_HTTP_PORT");
if (port == null || port.length() == 0)
port = System.getenv("PORT");
if (port != null && port.length() > 0)
this.port = Integer.valueOf(port);
System.out.println("--- HTTP p:wq"
+ "ort = [" + this.port + "]");
if (rootPath != null)
this.rootPath = rootPath;
System.out.println("--- Root webapp path = [" + this.rootPath + "]");
}
public void launch() throws Exception {
Tomcat tomcat = new Tomcat();
File f = new File("").getAbsoluteFile();
tomcat.setBaseDir(f.getAbsolutePath());
tomcat.getServer().setCatalinaHome(f);
tomcat.getServer().setCatalinaBase(f);
System.out.println("--- Tomcat home and base dirs set to [" + tomcat.getServer().getCatalinaHome() + "]");
tomcat.enableNaming();
tomcat.setPort(port);
File root= new File(rootPath);
String rootAbsPath = root.getAbsolutePath();
System.out.print("--- Looking for ROOT webapp... ");
if (!root.exists()) {
System.out.print("Creating... ");
root.mkdirs();
File index = new File(root.getPath() + "/index.jsp");
FileOutputStream fos = new FileOutputStream(index);
fos.write(new String("It works (<%= new java.util.Date() %>)!").getBytes());
fos.close();
}
System.out.println("Done");
System.out.print("--- Deploying ROOT webapp... ");
tomcat.addWebapp("", rootAbsPath);
System.out.println("Done");
tomcat.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.print("--- Closing... ");
// TODO: cleaning cache, temporary and work folders
System.out.println("Done");
}
});
tomcat.getServer().await();
}
public static void main(String[] args) {
try {
new Launcher(args != null && args.length > 0 ? args[0] : null).launch();
} catch (Exception e) {
e.printStackTrace();
}
}
} | src/main/java/com/simplicite/tomcat/Launcher.java | package com.simplicite.tomcat;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.catalina.startup.Tomcat;
public class Launcher {
private int port = 8080;
private String rootPath = "webapps/ROOT";
public Launcher(String rootPath) throws Exception {
String port = System.getenv("TOMCAT_HTTP_PORT");
if (port == null || port.length() == 0) port = System.getenv("PORT");
if (port != null && port.length() > 0) this.port = Integer.valueOf(port);
if (rootPath != null) this.rootPath = rootPath;
}
public void launch() throws Exception {
Tomcat tomcat = new Tomcat();
File f = new File("").getAbsoluteFile();
tomcat.setBaseDir(f.getAbsolutePath());
tomcat.getServer().setCatalinaHome(f);
tomcat.getServer().setCatalinaBase(f);
System.out.println("--- Tomcat home and base dirs set to [" + tomcat.getServer().getCatalinaHome() + "]");
tomcat.enableNaming();
tomcat.setPort(port);
File root= new File(rootPath);
String rootAbsPath = root.getAbsolutePath();
System.out.print("--- Looking for ROOT webapp in [" + rootAbsPath + "]... ");
if (!root.exists()) {
System.out.print("Creating... ");
root.mkdirs();
File index = new File(root.getPath() + "/index.jsp");
FileOutputStream fos = new FileOutputStream(index);
fos.write(new String("It works (<%= new java.util.Date() %>)!").getBytes());
fos.close();
}
System.out.println("Done");
System.out.print("--- Deploying ROOT webapp... ");
tomcat.addWebapp("", rootAbsPath);
System.out.println("Done");
tomcat.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.print("--- Closing... ");
// TODO: cleaning cache, temporary and work folders
System.out.println("Done");
}
});
tomcat.getServer().await();
}
public static void main(String[] args) {
try {
new Launcher(args != null && args.length > 0 ? args[0] : null).launch();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Fixed identation for debug
| src/main/java/com/simplicite/tomcat/Launcher.java | Fixed identation for debug |
|
Java | apache-2.0 | b795ea0a88362e43fe45c2bfcc398747a3fe3b85 | 0 | mckayclarey/jitsi,ringdna/jitsi,Metaswitch/jitsi,dkcreinoso/jitsi,bhatvv/jitsi,martin7890/jitsi,martin7890/jitsi,mckayclarey/jitsi,marclaporte/jitsi,dkcreinoso/jitsi,laborautonomo/jitsi,damencho/jitsi,iant-gmbh/jitsi,ibauersachs/jitsi,level7systems/jitsi,mckayclarey/jitsi,level7systems/jitsi,laborautonomo/jitsi,iant-gmbh/jitsi,dkcreinoso/jitsi,mckayclarey/jitsi,dkcreinoso/jitsi,procandi/jitsi,Metaswitch/jitsi,ibauersachs/jitsi,jitsi/jitsi,mckayclarey/jitsi,ringdna/jitsi,bebo/jitsi,jitsi/jitsi,cobratbq/jitsi,procandi/jitsi,cobratbq/jitsi,bhatvv/jitsi,jibaro/jitsi,gpolitis/jitsi,tuijldert/jitsi,marclaporte/jitsi,level7systems/jitsi,HelioGuilherme66/jitsi,pplatek/jitsi,damencho/jitsi,jibaro/jitsi,bebo/jitsi,gpolitis/jitsi,ringdna/jitsi,damencho/jitsi,jitsi/jitsi,jitsi/jitsi,level7systems/jitsi,martin7890/jitsi,gpolitis/jitsi,bebo/jitsi,cobratbq/jitsi,HelioGuilherme66/jitsi,459below/jitsi,iant-gmbh/jitsi,jibaro/jitsi,HelioGuilherme66/jitsi,iant-gmbh/jitsi,cobratbq/jitsi,tuijldert/jitsi,laborautonomo/jitsi,martin7890/jitsi,level7systems/jitsi,gpolitis/jitsi,459below/jitsi,bhatvv/jitsi,gpolitis/jitsi,pplatek/jitsi,ibauersachs/jitsi,Metaswitch/jitsi,ringdna/jitsi,marclaporte/jitsi,bhatvv/jitsi,ibauersachs/jitsi,bhatvv/jitsi,HelioGuilherme66/jitsi,Metaswitch/jitsi,ringdna/jitsi,dkcreinoso/jitsi,marclaporte/jitsi,tuijldert/jitsi,procandi/jitsi,laborautonomo/jitsi,procandi/jitsi,marclaporte/jitsi,bebo/jitsi,459below/jitsi,ibauersachs/jitsi,tuijldert/jitsi,HelioGuilherme66/jitsi,damencho/jitsi,martin7890/jitsi,459below/jitsi,jibaro/jitsi,pplatek/jitsi,procandi/jitsi,damencho/jitsi,laborautonomo/jitsi,pplatek/jitsi,pplatek/jitsi,cobratbq/jitsi,jitsi/jitsi,jibaro/jitsi,459below/jitsi,tuijldert/jitsi,bebo/jitsi,iant-gmbh/jitsi | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.osdependent.jdic;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import net.java.sip.communicator.impl.osdependent.*;
import net.java.sip.communicator.service.gui.*;
import org.jitsi.util.*;
/**
* The <tt>TrayMenu</tt> is the menu that appears when the user right-click
* on the Systray icon.
*
* @author Nicolas Chamouard
* @author Lubomir Marinov
* @author Yana Stamcheva
*/
public final class TrayMenuFactory
{
/**
* Handles the <tt>ActionEvent</tt> when one of the menu items is selected.
*
* @param evt the event containing the menu item name
*/
private static void actionPerformed(ActionEvent evt)
{
Object source = evt.getSource();
String itemName;
if (source instanceof JMenuItem)
{
JMenuItem menuItem = (JMenuItem) source;
itemName = menuItem.getName();
}
else
{
MenuItem menuItem = (MenuItem) source;
itemName = menuItem.getName();
}
if (itemName.equals("settings"))
{
OsDependentActivator.getUIService()
.getConfigurationContainer().setVisible(true);
}
else if (itemName.equals("service.gui.QUIT"))
{
OsDependentActivator.getShutdownService().beginShutdown();
}
else if (itemName.equals("addContact"))
{
ExportedWindow dialog =
OsDependentActivator.getUIService().getExportedWindow(
ExportedWindow.ADD_CONTACT_WINDOW);
if (dialog != null)
dialog.setVisible(true);
else
OsDependentActivator.getUIService().getPopupDialog()
.showMessagePopupDialog(Resources.getString(
"impl.systray.FAILED_TO_OPEN_ADD_CONTACT_DIALOG"));
}
else if (itemName.equals("service.gui.SHOW"))
{
OsDependentActivator.getUIService().setVisible(true);
OsDependentActivator.getUIService().bringToFront();
changeTrayMenuItem(source, "service.gui.HIDE",
"service.gui.HIDE", "service.gui.icons.SEARCH_ICON_16x16");
}
else if (itemName.equals("service.gui.HIDE"))
{
OsDependentActivator.getUIService().setVisible(false);
changeTrayMenuItem(source, "service.gui.SHOW",
"service.gui.SHOW", "service.gui.icons.SEARCH_ICON_16x16");
}
}
/**
* Adds the given <tt>trayMenuItem</tt> to the given <tt>trayMenu</tt>.
* @param trayMenu the tray menu to which to add the item
* @param trayMenuItem the item to add
*/
private static void add(Object trayMenu, Object trayMenuItem)
{
if (trayMenu instanceof JPopupMenu)
((JPopupMenu) trayMenu).add((JMenuItem) trayMenuItem);
else
((PopupMenu) trayMenu).add((MenuItem) trayMenuItem);
}
/**
* Adds a <tt>PopupMenuListener</tt> to the given <tt>trayMenu</tt>.
* @param trayMenu the tray menu to which to add a popup listener
* @param listener the listener to add
*/
public static void addPopupMenuListener(Object trayMenu,
PopupMenuListener listener)
{
if (trayMenu instanceof JPopupMenu)
((JPopupMenu) trayMenu).addPopupMenuListener(listener);
}
/**
* Adds a separator to the given <tt>trayMenu</tt>.
* @param trayMenu the tray menu to which to add a separator
*/
private static void addSeparator(Object trayMenu)
{
if (trayMenu instanceof JPopupMenu)
((JPopupMenu) trayMenu).addSeparator();
else
((PopupMenu) trayMenu).addSeparator();
}
/**
* Creates a tray menu for the given system tray.
*
* @param tray the system tray for which we're creating a menu
* @param swing indicates if we should create a Swing or an AWT menu
* @return a tray menu for the given system tray
*/
public static Object createTrayMenu(SystrayServiceJdicImpl tray,
boolean swing)
{
// Enable swing for java 1.6 except for the mac version
if (!swing && !OSUtils.IS_MAC)
swing = true;
Object trayMenu = swing ? new JPopupMenu() : new PopupMenu();
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
TrayMenuFactory.actionPerformed(event);
}
};
Boolean showOptions
= OsDependentActivator.getConfigurationService().getBoolean(
"net.java.sip.communicator.impl.gui.main.configforms."
+ "SHOW_OPTIONS_WINDOW",
true);
if (showOptions.booleanValue())
{
add(trayMenu, createTrayMenuItem(
"settings",
(OSUtils.IS_MAC)
? "service.gui.PREFERENCES"
: "service.gui.SETTINGS",
"service.systray.CONFIGURE_ICON", listener, swing));
}
add(trayMenu, createTrayMenuItem("addContact",
"service.gui.ADD_CONTACT",
"service.gui.icons.ADD_CONTACT_16x16_ICON", listener, swing));
addSeparator(trayMenu);
Boolean chatPresenceDisabled
= OsDependentActivator.getConfigurationService().getBoolean(
"net.java.sip.communicator.impl.gui.main.presence."
+ "CHAT_PRESENCE_DISABLED",
false);
if (!chatPresenceDisabled.booleanValue())
{
add(trayMenu, new StatusSubMenu(swing).getMenu());
addSeparator(trayMenu);
}
String showHideName;
String showHideTextId;
String showHideIconId;
if (OsDependentActivator.getUIService().isVisible())
{
showHideName = "service.gui.HIDE";
showHideTextId = "service.gui.HIDE";
showHideIconId = "service.gui.icons.SEARCH_ICON_16x16";
}
else
showHideName = "service.gui.SHOW";
showHideTextId = "service.gui.SHOW";
showHideIconId = "service.gui.icons.SEARCH_ICON_16x16";
final Object showHideMenuItem = createTrayMenuItem( showHideName,
showHideTextId,
showHideIconId,
listener,
swing);
add(trayMenu, showHideMenuItem);
add(trayMenu, createTrayMenuItem("service.gui.QUIT",
"service.gui.QUIT", "service.systray.QUIT_MENU_ICON", listener,
swing));
OsDependentActivator.getUIService().addWindowListener(
new WindowAdapter()
{
/**
* Invoked when a window is activated.
*/
public void windowActivated(WindowEvent e)
{
changeTrayMenuItem( showHideMenuItem,
"service.gui.HIDE",
"service.gui.HIDE",
"service.gui.icons.SEARCH_ICON_16x16");
}
/**
* Invoked when a window is de-activated.
*/
public void windowDeactivated(WindowEvent e)
{
changeTrayMenuItem( showHideMenuItem,
"service.gui.SHOW",
"service.gui.SHOW",
"service.gui.icons.SEARCH_ICON_16x16");
}
});
return trayMenu;
}
/**
* Creates a tray menu with the given <tt>name</tt>, text given by
* <tt>textID</tt> and icon given by <tt>iconID</tt>. The <tt>listener</tt>
* is handling item events and the <tt>swing</tt> value indicates if we
* should create a Swing menu item or and an AWT item.
* @param name the name of the item
* @param textID the identifier of the text in the localization resources
* @param iconID the identifier of the icon in the image resources
* @param listener the <tt>ActionListener</tt> handling action events
* @param swing indicates if we should create a Swing menu item or an AWT
* item
* @return a reference to the newly created item
*/
private static Object createTrayMenuItem( String name,
String textID,
String iconID,
ActionListener listener,
boolean swing)
{
String text = Resources.getString(textID);
Object trayMenuItem;
if (swing)
{
JMenuItem menuItem =
new JMenuItem(text, Resources.getImage(iconID));
menuItem.setName(name);
menuItem.addActionListener(listener);
trayMenuItem = menuItem;
}
else
{
MenuItem menuItem = new MenuItem(text);
menuItem.setName(name);
menuItem.addActionListener(listener);
trayMenuItem = menuItem;
}
return trayMenuItem;
}
/**
* Changes the tray menu item properties, like name, text and icon.
* @param trayItem the tray menu item to change
* @param name the new name of the item
* @param textID the new text identifier
* @param iconID the new icon string identifier
*/
private static void changeTrayMenuItem( Object trayItem,
String name,
String textID,
String iconID)
{
String text = Resources.getString(textID);
if (trayItem instanceof JMenuItem)
{
JMenuItem jmenuItem = (JMenuItem) trayItem;
jmenuItem.setName(name);
jmenuItem.setText(text);
jmenuItem.setIcon(Resources.getImage(iconID));
}
else if (trayItem instanceof MenuItem)
{
MenuItem menuItem = (MenuItem) trayItem;
menuItem.setName(name);
menuItem.setLabel(text);
}
}
/**
* Returns <tt>true</tt> if the given <tt>trayMenu</tt> is visible,
* otherwise returns <tt>false</tt>.
* @param trayMenu the <tt>TrayMenu</tt> to check
* @return <tt>true</tt> if the given <tt>trayMenu</tt> is visible,
* otherwise returns <tt>false</tt>
*/
public static boolean isVisible(Object trayMenu)
{
if (trayMenu instanceof JPopupMenu)
return ((JPopupMenu) trayMenu).isVisible();
return false;
}
}
| src/net/java/sip/communicator/impl/osdependent/jdic/TrayMenuFactory.java | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.osdependent.jdic;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import net.java.sip.communicator.impl.osdependent.*;
import net.java.sip.communicator.service.gui.*;
import org.jitsi.util.*;
/**
* The <tt>TrayMenu</tt> is the menu that appears when the user right-click
* on the Systray icon.
*
* @author Nicolas Chamouard
* @author Lubomir Marinov
* @author Yana Stamcheva
*/
public final class TrayMenuFactory
{
/**
* Handles the <tt>ActionEvent</tt> when one of the menu items is selected.
*
* @param evt the event containing the menu item name
*/
private static void actionPerformed(ActionEvent evt)
{
Object source = evt.getSource();
String itemName;
if (source instanceof JMenuItem)
{
JMenuItem menuItem = (JMenuItem) source;
itemName = menuItem.getName();
}
else
{
MenuItem menuItem = (MenuItem) source;
itemName = menuItem.getName();
}
if (itemName.equals("settings"))
{
OsDependentActivator.getUIService()
.getConfigurationContainer().setVisible(true);
}
else if (itemName.equals("service.gui.QUIT"))
{
OsDependentActivator.getShutdownService().beginShutdown();
}
else if (itemName.equals("addContact"))
{
ExportedWindow dialog =
OsDependentActivator.getUIService().getExportedWindow(
ExportedWindow.ADD_CONTACT_WINDOW);
if (dialog != null)
dialog.setVisible(true);
else
OsDependentActivator.getUIService().getPopupDialog()
.showMessagePopupDialog(Resources.getString(
"impl.systray.FAILED_TO_OPEN_ADD_CONTACT_DIALOG"));
}
else if (itemName.equals("service.gui.SHOW"))
{
OsDependentActivator.getUIService().setVisible(true);
OsDependentActivator.getUIService().bringToFront();
changeTrayMenuItem(source, "service.gui.HIDE",
"service.gui.HIDE", "service.gui.icons.SEARCH_ICON_16x16");
}
else if (itemName.equals("service.gui.HIDE"))
{
OsDependentActivator.getUIService().setVisible(false);
changeTrayMenuItem(source, "service.gui.SHOW",
"service.gui.SHOW", "service.gui.icons.SEARCH_ICON_16x16");
}
}
/**
* Adds the given <tt>trayMenuItem</tt> to the given <tt>trayMenu</tt>.
* @param trayMenu the tray menu to which to add the item
* @param trayMenuItem the item to add
*/
private static void add(Object trayMenu, Object trayMenuItem)
{
if (trayMenu instanceof JPopupMenu)
((JPopupMenu) trayMenu).add((JMenuItem) trayMenuItem);
else
((PopupMenu) trayMenu).add((MenuItem) trayMenuItem);
}
/**
* Adds a <tt>PopupMenuListener</tt> to the given <tt>trayMenu</tt>.
* @param trayMenu the tray menu to which to add a popup listener
* @param listener the listener to add
*/
public static void addPopupMenuListener(Object trayMenu,
PopupMenuListener listener)
{
if (trayMenu instanceof JPopupMenu)
((JPopupMenu) trayMenu).addPopupMenuListener(listener);
}
/**
* Adds a separator to the given <tt>trayMenu</tt>.
* @param trayMenu the tray menu to which to add a separator
*/
private static void addSeparator(Object trayMenu)
{
if (trayMenu instanceof JPopupMenu)
((JPopupMenu) trayMenu).addSeparator();
else
((PopupMenu) trayMenu).addSeparator();
}
/**
* Creates a tray menu for the given system tray.
*
* @param tray the system tray for which we're creating a menu
* @param swing indicates if we should create a Swing or an AWT menu
* @return a tray menu for the given system tray
*/
public static Object createTrayMenu(SystrayServiceJdicImpl tray,
boolean swing)
{
// Enable swing for java 1.6 except for the mac version
if (!swing && !OSUtils.IS_MAC)
swing = true;
Object trayMenu = swing ? new JPopupMenu() : new PopupMenu();
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
TrayMenuFactory.actionPerformed(event);
}
};
Boolean showOptions
= OsDependentActivator.getConfigurationService().getBoolean(
"net.java.sip.communicator.impl.gui.main.configforms."
+ "SHOW_OPTIONS_WINDOW",
true);
if (showOptions.booleanValue())
{
add(trayMenu, createTrayMenuItem(
"settings",
(OSUtils.IS_MAC)
? "service.gui.PREFERENCES"
: "service.gui.SETTINGS",
"service.systray.CONFIGURE_ICON", listener, swing));
}
add(trayMenu, createTrayMenuItem("addContact",
"service.gui.ADD_CONTACT",
"service.gui.icons.ADD_CONTACT_16x16_ICON", listener, swing));
addSeparator(trayMenu);
add(trayMenu, new StatusSubMenu(swing).getMenu());
addSeparator(trayMenu);
String showHideName;
String showHideTextId;
String showHideIconId;
if (OsDependentActivator.getUIService().isVisible())
{
showHideName = "service.gui.HIDE";
showHideTextId = "service.gui.HIDE";
showHideIconId = "service.gui.icons.SEARCH_ICON_16x16";
}
else
showHideName = "service.gui.SHOW";
showHideTextId = "service.gui.SHOW";
showHideIconId = "service.gui.icons.SEARCH_ICON_16x16";
final Object showHideMenuItem = createTrayMenuItem( showHideName,
showHideTextId,
showHideIconId,
listener,
swing);
add(trayMenu, showHideMenuItem);
add(trayMenu, createTrayMenuItem("service.gui.QUIT",
"service.gui.QUIT", "service.systray.QUIT_MENU_ICON", listener,
swing));
OsDependentActivator.getUIService().addWindowListener(
new WindowAdapter()
{
/**
* Invoked when a window is activated.
*/
public void windowActivated(WindowEvent e)
{
changeTrayMenuItem( showHideMenuItem,
"service.gui.HIDE",
"service.gui.HIDE",
"service.gui.icons.SEARCH_ICON_16x16");
}
/**
* Invoked when a window is de-activated.
*/
public void windowDeactivated(WindowEvent e)
{
changeTrayMenuItem( showHideMenuItem,
"service.gui.SHOW",
"service.gui.SHOW",
"service.gui.icons.SEARCH_ICON_16x16");
}
});
return trayMenu;
}
/**
* Creates a tray menu with the given <tt>name</tt>, text given by
* <tt>textID</tt> and icon given by <tt>iconID</tt>. The <tt>listener</tt>
* is handling item events and the <tt>swing</tt> value indicates if we
* should create a Swing menu item or and an AWT item.
* @param name the name of the item
* @param textID the identifier of the text in the localization resources
* @param iconID the identifier of the icon in the image resources
* @param listener the <tt>ActionListener</tt> handling action events
* @param swing indicates if we should create a Swing menu item or an AWT
* item
* @return a reference to the newly created item
*/
private static Object createTrayMenuItem( String name,
String textID,
String iconID,
ActionListener listener,
boolean swing)
{
String text = Resources.getString(textID);
Object trayMenuItem;
if (swing)
{
JMenuItem menuItem =
new JMenuItem(text, Resources.getImage(iconID));
menuItem.setName(name);
menuItem.addActionListener(listener);
trayMenuItem = menuItem;
}
else
{
MenuItem menuItem = new MenuItem(text);
menuItem.setName(name);
menuItem.addActionListener(listener);
trayMenuItem = menuItem;
}
return trayMenuItem;
}
/**
* Changes the tray menu item properties, like name, text and icon.
* @param trayItem the tray menu item to change
* @param name the new name of the item
* @param textID the new text identifier
* @param iconID the new icon string identifier
*/
private static void changeTrayMenuItem( Object trayItem,
String name,
String textID,
String iconID)
{
String text = Resources.getString(textID);
if (trayItem instanceof JMenuItem)
{
JMenuItem jmenuItem = (JMenuItem) trayItem;
jmenuItem.setName(name);
jmenuItem.setText(text);
jmenuItem.setIcon(Resources.getImage(iconID));
}
else if (trayItem instanceof MenuItem)
{
MenuItem menuItem = (MenuItem) trayItem;
menuItem.setName(name);
menuItem.setLabel(text);
}
}
/**
* Returns <tt>true</tt> if the given <tt>trayMenu</tt> is visible,
* otherwise returns <tt>false</tt>.
* @param trayMenu the <tt>TrayMenu</tt> to check
* @return <tt>true</tt> if the given <tt>trayMenu</tt> is visible,
* otherwise returns <tt>false</tt>
*/
public static boolean isVisible(Object trayMenu)
{
if (trayMenu instanceof JPopupMenu)
return ((JPopupMenu) trayMenu).isVisible();
return false;
}
}
| Use config to control whether user can change presence state from the systray.
No change to default behaviour (i.e. user can change presence state).
| src/net/java/sip/communicator/impl/osdependent/jdic/TrayMenuFactory.java | Use config to control whether user can change presence state from the systray. No change to default behaviour (i.e. user can change presence state). |
|
Java | apache-2.0 | 856168e39e6b84e555bfd036ea884c3e73b938bb | 0 | hypercube1024/firefly,hypercube1024/firefly,hypercube1024/firefly,hypercube1024/firefly,hypercube1024/firefly | package com.firefly.client.http2;
import com.firefly.codec.http2.model.*;
import com.firefly.codec.http2.model.MetaData.Response;
import com.firefly.codec.http2.stream.HTTPConnection;
import com.firefly.codec.http2.stream.HTTPOutputStream;
import com.firefly.utils.collection.ConcurrentReferenceHashMap;
import com.firefly.utils.concurrent.FuturePromise;
import com.firefly.utils.concurrent.Promise;
import com.firefly.utils.function.Action1;
import com.firefly.utils.function.Action3;
import com.firefly.utils.io.BufferUtils;
import com.firefly.utils.io.EofException;
import com.firefly.utils.json.Json;
import com.firefly.utils.lang.AbstractLifeCycle;
import com.firefly.utils.lang.pool.BlockingPool;
import com.firefly.utils.lang.pool.BoundedBlockingPool;
import com.firefly.utils.time.Millisecond100Clock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class SimpleHTTPClient extends AbstractLifeCycle {
private static Logger log = LoggerFactory.getLogger("firefly-system");
private static Logger monitor = LoggerFactory.getLogger("firefly-monitor");
protected final HTTP2Client http2Client;
private final Map<RequestBuilder, BlockingPool<HTTPClientConnection>> poolMap = new ConcurrentReferenceHashMap<>();
public SimpleHTTPClient() {
this(new SimpleHTTPClientConfiguration());
}
public SimpleHTTPClient(SimpleHTTPClientConfiguration http2Configuration) {
http2Client = new HTTP2Client(http2Configuration);
start();
}
public class RequestBuilder {
String host;
int port;
MetaData.Request request;
List<ByteBuffer> requestBody = new ArrayList<>();
Action1<Response> headerComplete;
Action1<ByteBuffer> content;
Action1<Response> messageComplete;
Action3<Integer, String, Response> badMessage;
Action1<Response> earlyEof;
Promise<HTTPOutputStream> promise;
Action1<HTTPOutputStream> output;
FuturePromise<SimpleResponse> future;
SimpleResponse simpleResponse;
public RequestBuilder cookies(List<Cookie> cookies) {
request.getFields().put(HttpHeader.COOKIE, CookieGenerator.generateCookies(cookies));
return this;
}
public RequestBuilder put(String name, List<String> list) {
request.getFields().put(name, list);
return this;
}
public RequestBuilder put(HttpHeader header, String value) {
request.getFields().put(header, value);
return this;
}
public RequestBuilder put(String name, String value) {
request.getFields().put(name, value);
return this;
}
public RequestBuilder put(HttpField field) {
request.getFields().put(field);
return this;
}
public RequestBuilder addAll(HttpFields fields) {
request.getFields().addAll(fields);
return this;
}
public RequestBuilder add(HttpField field) {
request.getFields().add(field);
return this;
}
public RequestBuilder jsonBody(Object obj) {
return put(HttpHeader.CONTENT_TYPE, MimeTypes.Type.APPLICATION_JSON.asString()).body(Json.toJson(obj));
}
public RequestBuilder body(String content) {
return body(content, StandardCharsets.UTF_8);
}
public RequestBuilder body(String content, Charset charset) {
return write(BufferUtils.toBuffer(content, charset));
}
public RequestBuilder write(ByteBuffer buffer) {
requestBody.add(buffer);
return this;
}
public RequestBuilder output(Action1<HTTPOutputStream> output) {
this.output = output;
return this;
}
public RequestBuilder output(Promise<HTTPOutputStream> promise) {
this.promise = promise;
return this;
}
public RequestBuilder headerComplete(Action1<Response> headerComplete) {
this.headerComplete = headerComplete;
return this;
}
public RequestBuilder messageComplete(Action1<Response> messageComplete) {
this.messageComplete = messageComplete;
return this;
}
public RequestBuilder content(Action1<ByteBuffer> content) {
this.content = content;
return this;
}
public RequestBuilder badMessage(Action3<Integer, String, Response> badMessage) {
this.badMessage = badMessage;
return this;
}
public RequestBuilder earlyEof(Action1<Response> earlyEof) {
this.earlyEof = earlyEof;
return this;
}
public FuturePromise<SimpleResponse> submit() {
submit(new FuturePromise<>());
return future;
}
public void submit(FuturePromise<SimpleResponse> future) {
this.future = future;
send(this);
}
public void submit(Action1<SimpleResponse> action) {
FuturePromise<SimpleResponse> future = new FuturePromise<SimpleResponse>() {
public void succeeded(SimpleResponse t) {
action.call(t);
}
public void failed(Throwable c) {
log.error("http request exception", c);
}
};
submit(future);
}
public void end() {
send(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((host == null) ? 0 : host.hashCode());
result = prime * result + port;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RequestBuilder other = (RequestBuilder) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (host == null) {
if (other.host != null)
return false;
} else if (!host.equals(other.host))
return false;
if (port != other.port)
return false;
return true;
}
private SimpleHTTPClient getOuterType() {
return SimpleHTTPClient.this;
}
}
public void removeConnectionPool(String url) {
try {
removeConnectionPool(new URL(url));
} catch (MalformedURLException e) {
log.error("url exception", e);
throw new IllegalArgumentException(e);
}
}
public void removeConnectionPool(URL url) {
RequestBuilder req = new RequestBuilder();
req.host = url.getHost();
req.port = url.getPort() < 0 ? url.getDefaultPort() : url.getPort();
poolMap.remove(req);
}
public void removeConnectionPool(String host, int port) {
RequestBuilder req = new RequestBuilder();
req.host = host;
req.port = port;
poolMap.remove(req);
}
public int getConnectionPoolSize(String host, int port) {
RequestBuilder req = new RequestBuilder();
req.host = host;
req.port = port;
return _getPoolSize(req);
}
public int getConnectionPoolSize(String url) {
try {
return getConnectionPoolSize(new URL(url));
} catch (MalformedURLException e) {
log.error("url exception", e);
throw new IllegalArgumentException(e);
}
}
public int getConnectionPoolSize(URL url) {
RequestBuilder req = new RequestBuilder();
req.host = url.getHost();
req.port = url.getPort() < 0 ? url.getDefaultPort() : url.getPort();
return _getPoolSize(req);
}
private int _getPoolSize(RequestBuilder req) {
BlockingPool<HTTPClientConnection> pool = poolMap.get(req);
if (pool != null) {
return pool.size();
} else {
return 0;
}
}
public RequestBuilder get(String url) {
return request(HttpMethod.GET.asString(), url);
}
public RequestBuilder post(String url) {
return request(HttpMethod.POST.asString(), url);
}
public RequestBuilder head(String url) {
return request(HttpMethod.HEAD.asString(), url);
}
public RequestBuilder put(String url) {
return request(HttpMethod.PUT.asString(), url);
}
public RequestBuilder delete(String url) {
return request(HttpMethod.DELETE.asString(), url);
}
public RequestBuilder request(HttpMethod method, String url) {
return request(method.asString(), url);
}
public RequestBuilder request(String method, String url) {
try {
return request(method, new URL(url));
} catch (MalformedURLException e) {
log.error("url exception", e);
throw new IllegalArgumentException(e);
}
}
public RequestBuilder request(String method, URL url) {
try {
RequestBuilder req = new RequestBuilder();
req.host = url.getHost();
req.port = url.getPort() < 0 ? url.getDefaultPort() : url.getPort();
req.request = new MetaData.Request(method, new HttpURI(url.toURI()), HttpVersion.HTTP_1_1,
new HttpFields());
return req;
} catch (URISyntaxException e) {
log.error("url exception", e);
throw new IllegalArgumentException(e);
}
}
private void release(HTTPClientConnection connection, BlockingPool<HTTPClientConnection> pool) {
boolean released = (Boolean) connection.getAttachment();
if (!released) {
connection.setAttachment(true);
pool.release(connection);
}
}
protected void send(RequestBuilder r) {
long start = Millisecond100Clock.currentTimeMillis();
SimpleHTTPClientConfiguration config = (SimpleHTTPClientConfiguration) http2Client.getHttp2Configuration();
BlockingPool<HTTPClientConnection> pool = getPool(r);
try {
HTTPClientConnection connection = pool.take(config.getTakeConnectionTimeout(), TimeUnit.MILLISECONDS);
connection.setAttachment(false);
if (connection.getHttpVersion() == HttpVersion.HTTP_2) {
release(connection, pool);
}
log.debug("take the connection {} from pool, released: {}", connection.getSessionId(),
connection.getAttachment());
ClientHTTPHandler handler = new ClientHTTPHandler.Adapter()
.headerComplete((req, resp, outputStream, conn) -> {
if (r.headerComplete != null) {
r.headerComplete.call(resp);
}
if (r.future != null) {
if (r.simpleResponse == null) {
r.simpleResponse = new SimpleResponse(resp);
}
}
return false;
}).messageComplete((req, resp, outputStream, conn) -> {
release(connection, pool);
log.debug("complete request of the connection {} , released: {}", connection.getSessionId(),
connection.getAttachment());
if (r.messageComplete != null) {
r.messageComplete.call(resp);
}
if (r.future != null) {
r.future.succeeded(r.simpleResponse);
}
return true;
}).content((buffer, req, resp, outputStream, conn) -> {
if (r.content != null) {
r.content.call(buffer);
}
if (r.future != null && r.simpleResponse != null) {
r.simpleResponse.responseBody.add(buffer);
}
return false;
}).badMessage((errCode, reason, req, resp, outputStream, conn) -> {
release(connection, pool);
log.debug("bad message of the connection {} , released: {}", connection.getSessionId(),
connection.getAttachment());
if (r.badMessage != null) {
r.badMessage.call(errCode, reason, resp);
}
if (r.future != null) {
if (r.simpleResponse == null) {
r.simpleResponse = new SimpleResponse(resp);
}
r.future.failed(new BadMessageException(errCode, reason));
}
}).earlyEOF((req, resp, outputStream, conn) -> {
release(connection, pool);
log.debug("eafly EOF of the connection {} , released: {}", connection.getSessionId(),
connection.getAttachment());
if (r.earlyEof != null) {
r.earlyEof.call(resp);
}
if (r.future != null) {
if (r.simpleResponse == null) {
r.simpleResponse = new SimpleResponse(resp);
}
r.future.failed(new EofException("early eof"));
}
});
if (r.requestBody != null && !r.requestBody.isEmpty()) {
connection.send(r.request, r.requestBody.toArray(BufferUtils.EMPTY_BYTE_BUFFER_ARRAY), handler);
} else if (r.promise != null) {
connection.send(r.request, r.promise, handler);
} else if (r.output != null) {
Promise<HTTPOutputStream> p = new Promise<HTTPOutputStream>() {
public void succeeded(HTTPOutputStream out) {
r.output.call(out);
}
};
connection.send(r.request, p, handler);
} else {
connection.send(r.request, handler);
}
long end = Millisecond100Clock.currentTimeMillis();
monitor.info("SimpleHTTPClient take connection total time: {}", (end - start));
} catch (InterruptedException e) {
log.error("take connection exception", e);
}
}
private BlockingPool<HTTPClientConnection> getPool(RequestBuilder request) {
BlockingPool<HTTPClientConnection> pool = poolMap.get(request);
if (pool == null) {
synchronized (this) {
if (pool == null) {
SimpleHTTPClientConfiguration config = (SimpleHTTPClientConfiguration) http2Client
.getHttp2Configuration();
pool = new BoundedBlockingPool<>(config.getInitPoolSize(), config.getMaxPoolSize(), () -> {
FuturePromise<HTTPClientConnection> promise = new FuturePromise<>();
http2Client.connect(request.host, request.port, promise);
try {
return promise.get();
} catch (InterruptedException | ExecutionException e) {
log.error("create http connection exception", e);
throw new IllegalStateException(e);
}
}, HTTPConnection::isOpen, (conn) -> {
try {
conn.close();
} catch (IOException e) {
log.error("close http connection exception", e);
}
});
poolMap.put(request, pool);
return pool;
}
}
}
return pool;
}
@Override
protected void init() {
}
@Override
protected void destroy() {
http2Client.stop();
}
}
| firefly/src/main/java/com/firefly/client/http2/SimpleHTTPClient.java | package com.firefly.client.http2;
import com.firefly.codec.http2.model.*;
import com.firefly.codec.http2.model.MetaData.Response;
import com.firefly.codec.http2.stream.HTTPOutputStream;
import com.firefly.utils.collection.ConcurrentReferenceHashMap;
import com.firefly.utils.concurrent.FuturePromise;
import com.firefly.utils.concurrent.Promise;
import com.firefly.utils.concurrent.Scheduler;
import com.firefly.utils.concurrent.Schedulers;
import com.firefly.utils.function.Action1;
import com.firefly.utils.function.Action3;
import com.firefly.utils.io.BufferUtils;
import com.firefly.utils.io.EofException;
import com.firefly.utils.json.Json;
import com.firefly.utils.lang.AbstractLifeCycle;
import com.firefly.utils.lang.pool.BlockingPool;
import com.firefly.utils.lang.pool.BoundedBlockingPool;
import com.firefly.utils.time.Millisecond100Clock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class SimpleHTTPClient extends AbstractLifeCycle {
private static Logger log = LoggerFactory.getLogger("firefly-system");
private static Logger monitor = LoggerFactory.getLogger("firefly-monitor");
protected final HTTP2Client http2Client;
private final Map<RequestBuilder, BlockingPool<HTTPClientConnection>> poolMap = new ConcurrentReferenceHashMap<>();
public SimpleHTTPClient() {
this(new SimpleHTTPClientConfiguration());
}
public SimpleHTTPClient(SimpleHTTPClientConfiguration http2Configuration) {
http2Client = new HTTP2Client(http2Configuration);
start();
}
public class RequestBuilder {
String host;
int port;
MetaData.Request request;
List<ByteBuffer> requestBody = new ArrayList<>();
Action1<Response> headerComplete;
Action1<ByteBuffer> content;
Action1<Response> messageComplete;
Action3<Integer, String, Response> badMessage;
Action1<Response> earlyEof;
Promise<HTTPOutputStream> promise;
Action1<HTTPOutputStream> output;
FuturePromise<SimpleResponse> future;
SimpleResponse simpleResponse;
public RequestBuilder cookies(List<Cookie> cookies) {
request.getFields().put(HttpHeader.COOKIE, CookieGenerator.generateCookies(cookies));
return this;
}
public RequestBuilder put(String name, List<String> list) {
request.getFields().put(name, list);
return this;
}
public RequestBuilder put(HttpHeader header, String value) {
request.getFields().put(header, value);
return this;
}
public RequestBuilder put(String name, String value) {
request.getFields().put(name, value);
return this;
}
public RequestBuilder put(HttpField field) {
request.getFields().put(field);
return this;
}
public RequestBuilder addAll(HttpFields fields) {
request.getFields().addAll(fields);
return this;
}
public RequestBuilder add(HttpField field) {
request.getFields().add(field);
return this;
}
public RequestBuilder jsonBody(Object obj) {
return put(HttpHeader.CONTENT_TYPE, MimeTypes.Type.APPLICATION_JSON.asString()).body(Json.toJson(obj));
}
public RequestBuilder body(String content) {
return body(content, StandardCharsets.UTF_8);
}
public RequestBuilder body(String content, Charset charset) {
return write(BufferUtils.toBuffer(content, charset));
}
public RequestBuilder write(ByteBuffer buffer) {
requestBody.add(buffer);
return this;
}
public RequestBuilder output(Action1<HTTPOutputStream> output) {
this.output = output;
return this;
}
public RequestBuilder output(Promise<HTTPOutputStream> promise) {
this.promise = promise;
return this;
}
public RequestBuilder headerComplete(Action1<Response> headerComplete) {
this.headerComplete = headerComplete;
return this;
}
public RequestBuilder messageComplete(Action1<Response> messageComplete) {
this.messageComplete = messageComplete;
return this;
}
public RequestBuilder content(Action1<ByteBuffer> content) {
this.content = content;
return this;
}
public RequestBuilder badMessage(Action3<Integer, String, Response> badMessage) {
this.badMessage = badMessage;
return this;
}
public RequestBuilder earlyEof(Action1<Response> earlyEof) {
this.earlyEof = earlyEof;
return this;
}
public FuturePromise<SimpleResponse> submit() {
submit(new FuturePromise<>());
return future;
}
public void submit(FuturePromise<SimpleResponse> future) {
this.future = future;
send(this);
}
public void submit(Action1<SimpleResponse> action) {
FuturePromise<SimpleResponse> future = new FuturePromise<SimpleResponse>() {
public void succeeded(SimpleResponse t) {
action.call(t);
}
public void failed(Throwable c) {
log.error("http request exception", c);
}
};
submit(future);
}
public void end() {
send(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((host == null) ? 0 : host.hashCode());
result = prime * result + port;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RequestBuilder other = (RequestBuilder) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (host == null) {
if (other.host != null)
return false;
} else if (!host.equals(other.host))
return false;
if (port != other.port)
return false;
return true;
}
private SimpleHTTPClient getOuterType() {
return SimpleHTTPClient.this;
}
}
public void removeConnectionPool(String url) {
try {
removeConnectionPool(new URL(url));
} catch (MalformedURLException e) {
log.error("url exception", e);
throw new IllegalArgumentException(e);
}
}
public void removeConnectionPool(URL url) {
RequestBuilder req = new RequestBuilder();
req.host = url.getHost();
req.port = url.getPort() < 0 ? url.getDefaultPort() : url.getPort();
poolMap.remove(req);
}
public void removeConnectionPool(String host, int port) {
RequestBuilder req = new RequestBuilder();
req.host = host;
req.port = port;
poolMap.remove(req);
}
public int getConnectionPoolSize(String host, int port) {
RequestBuilder req = new RequestBuilder();
req.host = host;
req.port = port;
return _getPoolSize(req);
}
public int getConnectionPoolSize(String url) {
try {
return getConnectionPoolSize(new URL(url));
} catch (MalformedURLException e) {
log.error("url exception", e);
throw new IllegalArgumentException(e);
}
}
public int getConnectionPoolSize(URL url) {
RequestBuilder req = new RequestBuilder();
req.host = url.getHost();
req.port = url.getPort() < 0 ? url.getDefaultPort() : url.getPort();
return _getPoolSize(req);
}
private int _getPoolSize(RequestBuilder req) {
BlockingPool<HTTPClientConnection> pool = poolMap.get(req);
if (pool != null) {
return pool.size();
} else {
return 0;
}
}
public RequestBuilder get(String url) {
return request(HttpMethod.GET.asString(), url);
}
public RequestBuilder post(String url) {
return request(HttpMethod.POST.asString(), url);
}
public RequestBuilder head(String url) {
return request(HttpMethod.HEAD.asString(), url);
}
public RequestBuilder put(String url) {
return request(HttpMethod.PUT.asString(), url);
}
public RequestBuilder delete(String url) {
return request(HttpMethod.DELETE.asString(), url);
}
public RequestBuilder request(HttpMethod method, String url) {
return request(method.asString(), url);
}
public RequestBuilder request(String method, String url) {
try {
return request(method, new URL(url));
} catch (MalformedURLException e) {
log.error("url exception", e);
throw new IllegalArgumentException(e);
}
}
public RequestBuilder request(String method, URL url) {
try {
RequestBuilder req = new RequestBuilder();
req.host = url.getHost();
req.port = url.getPort() < 0 ? url.getDefaultPort() : url.getPort();
req.request = new MetaData.Request(method, new HttpURI(url.toURI()), HttpVersion.HTTP_1_1,
new HttpFields());
return req;
} catch (URISyntaxException e) {
log.error("url exception", e);
throw new IllegalArgumentException(e);
}
}
private void release(HTTPClientConnection connection, BlockingPool<HTTPClientConnection> pool) {
boolean released = (Boolean) connection.getAttachment();
if (released == false) {
connection.setAttachment(true);
pool.release(connection);
}
}
protected void send(RequestBuilder r) {
long start = Millisecond100Clock.currentTimeMillis();
SimpleHTTPClientConfiguration config = (SimpleHTTPClientConfiguration) http2Client.getHttp2Configuration();
BlockingPool<HTTPClientConnection> pool = getPool(r);
try {
HTTPClientConnection connection = pool.take(config.getTakeConnectionTimeout(), TimeUnit.MILLISECONDS);
connection.setAttachment(false);
if (connection.getHttpVersion() == HttpVersion.HTTP_2) {
release(connection, pool);
}
log.debug("take the connection {} from pool, released: {}", connection.getSessionId(),
connection.getAttachment());
ClientHTTPHandler handler = new ClientHTTPHandler.Adapter()
.headerComplete((req, resp, outputStream, conn) -> {
if (r.headerComplete != null) {
r.headerComplete.call(resp);
}
if (r.future != null) {
if (r.simpleResponse == null) {
r.simpleResponse = new SimpleResponse(resp);
}
}
return false;
}).messageComplete((req, resp, outputStream, conn) -> {
release(connection, pool);
log.debug("complete request of the connection {} , released: {}", connection.getSessionId(),
connection.getAttachment());
if (r.messageComplete != null) {
r.messageComplete.call(resp);
}
if (r.future != null) {
r.future.succeeded(r.simpleResponse);
}
return true;
}).content((buffer, req, resp, outputStream, conn) -> {
if (r.content != null) {
r.content.call(buffer);
}
if (r.future != null && r.simpleResponse != null) {
r.simpleResponse.responseBody.add(buffer);
}
return false;
}).badMessage((errCode, reason, req, resp, outputStream, conn) -> {
release(connection, pool);
log.debug("bad message of the connection {} , released: {}", connection.getSessionId(),
connection.getAttachment());
if (r.badMessage != null) {
r.badMessage.call(errCode, reason, resp);
}
if (r.future != null) {
if (r.simpleResponse == null) {
r.simpleResponse = new SimpleResponse(resp);
}
r.future.failed(new BadMessageException(errCode, reason));
}
}).earlyEOF((req, resp, outputStream, conn) -> {
release(connection, pool);
log.debug("eafly EOF of the connection {} , released: {}", connection.getSessionId(),
connection.getAttachment());
if (r.earlyEof != null) {
r.earlyEof.call(resp);
}
if (r.future != null) {
if (r.simpleResponse == null) {
r.simpleResponse = new SimpleResponse(resp);
}
r.future.failed(new EofException("early eof"));
}
});
if (r.requestBody != null && r.requestBody.isEmpty() == false) {
connection.send(r.request, r.requestBody.toArray(BufferUtils.EMPTY_BYTE_BUFFER_ARRAY), handler);
} else if (r.promise != null) {
connection.send(r.request, r.promise, handler);
} else if (r.output != null) {
Promise<HTTPOutputStream> p = new Promise<HTTPOutputStream>() {
public void succeeded(HTTPOutputStream out) {
r.output.call(out);
}
};
connection.send(r.request, p, handler);
} else {
connection.send(r.request, handler);
}
long end = Millisecond100Clock.currentTimeMillis();
monitor.info("SimpleHTTPClient take connection total time: {}", (end - start));
} catch (InterruptedException e) {
log.error("take connection exception", e);
}
}
private BlockingPool<HTTPClientConnection> getPool(RequestBuilder request) {
BlockingPool<HTTPClientConnection> pool = poolMap.get(request);
if (pool == null) {
synchronized (this) {
if (pool == null) {
SimpleHTTPClientConfiguration config = (SimpleHTTPClientConfiguration) http2Client
.getHttp2Configuration();
pool = new BoundedBlockingPool<>(config.getInitPoolSize(), config.getMaxPoolSize(), () -> {
FuturePromise<HTTPClientConnection> promise = new FuturePromise<>();
http2Client.connect(request.host, request.port, promise);
try {
return promise.get();
} catch (InterruptedException | ExecutionException e) {
log.error("create http connection exception", e);
throw new IllegalStateException(e);
}
}, (conn) -> conn.isOpen(), (conn) -> {
try {
conn.close();
} catch (IOException e) {
log.error("close http connection exception", e);
}
});
poolMap.put(request, pool);
return pool;
}
}
}
return pool;
}
@Override
protected void init() {
}
@Override
protected void destroy() {
http2Client.stop();
}
}
| simplify code
| firefly/src/main/java/com/firefly/client/http2/SimpleHTTPClient.java | simplify code |
|
Java | apache-2.0 | c084d0a999a81380db2af3fc54f02323d540ff70 | 0 | kisskys/incubator-asterixdb,lwhay/hyracks,ecarm002/incubator-asterixdb,heriram/incubator-asterixdb,ty1er/incubator-asterixdb,sjaco002/incubator-asterixdb-hyracks,lwhay/hyracks,amoudi87/hyracks,kisskys/incubator-asterixdb,heriram/incubator-asterixdb,waans11/incubator-asterixdb,apache/incubator-asterixdb,tectronics/hyracks,ty1er/incubator-asterixdb,apache/incubator-asterixdb,apache/incubator-asterixdb,ecarm002/incubator-asterixdb,heriram/incubator-asterixdb,waans11/incubator-asterixdb,kisskys/incubator-asterixdb,waans11/incubator-asterixdb-hyracks,kisskys/incubator-asterixdb-hyracks,apache/incubator-asterixdb,tectronics/hyracks,parshimers/incubator-asterixdb-hyracks,tectronics/hyracks,ecarm002/incubator-asterixdb,ecarm002/incubator-asterixdb,kisskys/incubator-asterixdb,ilovesoup/hyracks,amoudi87/hyracks,ty1er/incubator-asterixdb,ty1er/incubator-asterixdb,sjaco002/incubator-asterixdb-hyracks,waans11/incubator-asterixdb,apache/incubator-asterixdb,kisskys/incubator-asterixdb,waans11/incubator-asterixdb,ty1er/incubator-asterixdb-hyracks,ilovesoup/hyracks,sjaco002/incubator-asterixdb-hyracks,tectronics/hyracks,parshimers/incubator-asterixdb-hyracks,heriram/incubator-asterixdb,waans11/incubator-asterixdb,waans11/incubator-asterixdb-hyracks,waans11/incubator-asterixdb-hyracks,parshimers/incubator-asterixdb-hyracks,ecarm002/incubator-asterixdb,lwhay/hyracks,ty1er/incubator-asterixdb-hyracks,ilovesoup/hyracks,waans11/incubator-asterixdb,kisskys/incubator-asterixdb,ecarm002/incubator-asterixdb,ty1er/incubator-asterixdb,kisskys/incubator-asterixdb,lwhay/hyracks,ty1er/incubator-asterixdb,parshimers/incubator-asterixdb-hyracks,sjaco002/incubator-asterixdb-hyracks,ty1er/incubator-asterixdb-hyracks,waans11/incubator-asterixdb,kisskys/incubator-asterixdb-hyracks,kisskys/incubator-asterixdb-hyracks,ty1er/incubator-asterixdb-hyracks,heriram/incubator-asterixdb,heriram/incubator-asterixdb,ilovesoup/hyracks,amoudi87/hyracks,waans11/incubator-asterixdb-hyracks,heriram/incubator-asterixdb,apache/incubator-asterixdb,kisskys/incubator-asterixdb-hyracks,apache/incubator-asterixdb,amoudi87/hyracks,ecarm002/incubator-asterixdb | /*
* Copyright 2009-2010 by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.hyracks.api.comm;
import java.io.Serializable;
import java.util.Arrays;
public final class NetworkAddress implements Serializable {
private static final long serialVersionUID = 1L;
private final byte[] ipAddress;
private final int port;
public NetworkAddress(byte[] ipAddress, int port) {
this.ipAddress = ipAddress;
this.port = port;
}
public byte[] getIpAddress() {
return ipAddress;
}
public int getPort() {
return port;
}
@Override
public String toString() {
return Arrays.toString(ipAddress) + ":" + port;
}
@Override
public int hashCode() {
return Arrays.hashCode(ipAddress) + port;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof NetworkAddress)) {
return false;
}
NetworkAddress on = (NetworkAddress) o;
return on.port == port && Arrays.equals(on.ipAddress, ipAddress);
}
} | hyracks-api/src/main/java/edu/uci/ics/hyracks/api/comm/NetworkAddress.java | /*
* Copyright 2009-2010 by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.hyracks.api.comm;
import java.io.Serializable;
public final class NetworkAddress implements Serializable {
private static final long serialVersionUID = 1L;
private final byte[] ipAddress;
private final int port;
public NetworkAddress(byte[] ipAddress, int port) {
this.ipAddress = ipAddress;
this.port = port;
}
public byte[] getIpAddress() {
return ipAddress;
}
public int getPort() {
return port;
}
@Override
public String toString() {
return ipAddress + ":" + port;
}
@Override
public int hashCode() {
return ipAddress.hashCode() + port;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof NetworkAddress)) {
return false;
}
NetworkAddress on = (NetworkAddress) o;
return on.port == port && on.ipAddress.equals(ipAddress);
}
} | Fixed erroneous equals() and hashCode()
git-svn-id: a078fbb96e5d5886a75e65008c06a47c9bdeda97@1252 123451ca-8445-de46-9d55-352943316053
| hyracks-api/src/main/java/edu/uci/ics/hyracks/api/comm/NetworkAddress.java | Fixed erroneous equals() and hashCode() |
|
Java | apache-2.0 | 6186b72a6b22d91869b11c1633e452cc707fb675 | 0 | uzh/katts,uzh/katts,uzh/katts,uzh/katts | package ch.uzh.ddis.katts.query.processor;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlTransient;
import ch.uzh.ddis.katts.query.AbstractNode;
import ch.uzh.ddis.katts.query.stream.Producers;
import ch.uzh.ddis.katts.query.stream.Stream;
import ch.uzh.ddis.katts.query.stream.StreamConsumer;
/**
* This class implements an abstract processor. It provides convenient configuration
* methods for consuming, processing and emitting data.
*
* These are primarily the handling of the stream configurations.
*
* @author Thomas Hunziker
*
*/
public abstract class AbstractProcessor extends AbstractNode implements Processor{
private static final long serialVersionUID = 1L;
@XmlTransient
private List<StreamConsumer> consumers = new ArrayList<StreamConsumer>();
// We assume that a regular processor is fully parallelizable
@XmlTransient
private int parallelism = 0;
@XmlTransient
private List<Stream> producers = new Producers(this);
@XmlElementWrapper(name="consumes")
@XmlElement(name="stream")
@Override
public List<StreamConsumer> getConsumers() {
for (StreamConsumer consumer : consumers) {
consumer.setNode(this);
}
return consumers;
}
@XmlElementWrapper(name="produces")
@XmlElement(name="stream")
@Override
public List<Stream> getProducers() {
for (Stream producer : producers) {
producer.setNode(this);
}
return producers;
}
public void setConsumers(List<StreamConsumer> consumers) {
this.consumers = consumers;
}
public void setProducers(List<Stream> producers) {
this.producers = producers;
}
public void appendConsumer(StreamConsumer consumer) {
this.getConsumers().add(consumer);
}
public void appendProducer(Stream producer) {
this.getProducers().add(producer);
}
@Override
@XmlAttribute()
public int getParallelism() {
return this.parallelism;
}
public void setParallelism(int paralleism) {
this.parallelism = paralleism;
}
}
| src/main/java/ch/uzh/ddis/katts/query/processor/AbstractProcessor.java | package ch.uzh.ddis.katts.query.processor;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlTransient;
import ch.uzh.ddis.katts.query.AbstractNode;
import ch.uzh.ddis.katts.query.stream.Producers;
import ch.uzh.ddis.katts.query.stream.Stream;
import ch.uzh.ddis.katts.query.stream.StreamConsumer;
/**
* This class implements an abstract processor. It provides convenient configuration
* methods for consuming, processing and emitting data.
*
* These are primarily the handling of the stream configurations.
*
* @author Thomas Hunziker
*
*/
public abstract class AbstractProcessor extends AbstractNode implements Processor{
private static final long serialVersionUID = 1L;
@XmlTransient
private List<StreamConsumer> consumers = new ArrayList<StreamConsumer>();
@XmlTransient
private List<Stream> producers = new Producers(this);
@XmlElementWrapper(name="consumes")
@XmlElement(name="stream")
@Override
public List<StreamConsumer> getConsumers() {
for (StreamConsumer consumer : consumers) {
consumer.setNode(this);
}
return consumers;
}
@XmlElementWrapper(name="produces")
@XmlElement(name="stream")
@Override
public List<Stream> getProducers() {
for (Stream producer : producers) {
producer.setNode(this);
}
return producers;
}
public void setConsumers(List<StreamConsumer> consumers) {
this.consumers = consumers;
}
public void setProducers(List<Stream> producers) {
this.producers = producers;
}
public void appendConsumer(StreamConsumer consumer) {
this.getConsumers().add(consumer);
}
public void appendProducer(Stream producer) {
this.getProducers().add(producer);
}
@Override
@XmlTransient
public int getParallelism() {
// We assume that a regular processor is fully parallelizable
return 0;
}
}
| Add option to override the parallelization for processing nodes (joins,
functions, filter and aggregates).
| src/main/java/ch/uzh/ddis/katts/query/processor/AbstractProcessor.java | Add option to override the parallelization for processing nodes (joins, functions, filter and aggregates). |
|
Java | apache-2.0 | f5bdd83e5ca65bdc0188991a0f503e68112a9714 | 0 | gaieepo/HubTurbo,gaieepo/HubTurbo | package tests;
import backend.resource.TurboMilestone;
import org.eclipse.egit.github.core.Milestone;
import org.junit.Test;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
public class TurboMilestoneTest {
@Test
public void turboMilestoneTest() {
Milestone milestone = new Milestone();
milestone.setNumber(1);
milestone.setState("open");
TurboMilestone turboMilestone = new TurboMilestone("dummy/dummy", milestone);
assertEquals(1, turboMilestone.getId());
assertEquals("dummy/dummy", turboMilestone.getRepoId());
turboMilestone.setDueDate(Optional.<LocalDate>empty());
assertEquals(Optional.empty(), turboMilestone.getDueDate());
turboMilestone.setDescription("test description");
assertEquals("test description", turboMilestone.getDescription());
turboMilestone.setOpen(false);
assertEquals(false, turboMilestone.isOpen());
turboMilestone.setOpenIssues(0);
assertEquals(0, turboMilestone.getOpenIssues());
turboMilestone.setClosedIssues(0);
assertEquals(0, turboMilestone.getClosedIssues());
}
@Test
public void turboMilestoneSortingTest() {
// test for turbo milestone due date sorting behaviour
TurboMilestone milestone1 = new TurboMilestone("1", 1, "milestone1");
milestone1.setDueDate(Optional.of(LocalDate.now().minusDays(1)));
TurboMilestone milestone2 = new TurboMilestone("2", 2, "milestone2");
milestone2.setDueDate(Optional.of(LocalDate.now().minusDays(2)));
TurboMilestone milestone3 = new TurboMilestone("3", 3, "milestone3");
milestone3.setDueDate(Optional.of(LocalDate.now().minusDays(1)));
TurboMilestone milestone4 = new TurboMilestone("3", 4, "milestone4");
TurboMilestone milestone5 = new TurboMilestone("3", 5, "milestone5");
List<TurboMilestone> milestones = Arrays.asList(milestone1,
milestone2,
milestone3,
milestone4,
milestone5);
List<TurboMilestone> sortedMilestones = TurboMilestone.sortByDueDate(milestones);
// the sort should be stable
assertEquals("milestone2", sortedMilestones.get(0).getTitle());
assertEquals("milestone1", sortedMilestones.get(1).getTitle());
assertEquals("milestone3", sortedMilestones.get(2).getTitle());
assertEquals("milestone4", sortedMilestones.get(3).getTitle());
assertEquals("milestone5", sortedMilestones.get(4).getTitle());
}
}
| src/test/java/tests/TurboMilestoneTest.java | package tests;
import backend.resource.TurboMilestone;
import org.eclipse.egit.github.core.Milestone;
import org.junit.Test;
import java.time.LocalDate;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
public class TurboMilestoneTest {
@Test
public void turboMilestoneTest() {
Milestone milestone = new Milestone();
milestone.setNumber(1);
milestone.setState("open");
TurboMilestone turboMilestone = new TurboMilestone("dummy/dummy", milestone);
assertEquals(1, turboMilestone.getId());
assertEquals("dummy/dummy", turboMilestone.getRepoId());
turboMilestone.setDueDate(Optional.<LocalDate>empty());
assertEquals(Optional.empty(), turboMilestone.getDueDate());
turboMilestone.setDescription("test description");
assertEquals("test description", turboMilestone.getDescription());
turboMilestone.setOpen(false);
assertEquals(false, turboMilestone.isOpen());
turboMilestone.setOpenIssues(0);
assertEquals(0, turboMilestone.getOpenIssues());
turboMilestone.setClosedIssues(0);
assertEquals(0, turboMilestone.getClosedIssues());
}
}
| Add sorting test for TurboMilestone sort method
| src/test/java/tests/TurboMilestoneTest.java | Add sorting test for TurboMilestone sort method |
|
Java | apache-2.0 | 16389eac3795f8a9a6167e1bd463d0e14f7d514b | 0 | BrianBreniser/PSUCS410AgileProject | // Used code found in the example provided at http://www.codejava.net/java-se/networking/ftp/connect-and-login-to-a-ftp-server
// to connect to an ftp server.
/*
Exit codes
----------
1 IOException on user input for server
2 IOException on user input for username
3 IOException on user input for password
4 User provided invalid arguments when running the program
5 Directory creation failure
6 Failed to connect
*/
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.net.InetAddress;
import java.util.Scanner;
public class ftp_client {
private static String server;
private static String username;
private static String password;
private static int port = 21;
private static FTPClient ftpClient = new FTPClient();
public static void directSetupArgs(String ser, String use, String pass, int por) {
server = ser;
username = use;
password = pass;
port = por;
}
public static void directSetupArgs(connection c) {
server = c.server;
username = c.user;
password = c.getPassword();
port = c.port;
}
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
private static void setupServerUnamePass(String[] args) {
Scanner input = new Scanner(System.in);
authentication auth = new authentication();
if (args.length == 0) {
// if no arguments were passed in, prompt user for server, username, and password
// get server
System.out.print("Server: ");
server = input.nextLine();
if (server == null) {
System.out.println("Critical Failure! Exiting program with exit code 1");
System.exit(1);
}
// get username
username = auth.getUsername();
if (username == null) {
System.out.println("Critical Failure! Exiting program with exit code 2");
System.exit(2);
}
// get password
password = auth.getPassword();
if (password == null) {
System.out.println("Critical Failure! Exiting program with exit code 3");
System.exit(3);
}
} else if (args.length == 1) {
// User provided server
server = args[0];
// get username
username = auth.getUsername();
if (username == null) {
System.out.println("Critical Failure! Exiting program with exit code 2");
System.exit(2);
}
// get password
password = auth.getPassword();
if (password == null) {
System.out.println("Critical Failure! Exiting program with exit code 3");
System.exit(3);
}
} else {
// Invalid arguments
System.out.println("Invalid arguments. Only arguments should be server name");
System.exit(4);
}
}
public static void setupFtp() {
try {
if(username.equals("testuser")) {
port = 3131;
}
ftpClient.connect(server, port);
showServerReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Operation failed. Server reply code: " + replyCode);
return;
}
boolean success = ftpClient.login(username, password);
showServerReply(ftpClient);
if (!success) {
System.out.println("Could not login to the server");
} else {
System.out.println("LOGGED IN SERVER");
}
} catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
System.exit(6);
}
}
//Creates a new directory on the ftp server
public static boolean createDirectory(String dirPath) throws IOException {
boolean exists;
String root = ftpClient.printWorkingDirectory();
String[] directories = dirPath.split("/");
//for each piece of the path, check whether or not the dir exists. If not, make it.
for( String dir : directories ) {
exists = ftpClient.changeWorkingDirectory(dir);
if(exists) {
continue;
}
else {
if(!ftpClient.makeDirectory(dir)) {
throw new IOException("Failed to create directory " + dirPath + " error=" + ftpClient.getReplyString());
}
if(!ftpClient.changeWorkingDirectory(dir)) {
throw new IOException("Failed to change to directory " + dirPath + " error=" + ftpClient.getReplyString());
}
}
}
//change back the current working directory back to where it started.
ftpClient.changeWorkingDirectory(root);
return true;
}
public static void main(String[] args) {
// Set up server, username, and password to prepare FTP client
setupServerUnamePass(args);
// Set up ftp client with parameters
setupFtp();
// grab commands and do stuff for the user
command_loop(ftpClient);
}
private static void command_loop(FTPClient f) {
Scanner input = new Scanner(System.in);
connectionManager cm = new connectionManager();
String commandInput;
String dirName;
String getFilePattern = "get \\w.*";
String getMultipleFilePattern = "getmultiple \\w.*";
String putFilePattern = "put \\w.*";
String putMultipleFilePattern = "putmultiple \\w.*";
while(true) {
try {
System.out.print("Command: ");
commandInput = input.nextLine();
switch (commandInput) {
case "exit":
exit();
break;
case "get address":
System.out.println(getRemoteAddress());
break;
case "create dir":
System.out.print("Directory name or relative path: ");
dirName = input.nextLine();
createDirectory(dirName);
break;
case "connection manager":
case "cm":
cm.run();
break;
case "save connection":
case "cm save":
System.out.print("file path: ");
dirName = input.nextLine();
cm.save(dirName);
break;
case "load connection":
case "cm load":
System.out.print("file path: ");
dirName = input.nextLine();
cm.load(dirName);
break;
case "change connection":
case "connection select":
case "cm select":
case "cm change":
connection c = cm.select();
if(c != null) {
if(f.isConnected()) {
f.disconnect();
}
directSetupArgs(c);
setupFtp(); //reconnect
}
break;
case "new connection":
case "add connection":
case "cm new":
case "cm add":
cm.add();
break;
// case "user input": correspondingMethodName();
default:
if (commandInput.matches(getFilePattern)) {
try {
if (!getFile(commandInput)) {
System.out.println("Could not get file from remote server!");
}
} catch (IOException e) {
System.out.println("I/O error getting remote file!");
}
}
if (commandInput.matches(getMultipleFilePattern)) {
try {
if (!getMultipleFile(commandInput)) {
System.out.println("Could not get file(s) from remote server!");
}
} catch (IOException e) {
System.out.println("I/O error getting remote file!");
}
}
if (commandInput.matches(putMultipleFilePattern)) {
try {
if (!putMultipleFile(commandInput)) {
System.out.println("Could not put file(s) from remote server!");
}
} catch (IOException e) {
System.out.println("I/O error putting remote file!");
}
}
if (commandInput.matches(putFilePattern)) {
try {
if (!putFile(commandInput)) {
System.out.println("Could not put file(s) from remote server!");
}
} catch (IOException e) {
System.out.println("I/O error putting remote file!");
}
}
}
}
catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}
}
}
/**
* Will exit the application with a message
*/
public static void exit() {
System.out.println("Thanks for using this FTP client!");
System.exit(0);
}
/**
* @param f FTPClient
* @return String
* Pass in an FTPClient object as an argument
* return, via a string, the remote address, may return qualified domain name,
* or ip address, depending on circumstances of the object and machine.
*/
public static String getRemoteAddress() {
InetAddress addr = ftpClient.getRemoteAddress();
return addr.getCanonicalHostName();
}
/**
* @param String
* @return boolean
* Pass in input String (may contain multiple words)
* Get remote file and write it locally as same-named file.
* If another name is specified after the filename-to-get, write to that name.
*/
public static boolean getFile(String input) throws IOException {
boolean retval = false;
FileOutputStream out;
String [] splitInput = input.split("\\s+");
if (splitInput.length > 2) {
out = new FileOutputStream(splitInput[2]);
}
else {
out = new FileOutputStream(splitInput[1]);
}
retval = ftpClient.retrieveFile(splitInput[1], out);
out.close();
return retval;
}
public static boolean getMultipleFile(String input) throws IOException {
boolean retval = false;
String [] splitInput = input.split("\\s+");
FileOutputStream out;
if(splitInput.length > 1) {
for (int i = 1; i < splitInput.length; ++i) {
out = new FileOutputStream(splitInput[i]);
retval = ftpClient.retrieveFile(splitInput[i], out);
out.close();
if (!retval) {
return false;
}
}
}
return retval;
}
/**
* @param String
* @return boolean
* Pass in input String (may contain multiple words)
* Get local file and write it to remote server as same-named file.
* If another name is specified before the filename-to-get, write to that name.
*/
public static boolean putFile(String input) throws IOException {
boolean retval = false;
String [] splitInput = input.split("\\s+");
FileInputStream in;
if (splitInput.length > 2) {
in = new FileInputStream(splitInput[2]);
}
else {
in = new FileInputStream(splitInput[1]);
}
retval = ftpClient.storeFile(splitInput[1], in);
in.close();
return retval;
}
/**
* @param String
* @return boolean
* @throws IOException
* pass in a string containing "put multiple ... ... .." with ... being any number of files
* that you would like to send to the server, in this case you cannot change the filename
* while in route.
*/
public static boolean putMultipleFile(String input) throws IOException {
boolean retval = false;
String [] splitInput = input.split("\\s+");
FileInputStream in;
if(splitInput.length > 1) {
for (int i = 1; i < splitInput.length; ++i) {
in = new FileInputStream(splitInput[i]);
retval = ftpClient.storeFile(splitInput[i], in);
in.close();
if (!retval) {
return false;
}
}
}
return true;
}
}
| ftp_client.java | // Used code found in the example provided at http://www.codejava.net/java-se/networking/ftp/connect-and-login-to-a-ftp-server
// to connect to an ftp server.
/*
Exit codes
----------
1 IOException on user input for server
2 IOException on user input for username
3 IOException on user input for password
4 User provided invalid arguments when running the program
5 Directory creation failure
6 Failed to connect
*/
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.net.InetAddress;
import java.util.Scanner;
public class ftp_client {
private static String server;
private static String username;
private static String password;
private static int port = 21;
private static FTPClient ftpClient = new FTPClient();
public static void directSetupArgs(String ser, String use, String pass, int por) {
server = ser;
username = use;
password = pass;
port = por;
}
public static void directSetupArgs(connection c) {
server = c.server;
username = c.user;
password = c.getPassword();
port = c.port;
}
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
private static void setupServerUnamePass(String[] args) {
Scanner input = new Scanner(System.in);
authentication auth = new authentication();
if (args.length == 0) {
// if no arguments were passed in, prompt user for server, username, and password
// get server
System.out.print("Server: ");
server = input.nextLine();
if (server == null) {
System.out.println("Critical Failure! Exiting program with exit code 1");
System.exit(1);
}
// get username
username = auth.getUsername();
if (username == null) {
System.out.println("Critical Failure! Exiting program with exit code 2");
System.exit(2);
}
// get password
password = auth.getPassword();
if (password == null) {
System.out.println("Critical Failure! Exiting program with exit code 3");
System.exit(3);
}
} else if (args.length == 1) {
// User provided server
server = args[0];
// get username
username = auth.getUsername();
if (username == null) {
System.out.println("Critical Failure! Exiting program with exit code 2");
System.exit(2);
}
// get password
password = auth.getPassword();
if (password == null) {
System.out.println("Critical Failure! Exiting program with exit code 3");
System.exit(3);
}
} else {
// Invalid arguments
System.out.println("Invalid arguments. Only arguments should be server name");
System.exit(4);
}
}
public static void setupFtp() {
try {
if(username.equals("testuser")) {
port = 3131;
}
ftpClient.connect(server, port);
showServerReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Operation failed. Server reply code: " + replyCode);
return;
}
boolean success = ftpClient.login(username, password);
showServerReply(ftpClient);
if (!success) {
System.out.println("Could not login to the server");
} else {
System.out.println("LOGGED IN SERVER");
}
} catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
System.exit(6);
}
}
//Creates a new directory on the ftp server
public static boolean createDirectory(String dirPath) throws IOException {
boolean exists;
String root = ftpClient.printWorkingDirectory();
String[] directories = dirPath.split("/");
//for each piece of the path, check whether or not the dir exists. If not, make it.
for( String dir : directories ) {
exists = ftpClient.changeWorkingDirectory(dir);
if(exists) {
continue;
}
else {
if(!ftpClient.makeDirectory(dir)) {
throw new IOException("Failed to create directory " + dirPath + " error=" + ftpClient.getReplyString());
}
if(!ftpClient.changeWorkingDirectory(dir)) {
throw new IOException("Failed to change to directory " + dirPath + " error=" + ftpClient.getReplyString());
}
}
}
//change back the current working directory back to where it started.
ftpClient.changeWorkingDirectory(root);
return true;
}
public static void main(String[] args) {
// Set up server, username, and password to prepare FTP client
setupServerUnamePass(args);
// Set up ftp client with parameters
setupFtp();
// grab commands and do stuff for the user
command_loop(ftpClient);
}
private static void command_loop(FTPClient f) {
Scanner input = new Scanner(System.in);
connectionManager cm = new connectionManager();
String commandInput;
String dirName;
String getFilePattern = "get \\w.*";
String getMultipleFilePattern = "getmultiple \\w.*";
String putFilePattern = "put \\w.*";
String putMultipleFilePattern = "putmultiple \\w.*";
while(true) {
try {
System.out.print("Command: ");
commandInput = input.nextLine();
switch (commandInput) {
case "exit":
exit();
break;
case "get address":
System.out.println(getRemoteAddress());
break;
case "create dir":
System.out.print("Directory name or relative path: ");
dirName = input.nextLine();
createDirectory(dirName);
break;
case "connection manager":
case "cm":
cm.run();
break;
case "save connection":
case "cm save":
System.out.print("file path: ");
dirName = input.nextLine();
cm.save(dirName);
break;
case "load connection":
case "cm load":
System.out.print("file path: ");
dirName = input.nextLine();
cm.load(dirName);
break;
case "change connection":
case "connection select":
case "cm select":
case "cm change":
connection c = cm.select();
if(c != null) {
directSetupArgs(c);
setupFtp(); //reconnect
}
break;
case "new connection":
case "add connection":
case "cm new":
case "cm add":
cm.add();
break;
// case "user input": correspondingMethodName();
default:
if (commandInput.matches(getFilePattern)) {
try {
if (!getFile(commandInput)) {
System.out.println("Could not get file from remote server!");
}
} catch (IOException e) {
System.out.println("I/O error getting remote file!");
}
}
if (commandInput.matches(getMultipleFilePattern)) {
try {
if (!getMultipleFile(commandInput)) {
System.out.println("Could not get file(s) from remote server!");
}
} catch (IOException e) {
System.out.println("I/O error getting remote file!");
}
}
if (commandInput.matches(putMultipleFilePattern)) {
try {
if (!putMultipleFile(commandInput)) {
System.out.println("Could not put file(s) from remote server!");
}
} catch (IOException e) {
System.out.println("I/O error putting remote file!");
}
}
if (commandInput.matches(putFilePattern)) {
try {
if (!putFile(commandInput)) {
System.out.println("Could not put file(s) from remote server!");
}
} catch (IOException e) {
System.out.println("I/O error putting remote file!");
}
}
}
}
catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}
}
}
/**
* Will exit the application with a message
*/
public static void exit() {
System.out.println("Thanks for using this FTP client!");
System.exit(0);
}
/**
* @param f FTPClient
* @return String
* Pass in an FTPClient object as an argument
* return, via a string, the remote address, may return qualified domain name,
* or ip address, depending on circumstances of the object and machine.
*/
public static String getRemoteAddress() {
InetAddress addr = ftpClient.getRemoteAddress();
return addr.getCanonicalHostName();
}
/**
* @param String
* @return boolean
* Pass in input String (may contain multiple words)
* Get remote file and write it locally as same-named file.
* If another name is specified after the filename-to-get, write to that name.
*/
public static boolean getFile(String input) throws IOException {
boolean retval = false;
FileOutputStream out;
String [] splitInput = input.split("\\s+");
if (splitInput.length > 2) {
out = new FileOutputStream(splitInput[2]);
}
else {
out = new FileOutputStream(splitInput[1]);
}
retval = ftpClient.retrieveFile(splitInput[1], out);
out.close();
return retval;
}
public static boolean getMultipleFile(String input) throws IOException {
boolean retval = false;
String [] splitInput = input.split("\\s+");
FileOutputStream out;
if(splitInput.length > 1) {
for (int i = 1; i < splitInput.length; ++i) {
out = new FileOutputStream(splitInput[i]);
retval = ftpClient.retrieveFile(splitInput[i], out);
out.close();
if (!retval) {
return false;
}
}
}
return retval;
}
/**
* @param String
* @return boolean
* Pass in input String (may contain multiple words)
* Get local file and write it to remote server as same-named file.
* If another name is specified before the filename-to-get, write to that name.
*/
public static boolean putFile(String input) throws IOException {
boolean retval = false;
String [] splitInput = input.split("\\s+");
FileInputStream in;
if (splitInput.length > 2) {
in = new FileInputStream(splitInput[2]);
}
else {
in = new FileInputStream(splitInput[1]);
}
retval = ftpClient.storeFile(splitInput[1], in);
in.close();
return retval;
}
/**
* @param String
* @return boolean
* @throws IOException
* pass in a string containing "put multiple ... ... .." with ... being any number of files
* that you would like to send to the server, in this case you cannot change the filename
* while in route.
*/
public static boolean putMultipleFile(String input) throws IOException {
boolean retval = false;
String [] splitInput = input.split("\\s+");
FileInputStream in;
if(splitInput.length > 1) {
for (int i = 1; i < splitInput.length; ++i) {
in = new FileInputStream(splitInput[i]);
retval = ftpClient.storeFile(splitInput[i], in);
in.close();
if (!retval) {
return false;
}
}
}
return true;
}
}
| Forgot to disconnect before changing connections
| ftp_client.java | Forgot to disconnect before changing connections |
|
Java | apache-2.0 | 24b184fb1e85fdf2a5903ef04b792348eeeeb890 | 0 | dain/airlift,daququ/airlift,zhenyuy-fb/airlift,haozhun/airlift,johngmyers/airlift,zhenyuy-fb/airlift,cberner/airlift,airlift/airlift,mono-plane/airlift,haozhun/airlift,cberner/airlift,dain/airlift,dain/airlift,zhenyuy-fb/airlift,airlift/airlift,zhenyuy-fb/airlift,electrum/airlift,daququ/airlift,haozhun/airlift,dain/airlift,cberner/airlift,airlift/airlift,mono-plane/airlift,haozhun/airlift,daququ/airlift,johngmyers/airlift,electrum/airlift,airlift/airlift,electrum/airlift,daququ/airlift,mono-plane/airlift,johngmyers/airlift,cberner/airlift,electrum/airlift,mono-plane/airlift,johngmyers/airlift | package io.airlift.http.client.jetty;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.io.CountingInputStream;
import com.google.common.net.HostAndPort;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.AbstractFuture;
import io.airlift.http.client.BodyGenerator;
import io.airlift.http.client.HttpClientConfig;
import io.airlift.http.client.HttpRequestFilter;
import io.airlift.http.client.Request;
import io.airlift.http.client.RequestStats;
import io.airlift.http.client.ResponseHandler;
import io.airlift.http.client.ResponseTooLargeException;
import io.airlift.http.client.StaticBodyGenerator;
import io.airlift.log.Logger;
import io.airlift.stats.Distribution;
import io.airlift.units.DataSize;
import io.airlift.units.DataSize.Unit;
import io.airlift.units.Duration;
import org.eclipse.jetty.client.ConnectionPool;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpExchange;
import org.eclipse.jetty.client.HttpRequest;
import org.eclipse.jetty.client.PoolingHttpDestination;
import org.eclipse.jetty.client.Socks4Proxy;
import org.eclipse.jetty.client.api.Connection;
import org.eclipse.jetty.client.api.ContentProvider;
import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Response.Listener;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.http.HttpChannelOverHTTP;
import org.eclipse.jetty.client.http.HttpConnectionOverHTTP;
import org.eclipse.jetty.client.util.BytesContentProvider;
import org.eclipse.jetty.client.util.InputStreamResponseListener;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.util.HttpCookieStore;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.weakref.jmx.Flatten;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.Math.min;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
public class JettyHttpClient
implements io.airlift.http.client.HttpClient
{
private static final AtomicLong nameCounter = new AtomicLong();
private static final String PRESTO_STATS_KEY = "presto_stats";
private final HttpClient httpClient;
private final long maxContentLength;
private final long requestTimeoutMillis;
private final long idleTimeoutMillis;
private final RequestStats stats = new RequestStats();
private final CachedDistribution queuedRequestsPerDestination;
private final CachedDistribution activeConnectionsPerDestination;
private final CachedDistribution idleConnectionsPerDestination;
private final CachedDistribution currentQueuedTime;
private final CachedDistribution currentRequestTime;
private final CachedDistribution currentRequestSendTime;
private final CachedDistribution currentResponseWaitTime;
private final CachedDistribution currentResponseProcessTime;
private final List<HttpRequestFilter> requestFilters;
private final Exception creationLocation = new Exception();
private final String name;
public JettyHttpClient()
{
this(new HttpClientConfig(), ImmutableList.<HttpRequestFilter>of());
}
public JettyHttpClient(HttpClientConfig config)
{
this(config, ImmutableList.<HttpRequestFilter>of());
}
public JettyHttpClient(HttpClientConfig config, Iterable<? extends HttpRequestFilter> requestFilters)
{
this(config, Optional.<JettyIoPool>absent(), requestFilters);
}
public JettyHttpClient(HttpClientConfig config, JettyIoPool jettyIoPool, Iterable<? extends HttpRequestFilter> requestFilters)
{
this(config, Optional.of(jettyIoPool), requestFilters);
}
private JettyHttpClient(HttpClientConfig config, Optional<JettyIoPool> jettyIoPool, Iterable<? extends HttpRequestFilter> requestFilters)
{
checkNotNull(config, "config is null");
checkNotNull(jettyIoPool, "jettyIoPool is null");
checkNotNull(requestFilters, "requestFilters is null");
maxContentLength = config.getMaxContentLength().toBytes();
requestTimeoutMillis = config.getRequestTimeout().toMillis();
idleTimeoutMillis = config.getIdleTimeout().toMillis();
creationLocation.fillInStackTrace();
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setEndpointIdentificationAlgorithm("HTTPS");
if (config.getKeyStorePath() != null) {
sslContextFactory.setKeyStorePath(config.getKeyStorePath());
sslContextFactory.setKeyStorePassword(config.getKeyStorePassword());
}
httpClient = new HttpClient(sslContextFactory);
httpClient.setMaxConnectionsPerDestination(config.getMaxConnectionsPerServer());
httpClient.setMaxRequestsQueuedPerDestination(config.getMaxRequestsQueuedPerDestination());
// disable cookies
httpClient.setCookieStore(new HttpCookieStore.Empty());
// timeouts
httpClient.setIdleTimeout(idleTimeoutMillis);
httpClient.setConnectTimeout(config.getConnectTimeout().toMillis());
httpClient.setAddressResolutionTimeout(config.getConnectTimeout().toMillis());
HostAndPort socksProxy = config.getSocksProxy();
if (socksProxy != null) {
httpClient.getProxyConfiguration().getProxies().add(new Socks4Proxy(socksProxy.getHostText(), socksProxy.getPortOrDefault(1080)));
}
JettyIoPool pool = jettyIoPool.orNull();
if (pool == null) {
pool = new JettyIoPool("anonymous" + nameCounter.incrementAndGet(), new JettyIoPoolConfig());
}
name = pool.getName();
httpClient.setExecutor(pool.getExecutor());
httpClient.setByteBufferPool(pool.setByteBufferPool());
httpClient.setScheduler(pool.setScheduler());
try {
httpClient.start();
// remove the GZIP encoding from the client
// TODO: there should be a better way to to do this
httpClient.getContentDecoderFactories().clear();
}
catch (Exception e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
throw Throwables.propagate(e);
}
this.requestFilters = ImmutableList.copyOf(requestFilters);
this.activeConnectionsPerDestination = new ConnectionPoolDistribution(httpClient,
(distribution, connectionPool) -> distribution.add(connectionPool.getActiveConnections().size()));
this.idleConnectionsPerDestination = new ConnectionPoolDistribution(httpClient,
(distribution, connectionPool) -> distribution.add(connectionPool.getIdleConnections().size()));
this.queuedRequestsPerDestination = new DestinationDistribution(httpClient,
(distribution, destination) -> distribution.add(destination.getHttpExchanges().size()));
this.currentQueuedTime = new RequestDistribution(httpClient, (distribution, listener, now) -> {
long started = listener.getRequestStarted();
if (started == 0) {
started = now;
}
distribution.add(NANOSECONDS.toMillis(started - listener.getCreated()));
});
this.currentRequestTime = new RequestDistribution(httpClient, (distribution, listener, now) -> {
long started = listener.getRequestStarted();
if (started == 0) {
return;
}
long finished = listener.getResponseFinished();
if (finished == 0) {
finished = now;
}
distribution.add(NANOSECONDS.toMillis(finished - started));
});
this.currentRequestSendTime = new RequestDistribution(httpClient, (distribution, listener, now) -> {
long started = listener.getRequestStarted();
if (started == 0) {
return;
}
long requestSent = listener.getRequestFinished();
if (requestSent == 0) {
requestSent = now;
}
distribution.add(NANOSECONDS.toMillis(requestSent - started));
});
this.currentResponseWaitTime = new RequestDistribution(httpClient, (distribution, listener, now) -> {
long requestSent = listener.getRequestFinished();
if (requestSent == 0) {
return;
}
long responseStarted = listener.getResponseStarted();
if (responseStarted == 0) {
responseStarted = now;
}
distribution.add(NANOSECONDS.toMillis(responseStarted - requestSent));
});
this.currentResponseProcessTime = new RequestDistribution(httpClient, (distribution, listener, now) -> {
long responseStarted = listener.getResponseStarted();
if (responseStarted == 0) {
return;
}
long finished = listener.getResponseFinished();
if (finished == 0) {
finished = now;
}
distribution.add(NANOSECONDS.toMillis(finished - responseStarted));
});
}
@Override
public <T, E extends Exception> T execute(Request request, ResponseHandler<T, E> responseHandler)
throws E
{
long requestStart = System.nanoTime();
// apply filters
request = applyRequestFilters(request);
// create jetty request and response listener
HttpRequest jettyRequest = buildJettyRequest(request);
InputStreamResponseListener listener = new InputStreamResponseListener(maxContentLength)
{
@Override
public void onContent(Response response, ByteBuffer content)
{
// ignore empty blocks
if (content.remaining() == 0) {
return;
}
super.onContent(response, content);
}
};
// fire the request
jettyRequest.send(listener);
// wait for response to begin
Response response;
try {
response = listener.get(httpClient.getIdleTimeout(), MILLISECONDS);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
return responseHandler.handleException(request, e);
}
catch (TimeoutException e) {
return responseHandler.handleException(request, e);
}
catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception) {
return responseHandler.handleException(request, (Exception) cause);
}
else {
return responseHandler.handleException(request, new RuntimeException(cause));
}
}
// process response
long responseStart = System.nanoTime();
JettyResponse jettyResponse = null;
T value;
try {
jettyResponse = new JettyResponse(response, listener.getInputStream());
value = responseHandler.handle(request, jettyResponse);
}
finally {
recordRequestComplete(stats, request, requestStart, jettyResponse, responseStart);
}
return value;
}
@Override
public <T, E extends Exception> HttpResponseFuture<T> executeAsync(Request request, ResponseHandler<T, E> responseHandler)
{
checkNotNull(request, "request is null");
checkNotNull(responseHandler, "responseHandler is null");
request = applyRequestFilters(request);
HttpRequest jettyRequest = buildJettyRequest(request);
JettyResponseFuture<T, E> future = new JettyResponseFuture<>(request, jettyRequest, responseHandler, stats);
BufferingResponseListener listener = new BufferingResponseListener(future, Ints.saturatedCast(maxContentLength));
try {
jettyRequest.send(listener);
}
catch (RuntimeException e) {
// normally this is a rejected execution exception because the client has been closed
future.failed(e);
}
return future;
}
private Request applyRequestFilters(Request request)
{
for (HttpRequestFilter requestFilter : requestFilters) {
request = requestFilter.filterRequest(request);
}
return request;
}
private HttpRequest buildJettyRequest(Request finalRequest)
{
HttpRequest jettyRequest = (HttpRequest) httpClient.newRequest(finalRequest.getUri());
JettyRequestListener listener = new JettyRequestListener(finalRequest.getUri());
jettyRequest.onRequestBegin(request -> listener.onRequestBegin());
jettyRequest.onRequestSuccess(request -> listener.onRequestEnd());
jettyRequest.onResponseBegin(response -> listener.onResponseBegin());
jettyRequest.onComplete(result -> listener.onFinish());
jettyRequest.attribute(PRESTO_STATS_KEY, listener);
// jetty client always adds the user agent header
// todo should there be a default?
jettyRequest.getHeaders().remove(HttpHeader.USER_AGENT);
jettyRequest.method(finalRequest.getMethod());
for (Entry<String, String> entry : finalRequest.getHeaders().entries()) {
jettyRequest.header(entry.getKey(), entry.getValue());
}
BodyGenerator bodyGenerator = finalRequest.getBodyGenerator();
if (bodyGenerator != null) {
if (bodyGenerator instanceof StaticBodyGenerator) {
StaticBodyGenerator staticBodyGenerator = (StaticBodyGenerator) bodyGenerator;
jettyRequest.content(new BytesContentProvider(staticBodyGenerator.getBody()));
}
else {
jettyRequest.content(new BodyGeneratorContentProvider(bodyGenerator, httpClient.getExecutor()));
}
}
// timeouts
jettyRequest.timeout(requestTimeoutMillis, MILLISECONDS);
jettyRequest.idleTimeout(idleTimeoutMillis, MILLISECONDS);
return jettyRequest;
}
public List<HttpRequestFilter> getRequestFilters()
{
return requestFilters;
}
@Override
@Managed
@Flatten
public RequestStats getStats()
{
return stats;
}
@Managed
@Nested
public CachedDistribution getActiveConnectionsPerDestination()
{
return activeConnectionsPerDestination;
}
@Managed
@Nested
public CachedDistribution getIdleConnectionsPerDestination()
{
return idleConnectionsPerDestination;
}
@Managed
@Nested
public CachedDistribution getQueuedRequestsPerDestination()
{
return queuedRequestsPerDestination;
}
@Managed
@Nested
public CachedDistribution getCurrentQueuedTime()
{
return currentQueuedTime;
}
@Managed
@Nested
public CachedDistribution getCurrentRequestTime()
{
return currentRequestTime;
}
@Managed
@Nested
public CachedDistribution getCurrentRequestSendTime()
{
return currentRequestSendTime;
}
@Managed
@Nested
public CachedDistribution getCurrentResponseWaitTime()
{
return currentResponseWaitTime;
}
@Managed
@Nested
public CachedDistribution getCurrentResponseProcessTime()
{
return currentResponseProcessTime;
}
@Managed
public String dump()
{
return httpClient.dump();
}
@Managed
public void dumpStdErr()
{
httpClient.dumpStdErr();
}
@Managed
public String dumpAllDestinations()
{
return String.format("%s\t%s\t%s\t%s\t%s\n", "URI", "queued", "request", "wait", "response") +
httpClient.getDestinations().stream()
.map(JettyHttpClient::dumpDestination)
.collect(Collectors.joining("\n"));
}
// todo this should be @Managed but operations with parameters are broken in jmx utils https://github.com/martint/jmxutils/issues/27
@SuppressWarnings("UnusedDeclaration")
public String dumpDestination(URI uri)
{
Destination destination = httpClient.getDestination(uri.getScheme(), uri.getHost(), uri.getPort());
if (destination == null) {
return null;
}
return dumpDestination(destination);
}
private static String dumpDestination(Destination destination)
{
long now = System.nanoTime();
return getRequestListenersForDestination(destination).stream()
.map(request -> dumpRequest(now, request))
.sorted()
.collect(Collectors.joining("\n"));
}
private static List<JettyRequestListener> getRequestListenersForDestination(Destination destination)
{
return getRequestForDestination(destination).stream()
.map(request -> (JettyRequestListener) request.getAttributes().get(PRESTO_STATS_KEY))
.filter(listener -> listener != null)
.collect(Collectors.toList());
}
private static List<org.eclipse.jetty.client.api.Request> getRequestForDestination(Destination destination)
{
PoolingHttpDestination<?> poolingHttpDestination = (PoolingHttpDestination<?>) destination;
Queue<HttpExchange> httpExchanges = poolingHttpDestination.getHttpExchanges();
List<org.eclipse.jetty.client.api.Request> requests = httpExchanges.stream()
.map(HttpExchange::getRequest)
.collect(Collectors.toList());
for (Connection connection : poolingHttpDestination.getConnectionPool().getActiveConnections()) {
HttpConnectionOverHTTP httpConnectionOverHTTP = (HttpConnectionOverHTTP) connection;
HttpChannelOverHTTP httpChannel = httpConnectionOverHTTP.getHttpChannel();
requests.add(httpChannel.getHttpExchange().getRequest());
}
return requests.stream().filter(request -> request != null).collect(Collectors.toList());
}
private static String dumpRequest(long now, JettyRequestListener listener)
{
long created = listener.getCreated();
long requestStarted = listener.getRequestStarted();
if (requestStarted == 0) {
requestStarted = now;
}
long requestFinished = listener.getRequestFinished();
if (requestFinished == 0) {
requestFinished = now;
}
long responseStarted = listener.getResponseStarted();
if (responseStarted == 0) {
responseStarted = now;
}
long finished = listener.getResponseFinished();
if (finished == 0) {
finished = now;
}
return String.format("%s\t%.1f\t%.1f\t%.1f\t%.1f",
listener.getUri(),
nanosToMillis(requestStarted - created),
nanosToMillis(requestFinished - requestStarted),
nanosToMillis(responseStarted - requestFinished),
nanosToMillis(finished - responseStarted));
}
private static double nanosToMillis(long nanos)
{
return new Duration(nanos, NANOSECONDS).getValue(MILLISECONDS);
}
@Override
public void close()
{
try {
httpClient.stop();
}
catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
catch (Exception ignored) {
}
}
@Override
public String toString()
{
return toStringHelper(this)
.addValue(name)
.toString();
}
@SuppressWarnings("UnusedDeclaration")
public StackTraceElement[] getCreationLocation()
{
return creationLocation.getStackTrace();
}
private static class JettyResponse
implements io.airlift.http.client.Response
{
private final Response response;
private final CountingInputStream inputStream;
public JettyResponse(Response response, InputStream inputStream)
{
this.response = response;
this.inputStream = new CountingInputStream(inputStream);
}
@Override
public int getStatusCode()
{
return response.getStatus();
}
@Override
public String getStatusMessage()
{
return response.getReason();
}
@Override
public String getHeader(String name)
{
return response.getHeaders().getStringField(name);
}
@Override
public ListMultimap<String, String> getHeaders()
{
HttpFields headers = response.getHeaders();
ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
for (String name : headers.getFieldNamesCollection()) {
for (String value : headers.getValuesList(name)) {
builder.put(name, value);
}
}
return builder.build();
}
@Override
public long getBytesRead()
{
return inputStream.getCount();
}
@Override
public InputStream getInputStream()
{
return inputStream;
}
@Override
public String toString()
{
return toStringHelper(this)
.add("statusCode", getStatusCode())
.add("statusMessage", getStatusMessage())
.add("headers", getHeaders())
.toString();
}
}
private static class JettyResponseFuture<T, E extends Exception>
extends AbstractFuture<T>
implements HttpResponseFuture<T>
{
public enum JettyAsyncHttpState
{
WAITING_FOR_CONNECTION,
SENDING_REQUEST,
WAITING_FOR_RESPONSE,
PROCESSING_RESPONSE,
DONE,
FAILED,
CANCELED
}
private static final Logger log = Logger.get(JettyResponseFuture.class);
private final long requestStart = System.nanoTime();
private final AtomicReference<JettyAsyncHttpState> state = new AtomicReference<>(JettyAsyncHttpState.WAITING_FOR_CONNECTION);
private final Request request;
private final org.eclipse.jetty.client.api.Request jettyRequest;
private final ResponseHandler<T, E> responseHandler;
private final RequestStats stats;
public JettyResponseFuture(Request request, org.eclipse.jetty.client.api.Request jettyRequest, ResponseHandler<T, E> responseHandler, RequestStats stats)
{
this.request = request;
this.jettyRequest = jettyRequest;
this.responseHandler = responseHandler;
this.stats = stats;
}
@Override
public String getState()
{
return state.get().toString();
}
@Override
public boolean cancel(boolean mayInterruptIfRunning)
{
try {
state.set(JettyAsyncHttpState.CANCELED);
jettyRequest.abort(new CancellationException());
return super.cancel(mayInterruptIfRunning);
}
catch (Throwable e) {
setException(e);
return true;
}
}
protected void completed(Response response, InputStream content)
{
if (state.get() == JettyAsyncHttpState.CANCELED) {
return;
}
T value;
try {
value = processResponse(response, content);
}
catch (Throwable e) {
// this will be an instance of E from the response handler or an Error
storeException(e);
return;
}
state.set(JettyAsyncHttpState.DONE);
set(value);
}
private T processResponse(Response response, InputStream content)
throws E
{
// this time will not include the data fetching portion of the response,
// since the response is fully cached in memory at this point
long responseStart = System.nanoTime();
state.set(JettyAsyncHttpState.PROCESSING_RESPONSE);
JettyResponse jettyResponse = null;
T value;
try {
jettyResponse = new JettyResponse(response, content);
value = responseHandler.handle(request, jettyResponse);
}
finally {
recordRequestComplete(stats, request, requestStart, jettyResponse, responseStart);
}
return value;
}
protected void failed(Throwable throwable)
{
if (state.get() == JettyAsyncHttpState.CANCELED) {
return;
}
// give handler a chance to rewrite the exception or return a value instead
if (throwable instanceof Exception) {
try {
T value = responseHandler.handleException(request, (Exception) throwable);
// handler returned a value, store it in the future
state.set(JettyAsyncHttpState.DONE);
set(value);
return;
}
catch (Throwable newThrowable) {
throwable = newThrowable;
}
}
// at this point "throwable" will either be an instance of E
// from the response handler or not an instance of Exception
storeException(throwable);
}
private void storeException(Throwable throwable)
{
if (throwable instanceof CancellationException) {
state.set(JettyAsyncHttpState.CANCELED);
}
else {
state.set(JettyAsyncHttpState.FAILED);
}
if (throwable == null) {
throwable = new Throwable("Throwable is null");
log.error(throwable, "Something is broken");
}
setException(throwable);
}
@Override
public String toString()
{
return toStringHelper(this)
.add("requestStart", requestStart)
.add("state", state)
.add("request", request)
.toString();
}
}
private static void recordRequestComplete(RequestStats requestStats, Request request, long requestStart, JettyResponse response, long responseStart)
{
if (response == null) {
return;
}
Duration responseProcessingTime = Duration.nanosSince(responseStart);
Duration requestProcessingTime = new Duration(responseStart - requestStart, NANOSECONDS);
requestStats.record(request.getMethod(),
response.getStatusCode(),
response.getBytesRead(),
response.getBytesRead(),
requestProcessingTime,
responseProcessingTime);
}
private static class BodyGeneratorContentProvider
implements ContentProvider
{
private static final ByteBuffer DONE = ByteBuffer.allocate(0);
private static final ByteBuffer EXCEPTION = ByteBuffer.allocate(0);
private final BodyGenerator bodyGenerator;
private final Executor executor;
public BodyGeneratorContentProvider(BodyGenerator bodyGenerator, Executor executor)
{
this.bodyGenerator = bodyGenerator;
this.executor = executor;
}
@Override
public long getLength()
{
return -1;
}
@Override
public Iterator<ByteBuffer> iterator()
{
final BlockingQueue<ByteBuffer> chunks = new ArrayBlockingQueue<>(16);
final AtomicReference<Exception> exception = new AtomicReference<>();
executor.execute(() -> {
BodyGeneratorOutputStream out = new BodyGeneratorOutputStream(chunks);
try {
bodyGenerator.write(out);
out.close();
}
catch (Exception e) {
exception.set(e);
chunks.add(EXCEPTION);
}
});
return new AbstractIterator<ByteBuffer>()
{
@Override
protected ByteBuffer computeNext()
{
ByteBuffer chunk;
try {
chunk = chunks.take();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted", e);
}
if (chunk == EXCEPTION) {
throw Throwables.propagate(exception.get());
}
if (chunk == DONE) {
return endOfData();
}
return chunk;
}
};
}
private final class BodyGeneratorOutputStream
extends OutputStream
{
private final BlockingQueue<ByteBuffer> chunks;
private BodyGeneratorOutputStream(BlockingQueue<ByteBuffer> chunks)
{
this.chunks = chunks;
}
@Override
public void write(int b)
throws IOException
{
try {
// must copy array since it could be reused
chunks.put(ByteBuffer.wrap(new byte[] {(byte) b}));
}
catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
@Override
public void write(byte[] b, int off, int len)
throws IOException
{
try {
// must copy array since it could be reused
byte[] copy = Arrays.copyOfRange(b, off, len);
chunks.put(ByteBuffer.wrap(copy));
}
catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
@Override
public void close()
throws IOException
{
try {
chunks.put(DONE);
}
catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
}
}
private static class BufferingResponseListener
extends Listener.Adapter
{
private final JettyResponseFuture<?, ?> future;
private final int maxLength;
@GuardedBy("this")
private byte[] buffer = new byte[(int) new DataSize(64, Unit.KILOBYTE).toBytes()];
@GuardedBy("this")
private int size;
public BufferingResponseListener(JettyResponseFuture<?, ?> future, int maxLength)
{
this.future = checkNotNull(future, "future is null");
Preconditions.checkArgument(maxLength > 0, "maxLength must be greater than zero");
this.maxLength = maxLength;
}
@Override
public synchronized void onHeaders(Response response)
{
long length = response.getHeaders().getLongField(HttpHeader.CONTENT_LENGTH.asString());
if (length > maxLength) {
response.abort(new ResponseTooLargeException());
}
if (length > buffer.length) {
buffer = Arrays.copyOf(buffer, Ints.saturatedCast(length));
}
}
@Override
public synchronized void onContent(Response response, ByteBuffer content)
{
int length = content.remaining();
int requiredCapacity = size + length;
if (requiredCapacity > buffer.length) {
if (requiredCapacity > maxLength) {
response.abort(new ResponseTooLargeException());
return;
}
// newCapacity = min(log2ceiling(requiredCapacity), maxLength);
int newCapacity = min(Integer.highestOneBit(requiredCapacity) << 1, maxLength);
buffer = Arrays.copyOf(buffer, newCapacity);
}
content.get(buffer, size, length);
size += length;
}
@Override
public synchronized void onComplete(Result result)
{
Throwable throwable = result.getFailure();
if (throwable != null) {
future.failed(throwable);
}
else {
future.completed(result.getResponse(), new ByteArrayInputStream(buffer, 0, size));
}
}
}
/*
* This class is needed because jmxutils only fetches a nested instance object once and holds on to it forever.
* todo remove this when https://github.com/martint/jmxutils/issues/26 is implemented
*/
@ThreadSafe
public static class CachedDistribution
{
private final Supplier<Distribution> distributionSupplier;
@GuardedBy("this")
private Distribution distribution;
@GuardedBy("this")
private long lastUpdate = System.nanoTime();
public CachedDistribution(Supplier<Distribution> distributionSupplier)
{
this.distributionSupplier = distributionSupplier;
}
public synchronized Distribution getDistribution()
{
// refresh stats only once a second
if (NANOSECONDS.toMillis(System.nanoTime() - lastUpdate) > 1000) {
this.distribution = distributionSupplier.get();
this.lastUpdate = System.nanoTime();
}
return distribution;
}
@Managed
public double getMaxError()
{
return getDistribution().getMaxError();
}
@Managed
public double getCount()
{
return getDistribution().getCount();
}
@Managed
public double getTotal()
{
return getDistribution().getTotal();
}
@Managed
public long getP01()
{
return getDistribution().getP01();
}
@Managed
public long getP05()
{
return getDistribution().getP05();
}
@Managed
public long getP10()
{
return getDistribution().getP10();
}
@Managed
public long getP25()
{
return getDistribution().getP25();
}
@Managed
public long getP50()
{
return getDistribution().getP50();
}
@Managed
public long getP75()
{
return getDistribution().getP75();
}
@Managed
public long getP90()
{
return getDistribution().getP90();
}
@Managed
public long getP95()
{
return getDistribution().getP95();
}
@Managed
public long getP99()
{
return getDistribution().getP99();
}
@Managed
public long getMin()
{
return getDistribution().getMin();
}
@Managed
public long getMax()
{
return getDistribution().getMax();
}
@Managed
public Map<Double, Long> getPercentiles()
{
return getDistribution().getPercentiles();
}
}
private static class JettyRequestListener
{
enum State
{
CREATED, SENDING_REQUEST, AWAITING_RESPONSE, READING_RESPONSE, FINISHED
}
private final AtomicReference<State> state = new AtomicReference<>(State.CREATED);
private final URI uri;
private final long created = System.nanoTime();
private final AtomicLong requestStarted = new AtomicLong();
private final AtomicLong requestFinished = new AtomicLong();
private final AtomicLong responseStarted = new AtomicLong();
private final AtomicLong responseFinished = new AtomicLong();
public JettyRequestListener(URI uri)
{
this.uri = uri;
}
public URI getUri()
{
return uri;
}
public State getState()
{
return state.get();
}
public long getCreated()
{
return created;
}
public long getRequestStarted()
{
return requestStarted.get();
}
public long getRequestFinished()
{
return requestFinished.get();
}
public long getResponseStarted()
{
return responseStarted.get();
}
public long getResponseFinished()
{
return responseFinished.get();
}
public void onRequestBegin()
{
changeState(State.SENDING_REQUEST);
long now = System.nanoTime();
requestStarted.compareAndSet(0, now);
}
public void onRequestEnd()
{
changeState(State.AWAITING_RESPONSE);
long now = System.nanoTime();
requestStarted.compareAndSet(0, now);
requestFinished.compareAndSet(0, now);
}
private void onResponseBegin()
{
changeState(State.READING_RESPONSE);
long now = System.nanoTime();
requestStarted.compareAndSet(0, now);
requestFinished.compareAndSet(0, now);
responseStarted.compareAndSet(0, now);
}
private void onFinish()
{
changeState(State.FINISHED);
long now = System.nanoTime();
requestStarted.compareAndSet(0, now);
requestFinished.compareAndSet(0, now);
responseStarted.compareAndSet(0, now);
responseFinished.compareAndSet(0, now);
}
private synchronized void changeState(State newState)
{
if (state.get().ordinal() < newState.ordinal()) {
state.set(newState);
}
}
}
private static class ConnectionPoolDistribution
extends CachedDistribution
{
interface Processor
{
void process(Distribution distribution, ConnectionPool pool);
}
public ConnectionPoolDistribution(HttpClient httpClient, Processor processor)
{
super(() -> {
Distribution distribution = new Distribution();
for (Destination destination : httpClient.getDestinations()) {
PoolingHttpDestination<?> poolingHttpDestination = (PoolingHttpDestination<?>) destination;
processor.process(distribution, poolingHttpDestination.getConnectionPool());
}
return distribution;
});
}
}
private static class DestinationDistribution
extends CachedDistribution
{
interface Processor
{
void process(Distribution distribution, PoolingHttpDestination<?> destination);
}
public DestinationDistribution(HttpClient httpClient, Processor processor)
{
super(() -> {
Distribution distribution = new Distribution();
for (Destination destination : httpClient.getDestinations()) {
PoolingHttpDestination<?> poolingHttpDestination = (PoolingHttpDestination<?>) destination;
processor.process(distribution, poolingHttpDestination);
}
return distribution;
});
}
}
private static class RequestDistribution
extends CachedDistribution
{
interface Processor
{
void process(Distribution distribution, JettyRequestListener listener, long now);
}
public RequestDistribution(HttpClient httpClient, Processor processor)
{
super(() -> {
long now = System.nanoTime();
Distribution distribution = new Distribution();
for (Destination destination : httpClient.getDestinations()) {
for (JettyRequestListener listener : getRequestListenersForDestination(destination)) {
processor.process(distribution, listener, now);
}
}
return distribution;
});
}
}
}
| http-client/src/main/java/io/airlift/http/client/jetty/JettyHttpClient.java | package io.airlift.http.client.jetty;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.io.CountingInputStream;
import com.google.common.net.HostAndPort;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.AbstractFuture;
import io.airlift.http.client.BodyGenerator;
import io.airlift.http.client.HttpClientConfig;
import io.airlift.http.client.HttpRequestFilter;
import io.airlift.http.client.Request;
import io.airlift.http.client.RequestStats;
import io.airlift.http.client.ResponseHandler;
import io.airlift.http.client.ResponseTooLargeException;
import io.airlift.http.client.StaticBodyGenerator;
import io.airlift.log.Logger;
import io.airlift.stats.Distribution;
import io.airlift.units.DataSize;
import io.airlift.units.DataSize.Unit;
import io.airlift.units.Duration;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpRequest;
import org.eclipse.jetty.client.PoolingHttpDestination;
import org.eclipse.jetty.client.Socks4Proxy;
import org.eclipse.jetty.client.api.ContentProvider;
import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Response.Listener;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.util.BytesContentProvider;
import org.eclipse.jetty.client.util.InputStreamResponseListener;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.util.HttpCookieStore;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.weakref.jmx.Flatten;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.Math.min;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class JettyHttpClient
implements io.airlift.http.client.HttpClient
{
private static final AtomicLong nameCounter = new AtomicLong();
private final HttpClient httpClient;
private final long maxContentLength;
private final long requestTimeoutMillis;
private final long idleTimeoutMillis;
private final RequestStats stats = new RequestStats();
private final CachedDistribution queuedRequestsPerDestination;
private final CachedDistribution activeConnectionsPerDestination;
private final CachedDistribution idleConnectionsPerDestination;
private final List<HttpRequestFilter> requestFilters;
private final Exception creationLocation = new Exception();
private final String name;
public JettyHttpClient()
{
this(new HttpClientConfig(), ImmutableList.<HttpRequestFilter>of());
}
public JettyHttpClient(HttpClientConfig config)
{
this(config, ImmutableList.<HttpRequestFilter>of());
}
public JettyHttpClient(HttpClientConfig config, Iterable<? extends HttpRequestFilter> requestFilters)
{
this(config, Optional.<JettyIoPool>absent(), requestFilters);
}
public JettyHttpClient(HttpClientConfig config, JettyIoPool jettyIoPool, Iterable<? extends HttpRequestFilter> requestFilters)
{
this(config, Optional.of(jettyIoPool), requestFilters);
}
private JettyHttpClient(HttpClientConfig config, Optional<JettyIoPool> jettyIoPool, Iterable<? extends HttpRequestFilter> requestFilters)
{
checkNotNull(config, "config is null");
checkNotNull(jettyIoPool, "jettyIoPool is null");
checkNotNull(requestFilters, "requestFilters is null");
maxContentLength = config.getMaxContentLength().toBytes();
requestTimeoutMillis = config.getRequestTimeout().toMillis();
idleTimeoutMillis = config.getIdleTimeout().toMillis();
creationLocation.fillInStackTrace();
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setEndpointIdentificationAlgorithm("HTTPS");
if (config.getKeyStorePath() != null) {
sslContextFactory.setKeyStorePath(config.getKeyStorePath());
sslContextFactory.setKeyStorePassword(config.getKeyStorePassword());
}
httpClient = new HttpClient(sslContextFactory);
httpClient.setMaxConnectionsPerDestination(config.getMaxConnectionsPerServer());
httpClient.setMaxRequestsQueuedPerDestination(config.getMaxRequestsQueuedPerDestination());
// disable cookies
httpClient.setCookieStore(new HttpCookieStore.Empty());
// timeouts
httpClient.setIdleTimeout(idleTimeoutMillis);
httpClient.setConnectTimeout(config.getConnectTimeout().toMillis());
httpClient.setAddressResolutionTimeout(config.getConnectTimeout().toMillis());
HostAndPort socksProxy = config.getSocksProxy();
if (socksProxy != null) {
httpClient.getProxyConfiguration().getProxies().add(new Socks4Proxy(socksProxy.getHostText(), socksProxy.getPortOrDefault(1080)));
}
JettyIoPool pool = jettyIoPool.orNull();
if (pool == null) {
pool = new JettyIoPool("anonymous" + nameCounter.incrementAndGet(), new JettyIoPoolConfig());
}
name = pool.getName();
httpClient.setExecutor(pool.getExecutor());
httpClient.setByteBufferPool(pool.setByteBufferPool());
httpClient.setScheduler(pool.setScheduler());
try {
httpClient.start();
// remove the GZIP encoding from the client
// TODO: there should be a better way to to do this
httpClient.getContentDecoderFactories().clear();
}
catch (Exception e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
throw Throwables.propagate(e);
}
this.requestFilters = ImmutableList.copyOf(requestFilters);
this.activeConnectionsPerDestination = new CachedDistribution(() -> {
Distribution distribution = new Distribution();
for (Destination destination : httpClient.getDestinations()) {
PoolingHttpDestination<?> poolingHttpDestination = (PoolingHttpDestination<?>) destination;
distribution.add(poolingHttpDestination.getConnectionPool().getActiveConnections().size());
}
return distribution;
});
this.idleConnectionsPerDestination = new CachedDistribution(() -> {
Distribution distribution = new Distribution();
for (Destination destination : httpClient.getDestinations()) {
PoolingHttpDestination<?> poolingHttpDestination = (PoolingHttpDestination<?>) destination;
distribution.add(poolingHttpDestination.getConnectionPool().getIdleConnections().size());
}
return distribution;
});
this.queuedRequestsPerDestination = new CachedDistribution(() -> {
Distribution distribution = new Distribution();
for (Destination destination : httpClient.getDestinations()) {
PoolingHttpDestination<?> poolingHttpDestination = (PoolingHttpDestination<?>) destination;
distribution.add(poolingHttpDestination.getHttpExchanges().size());
}
return distribution;
});
}
@Override
public <T, E extends Exception> T execute(Request request, ResponseHandler<T, E> responseHandler)
throws E
{
long requestStart = System.nanoTime();
// apply filters
request = applyRequestFilters(request);
// create jetty request and response listener
HttpRequest jettyRequest = buildJettyRequest(request);
InputStreamResponseListener listener = new InputStreamResponseListener(maxContentLength)
{
@Override
public void onContent(Response response, ByteBuffer content)
{
// ignore empty blocks
if (content.remaining() == 0) {
return;
}
super.onContent(response, content);
}
};
// fire the request
jettyRequest.send(listener);
// wait for response to begin
Response response;
try {
response = listener.get(httpClient.getIdleTimeout(), MILLISECONDS);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
return responseHandler.handleException(request, e);
}
catch (TimeoutException e) {
return responseHandler.handleException(request, e);
}
catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception) {
return responseHandler.handleException(request, (Exception) cause);
}
else {
return responseHandler.handleException(request, new RuntimeException(cause));
}
}
// process response
long responseStart = System.nanoTime();
JettyResponse jettyResponse = null;
T value;
try {
jettyResponse = new JettyResponse(response, listener.getInputStream());
value = responseHandler.handle(request, jettyResponse);
}
finally {
recordRequestComplete(stats, request, requestStart, jettyResponse, responseStart);
}
return value;
}
@Override
public <T, E extends Exception> HttpResponseFuture<T> executeAsync(Request request, ResponseHandler<T, E> responseHandler)
{
checkNotNull(request, "request is null");
checkNotNull(responseHandler, "responseHandler is null");
request = applyRequestFilters(request);
HttpRequest jettyRequest = buildJettyRequest(request);
JettyResponseFuture<T, E> future = new JettyResponseFuture<>(request, jettyRequest, responseHandler, stats);
BufferingResponseListener listener = new BufferingResponseListener(future, Ints.saturatedCast(maxContentLength));
try {
jettyRequest.send(listener);
}
catch (RuntimeException e) {
// normally this is a rejected execution exception because the client has been closed
future.failed(e);
}
return future;
}
private Request applyRequestFilters(Request request)
{
for (HttpRequestFilter requestFilter : requestFilters) {
request = requestFilter.filterRequest(request);
}
return request;
}
private HttpRequest buildJettyRequest(Request finalRequest)
{
HttpRequest jettyRequest = (HttpRequest) httpClient.newRequest(finalRequest.getUri());
// jetty client always adds the user agent header
// todo should there be a default?
jettyRequest.getHeaders().remove(HttpHeader.USER_AGENT);
jettyRequest.method(finalRequest.getMethod());
for (Entry<String, String> entry : finalRequest.getHeaders().entries()) {
jettyRequest.header(entry.getKey(), entry.getValue());
}
BodyGenerator bodyGenerator = finalRequest.getBodyGenerator();
if (bodyGenerator != null) {
if (bodyGenerator instanceof StaticBodyGenerator) {
StaticBodyGenerator staticBodyGenerator = (StaticBodyGenerator) bodyGenerator;
jettyRequest.content(new BytesContentProvider(staticBodyGenerator.getBody()));
}
else {
jettyRequest.content(new BodyGeneratorContentProvider(bodyGenerator, httpClient.getExecutor()));
}
}
// timeouts
jettyRequest.timeout(requestTimeoutMillis, MILLISECONDS);
jettyRequest.idleTimeout(idleTimeoutMillis, MILLISECONDS);
return jettyRequest;
}
public List<HttpRequestFilter> getRequestFilters()
{
return requestFilters;
}
@Override
@Managed
@Flatten
public RequestStats getStats()
{
return stats;
}
@Managed
@Nested
public CachedDistribution getActiveConnectionsPerDestination()
{
return activeConnectionsPerDestination;
}
@Managed
@Nested
public CachedDistribution getIdleConnectionsPerDestination()
{
return idleConnectionsPerDestination;
}
@Managed
@Nested
public CachedDistribution getQueuedRequestsPerDestination()
{
return queuedRequestsPerDestination;
}
@Managed
public String dump()
{
return httpClient.dump();
}
@Managed
public void dumpStdErr()
{
httpClient.dumpStdErr();
}
@Override
public void close()
{
try {
httpClient.stop();
}
catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
catch (Exception ignored) {
}
}
@Override
public String toString()
{
return toStringHelper(this)
.addValue(name)
.toString();
}
@SuppressWarnings("UnusedDeclaration")
public StackTraceElement[] getCreationLocation()
{
return creationLocation.getStackTrace();
}
private static class JettyResponse
implements io.airlift.http.client.Response
{
private final Response response;
private final CountingInputStream inputStream;
public JettyResponse(Response response, InputStream inputStream)
{
this.response = response;
this.inputStream = new CountingInputStream(inputStream);
}
@Override
public int getStatusCode()
{
return response.getStatus();
}
@Override
public String getStatusMessage()
{
return response.getReason();
}
@Override
public String getHeader(String name)
{
return response.getHeaders().getStringField(name);
}
@Override
public ListMultimap<String, String> getHeaders()
{
HttpFields headers = response.getHeaders();
ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
for (String name : headers.getFieldNamesCollection()) {
for (String value : headers.getValuesList(name)) {
builder.put(name, value);
}
}
return builder.build();
}
@Override
public long getBytesRead()
{
return inputStream.getCount();
}
@Override
public InputStream getInputStream()
{
return inputStream;
}
@Override
public String toString()
{
return toStringHelper(this)
.add("statusCode", getStatusCode())
.add("statusMessage", getStatusMessage())
.add("headers", getHeaders())
.toString();
}
}
private static class JettyResponseFuture<T, E extends Exception>
extends AbstractFuture<T>
implements HttpResponseFuture<T>
{
public enum JettyAsyncHttpState
{
WAITING_FOR_CONNECTION,
SENDING_REQUEST,
WAITING_FOR_RESPONSE,
PROCESSING_RESPONSE,
DONE,
FAILED,
CANCELED
}
private static final Logger log = Logger.get(JettyResponseFuture.class);
private final long requestStart = System.nanoTime();
private final AtomicReference<JettyAsyncHttpState> state = new AtomicReference<>(JettyAsyncHttpState.WAITING_FOR_CONNECTION);
private final Request request;
private final org.eclipse.jetty.client.api.Request jettyRequest;
private final ResponseHandler<T, E> responseHandler;
private final RequestStats stats;
public JettyResponseFuture(Request request, org.eclipse.jetty.client.api.Request jettyRequest, ResponseHandler<T, E> responseHandler, RequestStats stats)
{
this.request = request;
this.jettyRequest = jettyRequest;
this.responseHandler = responseHandler;
this.stats = stats;
}
@Override
public String getState()
{
return state.get().toString();
}
@Override
public boolean cancel(boolean mayInterruptIfRunning)
{
try {
state.set(JettyAsyncHttpState.CANCELED);
jettyRequest.abort(new CancellationException());
return super.cancel(mayInterruptIfRunning);
}
catch (Throwable e) {
setException(e);
return true;
}
}
protected void completed(Response response, InputStream content)
{
if (state.get() == JettyAsyncHttpState.CANCELED) {
return;
}
T value;
try {
value = processResponse(response, content);
}
catch (Throwable e) {
// this will be an instance of E from the response handler or an Error
storeException(e);
return;
}
state.set(JettyAsyncHttpState.DONE);
set(value);
}
private T processResponse(Response response, InputStream content)
throws E
{
// this time will not include the data fetching portion of the response,
// since the response is fully cached in memory at this point
long responseStart = System.nanoTime();
state.set(JettyAsyncHttpState.PROCESSING_RESPONSE);
JettyResponse jettyResponse = null;
T value;
try {
jettyResponse = new JettyResponse(response, content);
value = responseHandler.handle(request, jettyResponse);
}
finally {
recordRequestComplete(stats, request, requestStart, jettyResponse, responseStart);
}
return value;
}
protected void failed(Throwable throwable)
{
if (state.get() == JettyAsyncHttpState.CANCELED) {
return;
}
// give handler a chance to rewrite the exception or return a value instead
if (throwable instanceof Exception) {
try {
T value = responseHandler.handleException(request, (Exception) throwable);
// handler returned a value, store it in the future
state.set(JettyAsyncHttpState.DONE);
set(value);
return;
}
catch (Throwable newThrowable) {
throwable = newThrowable;
}
}
// at this point "throwable" will either be an instance of E
// from the response handler or not an instance of Exception
storeException(throwable);
}
private void storeException(Throwable throwable)
{
if (throwable instanceof CancellationException) {
state.set(JettyAsyncHttpState.CANCELED);
}
else {
state.set(JettyAsyncHttpState.FAILED);
}
if (throwable == null) {
throwable = new Throwable("Throwable is null");
log.error(throwable, "Something is broken");
}
setException(throwable);
}
@Override
public String toString()
{
return toStringHelper(this)
.add("requestStart", requestStart)
.add("state", state)
.add("request", request)
.toString();
}
}
private static void recordRequestComplete(RequestStats requestStats, Request request, long requestStart, JettyResponse response, long responseStart)
{
if (response == null) {
return;
}
Duration responseProcessingTime = Duration.nanosSince(responseStart);
Duration requestProcessingTime = new Duration(responseStart - requestStart, TimeUnit.NANOSECONDS);
requestStats.record(request.getMethod(),
response.getStatusCode(),
response.getBytesRead(),
response.getBytesRead(),
requestProcessingTime,
responseProcessingTime);
}
private static class BodyGeneratorContentProvider
implements ContentProvider
{
private static final ByteBuffer DONE = ByteBuffer.allocate(0);
private static final ByteBuffer EXCEPTION = ByteBuffer.allocate(0);
private final BodyGenerator bodyGenerator;
private final Executor executor;
public BodyGeneratorContentProvider(BodyGenerator bodyGenerator, Executor executor)
{
this.bodyGenerator = bodyGenerator;
this.executor = executor;
}
@Override
public long getLength()
{
return -1;
}
@Override
public Iterator<ByteBuffer> iterator()
{
final BlockingQueue<ByteBuffer> chunks = new ArrayBlockingQueue<>(16);
final AtomicReference<Exception> exception = new AtomicReference<>();
executor.execute(() -> {
BodyGeneratorOutputStream out = new BodyGeneratorOutputStream(chunks);
try {
bodyGenerator.write(out);
out.close();
}
catch (Exception e) {
exception.set(e);
chunks.add(EXCEPTION);
}
});
return new AbstractIterator<ByteBuffer>()
{
@Override
protected ByteBuffer computeNext()
{
ByteBuffer chunk;
try {
chunk = chunks.take();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted", e);
}
if (chunk == EXCEPTION) {
throw Throwables.propagate(exception.get());
}
if (chunk == DONE) {
return endOfData();
}
return chunk;
}
};
}
private final class BodyGeneratorOutputStream
extends OutputStream
{
private final BlockingQueue<ByteBuffer> chunks;
private BodyGeneratorOutputStream(BlockingQueue<ByteBuffer> chunks)
{
this.chunks = chunks;
}
@Override
public void write(int b)
throws IOException
{
try {
// must copy array since it could be reused
chunks.put(ByteBuffer.wrap(new byte[] {(byte) b}));
}
catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
@Override
public void write(byte[] b, int off, int len)
throws IOException
{
try {
// must copy array since it could be reused
byte[] copy = Arrays.copyOfRange(b, off, len);
chunks.put(ByteBuffer.wrap(copy));
}
catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
@Override
public void close()
throws IOException
{
try {
chunks.put(DONE);
}
catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
}
}
private static class BufferingResponseListener
extends Listener.Adapter
{
private final JettyResponseFuture<?, ?> future;
private final int maxLength;
@GuardedBy("this")
private byte[] buffer = new byte[(int) new DataSize(64, Unit.KILOBYTE).toBytes()];
@GuardedBy("this")
private int size;
public BufferingResponseListener(JettyResponseFuture<?, ?> future, int maxLength)
{
this.future = checkNotNull(future, "future is null");
Preconditions.checkArgument(maxLength > 0, "maxLength must be greater than zero");
this.maxLength = maxLength;
}
@Override
public synchronized void onHeaders(Response response)
{
long length = response.getHeaders().getLongField(HttpHeader.CONTENT_LENGTH.asString());
if (length > maxLength) {
response.abort(new ResponseTooLargeException());
}
if (length > buffer.length) {
buffer = Arrays.copyOf(buffer, Ints.saturatedCast(length));
}
}
@Override
public synchronized void onContent(Response response, ByteBuffer content)
{
int length = content.remaining();
int requiredCapacity = size + length;
if (requiredCapacity > buffer.length) {
if (requiredCapacity > maxLength) {
response.abort(new ResponseTooLargeException());
return;
}
// newCapacity = min(log2ceiling(requiredCapacity), maxLength);
int newCapacity = min(Integer.highestOneBit(requiredCapacity) << 1, maxLength);
buffer = Arrays.copyOf(buffer, newCapacity);
}
content.get(buffer, size, length);
size += length;
}
@Override
public synchronized void onComplete(Result result)
{
Throwable throwable = result.getFailure();
if (throwable != null) {
future.failed(throwable);
}
else {
future.completed(result.getResponse(), new ByteArrayInputStream(buffer, 0, size));
}
}
}
/*
* This class is needed because jmxutils only fetches a nested instance object once and holds on to it forever.
* todo remove this when https://github.com/martint/jmxutils/issues/26 is implemented
*/
@ThreadSafe
public static class CachedDistribution
{
private final Supplier<Distribution> distributionSupplier;
@GuardedBy("this")
private Distribution distribution;
@GuardedBy("this")
private long lastUpdate = System.nanoTime();
public CachedDistribution(Supplier<Distribution> distributionSupplier)
{
this.distributionSupplier = distributionSupplier;
}
public synchronized Distribution getDistribution()
{
// refresh stats only once a second
if (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - lastUpdate) > 1000) {
this.distribution = distributionSupplier.get();
this.lastUpdate = System.nanoTime();
}
return distribution;
}
@Managed
public double getMaxError()
{
return getDistribution().getMaxError();
}
@Managed
public double getCount()
{
return getDistribution().getCount();
}
@Managed
public double getTotal()
{
return getDistribution().getTotal();
}
@Managed
public long getP01()
{
return getDistribution().getP01();
}
@Managed
public long getP05()
{
return getDistribution().getP05();
}
@Managed
public long getP10()
{
return getDistribution().getP10();
}
@Managed
public long getP25()
{
return getDistribution().getP25();
}
@Managed
public long getP50()
{
return getDistribution().getP50();
}
@Managed
public long getP75()
{
return getDistribution().getP75();
}
@Managed
public long getP90()
{
return getDistribution().getP90();
}
@Managed
public long getP95()
{
return getDistribution().getP95();
}
@Managed
public long getP99()
{
return getDistribution().getP99();
}
@Managed
public long getMin()
{
return getDistribution().getMin();
}
@Managed
public long getMax()
{
return getDistribution().getMax();
}
@Managed
public Map<Double, Long> getPercentiles()
{
return getDistribution().getPercentiles();
}
}
}
| Add stats and dump for current http client requests
| http-client/src/main/java/io/airlift/http/client/jetty/JettyHttpClient.java | Add stats and dump for current http client requests |
|
Java | apache-2.0 | 4e92cb203e5fe7301fe2387070113260a75639b2 | 0 | teknux-org/jetty-bootstrap,teknux-org/jetty-bootstrap | /*******************************************************************************
* (C) Copyright 2014 Teknux.org (http://teknux.org/).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* "Pierre PINON"
* "Francois EYL"
* "Laurent MARCHAL"
*
*******************************************************************************/
package org.teknux.jettybootstrap;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.teknux.jettybootstrap.configuration.IJettyConfiguration;
import org.teknux.jettybootstrap.configuration.JettyConnector;
import org.teknux.jettybootstrap.configuration.PropertiesJettyConfiguration;
import org.teknux.jettybootstrap.handler.ExplodedWarAppJettyHandler;
import org.teknux.jettybootstrap.handler.JettyHandler;
import org.teknux.jettybootstrap.handler.WarAppFromClasspathJettyHandler;
import org.teknux.jettybootstrap.handler.WarAppJettyHandler;
import org.teknux.jettybootstrap.keystore.JettyKeystore;
import org.teknux.jettybootstrap.keystore.JettyKeystoreException;
import org.teknux.jettybootstrap.utils.PathUtil;
/**
* Main class for easily boostrapping jetty.
*/
public class JettyBootstrap {
private final Logger logger = LoggerFactory.getLogger(JettyBootstrap.class);
private static final String DEFAULT_KEYSTORE_FILENAME = "default.keystore";
private static final String DEFAULT_KEYSTORE_DOMAINNAME = "unknown";
private static final String DEFAULT_KEYSTORE_ALIAS = "jettybootstrap";
private static final String DEFAULT_KEYSTORE_PASSWORD = "jettybootstrap";
private static final String TEMP_DIRECTORY_NAME = ".temp";
public static final File TEMP_DIRECTORY_JARDIR = new File(PathUtil.getJarDir() + File.separator + TEMP_DIRECTORY_NAME);
public static final File TEMP_DIRECTORY_SYSTEMP = new File(System.getProperty("java.io.tmpdir") + File.separator + TEMP_DIRECTORY_NAME);
protected static final File TEMP_DIRECTORY_DEFAULT = TEMP_DIRECTORY_JARDIR;
private static final String RESOURCE_WEBAPP = "/webapp";
private static final String CONTEXT_PATH_ROOT = "/";
private final IJettyConfiguration iJettyConfiguration;
private boolean isInitializedConfiguration = false;
private Server server = null;
private final HandlerList handlers = new HandlerList();
/**
* Shortcut to start Jetty when called within a JAR file containing the WEB-INF folder and needed libraries.
* <p>
* Basically uses {@link #addSelf()} and {@link #startServer()}
*
* @return a new instance of {@link JettyBootstrap}
* @throws JettyBootstrapException
* if an error occurs during the startup
*/
public static JettyBootstrap startSelf() throws JettyBootstrapException {
final JettyBootstrap jettyBootstrap = new JettyBootstrap();
jettyBootstrap.addSelf();
return jettyBootstrap.startServer();
}
/**
* Default constructor using the default {@link PropertiesJettyConfiguration} configuration.
*/
public JettyBootstrap() {
this(null);
}
/**
* Constructor specifiying the configuration properties.
*
* @param iJettyconfiguration
* the {@link IJettyConfiguration} implementation of the configuration
*/
public JettyBootstrap(final IJettyConfiguration iJettyconfiguration) {
if (iJettyconfiguration == null) {
this.iJettyConfiguration = new PropertiesJettyConfiguration();
} else {
this.iJettyConfiguration = iJettyconfiguration.clone();
}
}
/**
* Starts the Jetty Server and join the calling thread according to {@link IJettyConfiguration#isAutoJoinOnStart()}
*
* @return this instance
* @throws JettyBootstrapException
* if an exception occurs during the initialization
* @see #startServer(Boolean)
*/
public JettyBootstrap startServer() throws JettyBootstrapException {
return startServer(null);
}
/**
* Starts the Jetty Server and join the calling thread.
*
* @param join
* <code>true</code> to block the calling thread until the server stops. <code>false</code> otherwise
* @return this instance
* @throws JettyBootstrapException
* if an exception occurs during the initialization
*/
public JettyBootstrap startServer(Boolean join) throws JettyBootstrapException {
logger.info("Starting Server...");
IJettyConfiguration iJettyConfiguration = getInitializedConfiguration();
initServer(iJettyConfiguration);
try {
server.start();
} catch (Exception e) {
throw new JettyBootstrapException(e);
}
// display server addresses
if (iJettyConfiguration.getJettyConnectors().contains(JettyConnector.HTTP)) {
logger.info("http://{}:{}", iJettyConfiguration.getHost(), iJettyConfiguration.getPort());
}
if (iJettyConfiguration.getJettyConnectors().contains(JettyConnector.HTTPS)) {
logger.info("https://{}:{}", iJettyConfiguration.getHost(), iJettyConfiguration.getSslPort());
}
if ((join != null && join) || (join == null && iJettyConfiguration.isAutoJoinOnStart())) {
joinServer();
}
return this;
}
/**
* Blocks the calling thread until the server stops.
*
* @return this instance
* @throws JettyBootstrapException
* if an exception occurs while blocking the thread
*/
public JettyBootstrap joinServer() throws JettyBootstrapException {
try {
if (isServerStarted()) {
logger.debug("Joining Server...");
server.join();
} else {
logger.warn("Can't join Server. Not started");
}
} catch (InterruptedException e) {
throw new JettyBootstrapException(e);
}
return this;
}
/**
* Return if server is started
*
* @return if server is started
*/
public boolean isServerStarted() {
return (server != null && server.isStarted());
}
/**
* Stops the Jetty server.
*
* @return this instance
* @throws JettyBootstrapException
* if an exception occurs while stopping the server or if the server is not started
*/
public JettyBootstrap stopServer() throws JettyBootstrapException {
logger.info("Stopping Server...");
try {
if (isServerStarted()) {
handlers.stop();
server.stop();
logger.info("Server stopped.");
} else {
logger.warn("Can't stop server. Already stopped");
}
} catch (Exception e) {
throw new JettyBootstrapException(e);
}
return this;
}
/**
* Add a War application the default context path {@value #CONTEXT_PATH_ROOT}
*
* @param war
* the path to a war file
* @return WebAppContext
* @throws JettyBootstrapException
* on failure
*/
public WebAppContext addWarApp(String war) throws JettyBootstrapException {
return addWarApp(war, CONTEXT_PATH_ROOT);
}
/**
* Add a War application specifying the context path.
*
* @param war
* the path to a war file
* @param contextPath
* the path (base URL) to make the war available
* @return WebAppContext
* @throws JettyBootstrapException
* on failure
*/
public WebAppContext addWarApp(String war, String contextPath) throws JettyBootstrapException {
WarAppJettyHandler warAppJettyHandler = new WarAppJettyHandler(getInitializedConfiguration());
warAppJettyHandler.setWar(war);
warAppJettyHandler.setContextPath(contextPath);
WebAppContext webAppContext = warAppJettyHandler.getHandler();
handlers.addHandler(webAppContext);
return webAppContext;
}
/**
* Add a War application from the current classpath on the default context path {@value #CONTEXT_PATH_ROOT}
*
* @param warFromClasspath
* the path to a war file in the classpath
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addWarAppFromClasspath(String warFromClasspath) throws JettyBootstrapException {
return addWarAppFromClasspath(warFromClasspath, CONTEXT_PATH_ROOT);
}
/**
* Add a War application from the current classpath specifying the context path.
*
* @param warFromClasspath
* the path to a war file in the classpath
* @param contextPath
* the path (base URL) to make the war available
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addWarAppFromClasspath(String warFromClasspath, String contextPath) throws JettyBootstrapException {
WarAppFromClasspathJettyHandler warAppFromClasspathJettyHandler = new WarAppFromClasspathJettyHandler(getInitializedConfiguration());
warAppFromClasspathJettyHandler.setWarFromClasspath(warFromClasspath);
warAppFromClasspathJettyHandler.setContextPath(contextPath);
WebAppContext webAppContext = warAppFromClasspathJettyHandler.getHandler();
handlers.addHandler(webAppContext);
return webAppContext;
}
/**
* Add an exploded (not packaged) War application on the default context path {@value #CONTEXT_PATH_ROOT}
*
* @param explodedWar
* the exploded war path
* @param descriptor
* the web.xml descriptor path
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addExplodedWarApp(String explodedWar, String descriptor) throws JettyBootstrapException {
return addExplodedWarApp(explodedWar, descriptor, CONTEXT_PATH_ROOT);
}
/**
* Add an exploded (not packaged) War application specifying the context path.
*
* @param explodedWar
* the exploded war path
* @param descriptor
* the web.xml descriptor path
* @param contextPath
* the path (base URL) to make the resource available
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addExplodedWarApp(String explodedWar, String descriptor, String contextPath) throws JettyBootstrapException {
ExplodedWarAppJettyHandler explodedWarAppJettyHandler = new ExplodedWarAppJettyHandler(getInitializedConfiguration());
explodedWarAppJettyHandler.setWebAppBase(explodedWar);
explodedWarAppJettyHandler.setDescriptor(descriptor);
explodedWarAppJettyHandler.setContextPath(contextPath);
WebAppContext webAppContext = explodedWarAppJettyHandler.getHandler();
handlers.addHandler(webAppContext);
return webAppContext;
}
/**
* Add an exploded (not packaged) War application from the current classpath, on the default context path {@value #CONTEXT_PATH_ROOT}
*
* @param explodedWar
* the exploded war path
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addExplodedWarAppFromClasspath(String explodedWar) throws JettyBootstrapException {
return addExplodedWarAppFromClasspath(explodedWar, null);
}
/**
* Add an exploded (not packaged) War application from the current classpath, on the default context path {@value #CONTEXT_PATH_ROOT}
*
* @param explodedWar
* the exploded war path
* @param descriptor
* the web.xml descriptor path
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addExplodedWarAppFromClasspath(String explodedWar, String descriptor) throws JettyBootstrapException {
return addExplodedWarAppFromClasspath(explodedWar, descriptor, CONTEXT_PATH_ROOT);
}
/**
* Add an exploded (not packaged) War application from the current classpath, specifying the context path.
*
* @param explodedWar
* the exploded war path
* @param descriptor
* the web.xml descriptor path
* @param contextPath
* the path (base URL) to make the resource available
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addExplodedWarAppFromClasspath(String explodedWar, String descriptor, String contextPath) throws JettyBootstrapException {
ExplodedWarAppJettyHandler explodedWarAppJettyHandler = new ExplodedWarAppJettyHandler(getInitializedConfiguration());
explodedWarAppJettyHandler.setWebAppBaseFromClasspath(explodedWar);
explodedWarAppJettyHandler.setDescriptor(descriptor);
explodedWarAppJettyHandler.setContextPath(contextPath);
WebAppContext webAppContext = explodedWarAppJettyHandler.getHandler();
handlers.addHandler(webAppContext);
return webAppContext;
}
/**
* Add an exploded War application found from {@value #RESOURCE_WEBAPP} in the current classpath on the default context path {@value #CONTEXT_PATH_ROOT}
*
* @see #addExplodedWarAppFromClasspath(String, String)
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addSelf() throws JettyBootstrapException {
return addExplodedWarAppFromClasspath(RESOURCE_WEBAPP, null);
}
/**
* Add an exploded War application found from {@value #RESOURCE_WEBAPP} in the current classpath specifying the context path.
*
* @see #addExplodedWarAppFromClasspath(String, String, String)
* @param contextPath
* the path (base URL) to make the resource available
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addSelf(String contextPath) throws JettyBootstrapException {
return addExplodedWarAppFromClasspath(RESOURCE_WEBAPP, null, contextPath);
}
/**
* Add Handler
*
* @param handler
* Jetty Handler
* @return Handler
* @throws JettyBootstrapException
* on failed
*/
public Handler addHandler(Handler handler) throws JettyBootstrapException {
JettyHandler jettyHandler = new JettyHandler();
jettyHandler.setHandler(handler);
handlers.addHandler(handler);
return handler;
}
/**
* Get the jetty {@link Server} Object. Calls {@link #initServer(IJettyConfiguration)} if not initialized yet.
*
* @return the contained jetty {@link Server} Object.
* @throws JettyBootstrapException
* if an error occurs during {@link #initServer(IJettyConfiguration)}
*/
public Server getServer() throws JettyBootstrapException {
initServer(getInitializedConfiguration());
return server;
}
/**
* Initialize Jetty server using the given {@link IJettyConfiguration}. Basically creates the server, set connectors, handlers and adds the shutdown hook.
*
* @param iJettyConfiguration
* Jetty Configuration
* @throws JettyBootstrapException
* on failure
*/
protected void initServer(IJettyConfiguration iJettyConfiguration) throws JettyBootstrapException {
if (server == null) {
server = createServer(iJettyConfiguration);
server.setConnectors(createConnectors(iJettyConfiguration, server));
server.setHandler(handlers);
if (iJettyConfiguration.isStopAtShutdown()) {
createShutdownHook(iJettyConfiguration);
}
}
}
/**
* Parse the {@link IJettyConfiguration}, validate the configuration and initialize it if necessary. Clean temp directory if necessary and generates SSL keystore when
* necessary.
*
* @return IJettyConfiguration Jetty Configuration
* @throws JettyBootstrapException
* on failure
*/
protected IJettyConfiguration getInitializedConfiguration() throws JettyBootstrapException {
if (!isInitializedConfiguration) {
logger.debug("Init Configuration...");
logger.trace("Check Temp Directory...");
if (iJettyConfiguration.getTempDirectory() == null) {
iJettyConfiguration.setTempDirectory(TEMP_DIRECTORY_DEFAULT);
}
if (iJettyConfiguration.getTempDirectory().exists() && iJettyConfiguration.isCleanTempDir()) {
logger.trace("Clean Temp Directory...");
try {
FileUtils.deleteDirectory(iJettyConfiguration.getTempDirectory());
} catch (IOException e) {
throw new JettyBootstrapException("Can't clean temporary directory");
}
}
if (!iJettyConfiguration.getTempDirectory().exists() && !iJettyConfiguration.getTempDirectory().mkdirs()) {
throw new JettyBootstrapException("Can't create temporary directory");
}
logger.trace("Check required properties...");
if (iJettyConfiguration.getHost() == null || iJettyConfiguration.getHost().isEmpty()) {
throw new JettyBootstrapException("Host not specified");
}
logger.trace("Check connectors...");
if (iJettyConfiguration.hasJettyConnector(JettyConnector.HTTPS) &&
(iJettyConfiguration.getSslKeyStorePath() == null || iJettyConfiguration.getSslKeyStorePath().isEmpty())) {
File keystoreFile = new File(iJettyConfiguration.getTempDirectory().getPath() + File.separator + DEFAULT_KEYSTORE_FILENAME);
if (!keystoreFile.exists()) {
try {
JettyKeystore jettyKeystore = new JettyKeystore(DEFAULT_KEYSTORE_DOMAINNAME, DEFAULT_KEYSTORE_ALIAS, DEFAULT_KEYSTORE_PASSWORD);
jettyKeystore.generateAndSave(keystoreFile);
} catch (JettyKeystoreException e) {
throw new JettyBootstrapException("Can't generate keyStore", e);
}
}
iJettyConfiguration.setSslKeyStorePath(keystoreFile.getPath());
iJettyConfiguration.setSslKeyStorePassword(DEFAULT_KEYSTORE_PASSWORD);
}
if (iJettyConfiguration.isRedirectWebAppsOnHttpsConnector() &&
(!iJettyConfiguration.hasJettyConnector(JettyConnector.HTTP) || !iJettyConfiguration.hasJettyConnector(JettyConnector.HTTPS))) {
throw new JettyBootstrapException("You can't redirect all from HTTP to HTTPS Connector if both connectors are not setted");
}
isInitializedConfiguration = true;
logger.trace("Configuration : {}", iJettyConfiguration);
}
return iJettyConfiguration;
}
/**
* Convenient method used to build and return a new {@link Server}.
*
* @param iJettyConfiguration
* Jetty Configuration
* @return Server
*/
protected Server createServer(IJettyConfiguration iJettyConfiguration) {
logger.trace("Create Jetty Server...");
Server server = new Server(new QueuedThreadPool(iJettyConfiguration.getMaxThreads()));
server.setStopAtShutdown(false); // Reimplemented. See
// @IJettyConfiguration.stopAtShutdown
server.setStopTimeout(iJettyConfiguration.getStopTimeout());
return server;
}
/**
* Creates and returns the necessary {@link ServerConnector} based on the given {@link IJettyConfiguration}.
*
* @param iJettyConfiguration
* Jetty Configuration
* @param server
* the server to
* @return Connector[]
*/
protected Connector[] createConnectors(IJettyConfiguration iJettyConfiguration, Server server) {
logger.trace("Creating Jetty Connectors...");
List<Connector> connectors = new ArrayList<Connector>();
if (iJettyConfiguration.hasJettyConnector(JettyConnector.HTTP)) {
logger.trace("Adding HTTP Connector...");
ServerConnector serverConnector;
if (iJettyConfiguration.hasJettyConnector(JettyConnector.HTTPS)) {
HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.setSecurePort(iJettyConfiguration.getSslPort());
httpConfiguration.setSecureScheme(HttpScheme.HTTPS.asString());
HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory(httpConfiguration);
serverConnector = new ServerConnector(server, httpConnectionFactory);
} else {
serverConnector = new ServerConnector(server);
}
serverConnector.setIdleTimeout(iJettyConfiguration.getIdleTimeout());
serverConnector.setHost(iJettyConfiguration.getHost());
serverConnector.setPort(iJettyConfiguration.getPort());
connectors.add(serverConnector);
}
if (iJettyConfiguration.hasJettyConnector(JettyConnector.HTTPS)) {
logger.trace("Adding HTTPS Connector...");
SslContextFactory sslContextFactory = new SslContextFactory(iJettyConfiguration.getSslKeyStorePath());
sslContextFactory.setKeyStorePassword(iJettyConfiguration.getSslKeyStorePassword());
ServerConnector serverConnector = new ServerConnector(server, sslContextFactory);
serverConnector.setIdleTimeout(iJettyConfiguration.getIdleTimeout());
serverConnector.setHost(iJettyConfiguration.getHost());
serverConnector.setPort(iJettyConfiguration.getSslPort());
connectors.add(serverConnector);
}
return connectors.toArray(new Connector[connectors.size()]);
}
/**
* Create Shutdown Hook.
*
* @param iJettyConfiguration
* Jetty Configuration
*/
private void createShutdownHook(final IJettyConfiguration iJettyConfiguration) {
logger.trace("Creating Jetty ShutdownHook...");
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
logger.debug("Shutting Down...");
stopServer();
} catch (Exception e) {
logger.error("Shutdown", e);
}
}
});
}
}
| jetty-bootstrap/src/main/java/org/teknux/jettybootstrap/JettyBootstrap.java | /*******************************************************************************
* (C) Copyright 2014 Teknux.org (http://teknux.org/).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* "Pierre PINON"
* "Francois EYL"
* "Laurent MARCHAL"
*
*******************************************************************************/
package org.teknux.jettybootstrap;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.teknux.jettybootstrap.configuration.IJettyConfiguration;
import org.teknux.jettybootstrap.configuration.JettyConnector;
import org.teknux.jettybootstrap.configuration.PropertiesJettyConfiguration;
import org.teknux.jettybootstrap.handler.ExplodedWarAppJettyHandler;
import org.teknux.jettybootstrap.handler.JettyHandler;
import org.teknux.jettybootstrap.handler.WarAppFromClasspathJettyHandler;
import org.teknux.jettybootstrap.handler.WarAppJettyHandler;
import org.teknux.jettybootstrap.keystore.JettyKeystore;
import org.teknux.jettybootstrap.keystore.JettyKeystoreException;
import org.teknux.jettybootstrap.utils.PathUtil;
/**
* Main class for easily boostrapping jetty.
*/
public class JettyBootstrap {
private final Logger logger = LoggerFactory.getLogger(JettyBootstrap.class);
private static final String DEFAULT_KEYSTORE_FILENAME = "default.keystore";
private static final String DEFAULT_KEYSTORE_DOMAINNAME = "unknown";
private static final String DEFAULT_KEYSTORE_ALIAS = "jettybootstrap";
private static final String DEFAULT_KEYSTORE_PASSWORD = "jettybootstrap";
private static final String TEMP_DIRECTORY_NAME = ".temp";
public static final File TEMP_DIRECTORY_JARDIR = new File(PathUtil.getJarDir() + File.separator + TEMP_DIRECTORY_NAME);
public static final File TEMP_DIRECTORY_SYSTEMP = new File(System.getProperty("java.io.tmpdir") + File.separator + TEMP_DIRECTORY_NAME);
protected static final File TEMP_DIRECTORY_DEFAULT = TEMP_DIRECTORY_JARDIR;
private static final String RESOURCE_WEBAPP = "/webapp";
private static final String CONTEXT_PATH_ROOT = "/";
private final IJettyConfiguration iJettyConfiguration;
private boolean isInitializedConfiguration = false;
private Server server = null;
private final HandlerList handlers = new HandlerList();
/**
* Shortcut to start Jetty when called within a JAR file containing the WEB-INF folder and needed libraries.
* <p>
* Basically uses {@link #addSelf()} and {@link #startServer()}
*
* @return a new instance of {@link JettyBootstrap}
* @throws JettyBootstrapException
* if an error occurs during the startup
*/
public static JettyBootstrap startSelf() throws JettyBootstrapException {
final JettyBootstrap jettyBootstrap = new JettyBootstrap();
jettyBootstrap.addSelf();
return jettyBootstrap.startServer();
}
/**
* Default constructor using the default {@link PropertiesJettyConfiguration} configuration.
*/
public JettyBootstrap() {
this(null);
}
/**
* Constructor specifiying the configuration properties.
*
* @param iJettyconfiguration
* the {@link IJettyConfiguration} implementation of the configuration
*/
public JettyBootstrap(final IJettyConfiguration iJettyconfiguration) {
if (iJettyconfiguration == null) {
this.iJettyConfiguration = new PropertiesJettyConfiguration();
} else {
this.iJettyConfiguration = iJettyconfiguration.clone();
}
}
/**
* Starts the Jetty Server and join the calling thread according to {@link IJettyConfiguration#isAutoJoinOnStart()}
*
* @return this instance
* @throws JettyBootstrapException
* if an exception occurs during the initialization
* @see #startServer(Boolean)
*/
public JettyBootstrap startServer() throws JettyBootstrapException {
return startServer(null);
}
/**
* Starts the Jetty Server and join the calling thread.
*
* @param join
* <code>true</code> to block the calling thread until the server stops. <code>false</code> otherwise
* @return this instance
* @throws JettyBootstrapException
* if an exception occurs during the initialization
*/
public JettyBootstrap startServer(Boolean join) throws JettyBootstrapException {
logger.info("Starting Server...");
IJettyConfiguration iJettyConfiguration = getConfiguration();
initServer(iJettyConfiguration);
try {
server.start();
} catch (Exception e) {
throw new JettyBootstrapException(e);
}
// display server addresses
if (iJettyConfiguration.getJettyConnectors().contains(JettyConnector.HTTP)) {
logger.info("http://{}:{}", iJettyConfiguration.getHost(), iJettyConfiguration.getPort());
}
if (iJettyConfiguration.getJettyConnectors().contains(JettyConnector.HTTPS)) {
logger.info("https://{}:{}", iJettyConfiguration.getHost(), iJettyConfiguration.getSslPort());
}
if ((join != null && join) || (join == null && iJettyConfiguration.isAutoJoinOnStart())) {
joinServer();
}
return this;
}
/**
* Blocks the calling thread until the server stops.
*
* @return this instance
* @throws JettyBootstrapException
* if an exception occurs while blocking the thread
*/
public JettyBootstrap joinServer() throws JettyBootstrapException {
try {
if (isServerStarted()) {
logger.debug("Joining Server...");
server.join();
} else {
logger.warn("Can't join Server. Not started");
}
} catch (InterruptedException e) {
throw new JettyBootstrapException(e);
}
return this;
}
/**
* Return if server is started
*
* @return if server is started
*/
public boolean isServerStarted() {
return (server != null && server.isStarted());
}
/**
* Stops the Jetty server.
*
* @return this instance
* @throws JettyBootstrapException
* if an exception occurs while stopping the server or if the server is not started
*/
public JettyBootstrap stopServer() throws JettyBootstrapException {
logger.info("Stopping Server...");
try {
if (isServerStarted()) {
handlers.stop();
server.stop();
logger.info("Server stopped.");
} else {
logger.warn("Can't stop server. Already stopped");
}
} catch (Exception e) {
throw new JettyBootstrapException(e);
}
return this;
}
/**
* Add a War application the default context path {@value #CONTEXT_PATH_ROOT}
*
* @param war
* the path to a war file
* @return WebAppContext
* @throws JettyBootstrapException
* on failure
*/
public WebAppContext addWarApp(String war) throws JettyBootstrapException {
return addWarApp(war, CONTEXT_PATH_ROOT);
}
/**
* Add a War application specifying the context path.
*
* @param war
* the path to a war file
* @param contextPath
* the path (base URL) to make the war available
* @return WebAppContext
* @throws JettyBootstrapException
* on failure
*/
public WebAppContext addWarApp(String war, String contextPath) throws JettyBootstrapException {
WarAppJettyHandler warAppJettyHandler = new WarAppJettyHandler(getConfiguration());
warAppJettyHandler.setWar(war);
warAppJettyHandler.setContextPath(contextPath);
WebAppContext webAppContext = warAppJettyHandler.getHandler();
handlers.addHandler(webAppContext);
return webAppContext;
}
/**
* Add a War application from the current classpath on the default context path {@value #CONTEXT_PATH_ROOT}
*
* @param warFromClasspath
* the path to a war file in the classpath
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addWarAppFromClasspath(String warFromClasspath) throws JettyBootstrapException {
return addWarAppFromClasspath(warFromClasspath, CONTEXT_PATH_ROOT);
}
/**
* Add a War application from the current classpath specifying the context path.
*
* @param warFromClasspath
* the path to a war file in the classpath
* @param contextPath
* the path (base URL) to make the war available
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addWarAppFromClasspath(String warFromClasspath, String contextPath) throws JettyBootstrapException {
WarAppFromClasspathJettyHandler warAppFromClasspathJettyHandler = new WarAppFromClasspathJettyHandler(getConfiguration());
warAppFromClasspathJettyHandler.setWarFromClasspath(warFromClasspath);
warAppFromClasspathJettyHandler.setContextPath(contextPath);
WebAppContext webAppContext = warAppFromClasspathJettyHandler.getHandler();
handlers.addHandler(webAppContext);
return webAppContext;
}
/**
* Add an exploded (not packaged) War application on the default context path {@value #CONTEXT_PATH_ROOT}
*
* @param explodedWar
* the exploded war path
* @param descriptor
* the web.xml descriptor path
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addExplodedWarApp(String explodedWar, String descriptor) throws JettyBootstrapException {
return addExplodedWarApp(explodedWar, descriptor, CONTEXT_PATH_ROOT);
}
/**
* Add an exploded (not packaged) War application specifying the context path.
*
* @param explodedWar
* the exploded war path
* @param descriptor
* the web.xml descriptor path
* @param contextPath
* the path (base URL) to make the resource available
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addExplodedWarApp(String explodedWar, String descriptor, String contextPath) throws JettyBootstrapException {
ExplodedWarAppJettyHandler explodedWarAppJettyHandler = new ExplodedWarAppJettyHandler(getConfiguration());
explodedWarAppJettyHandler.setWebAppBase(explodedWar);
explodedWarAppJettyHandler.setDescriptor(descriptor);
explodedWarAppJettyHandler.setContextPath(contextPath);
WebAppContext webAppContext = explodedWarAppJettyHandler.getHandler();
handlers.addHandler(webAppContext);
return webAppContext;
}
/**
* Add an exploded (not packaged) War application from the current classpath, on the default context path {@value #CONTEXT_PATH_ROOT}
*
* @param explodedWar
* the exploded war path
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addExplodedWarAppFromClasspath(String explodedWar) throws JettyBootstrapException {
return addExplodedWarAppFromClasspath(explodedWar, null);
}
/**
* Add an exploded (not packaged) War application from the current classpath, on the default context path {@value #CONTEXT_PATH_ROOT}
*
* @param explodedWar
* the exploded war path
* @param descriptor
* the web.xml descriptor path
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addExplodedWarAppFromClasspath(String explodedWar, String descriptor) throws JettyBootstrapException {
return addExplodedWarAppFromClasspath(explodedWar, descriptor, CONTEXT_PATH_ROOT);
}
/**
* Add an exploded (not packaged) War application from the current classpath, specifying the context path.
*
* @param explodedWar
* the exploded war path
* @param descriptor
* the web.xml descriptor path
* @param contextPath
* the path (base URL) to make the resource available
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addExplodedWarAppFromClasspath(String explodedWar, String descriptor, String contextPath) throws JettyBootstrapException {
ExplodedWarAppJettyHandler explodedWarAppJettyHandler = new ExplodedWarAppJettyHandler(getConfiguration());
explodedWarAppJettyHandler.setWebAppBaseFromClasspath(explodedWar);
explodedWarAppJettyHandler.setDescriptor(descriptor);
explodedWarAppJettyHandler.setContextPath(contextPath);
WebAppContext webAppContext = explodedWarAppJettyHandler.getHandler();
handlers.addHandler(webAppContext);
return webAppContext;
}
/**
* Add an exploded War application found from {@value #RESOURCE_WEBAPP} in the current classpath on the default context path {@value #CONTEXT_PATH_ROOT}
*
* @see #addExplodedWarAppFromClasspath(String, String)
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addSelf() throws JettyBootstrapException {
return addExplodedWarAppFromClasspath(RESOURCE_WEBAPP, null);
}
/**
* Add an exploded War application found from {@value #RESOURCE_WEBAPP} in the current classpath specifying the context path.
*
* @see #addExplodedWarAppFromClasspath(String, String, String)
* @param contextPath
* the path (base URL) to make the resource available
* @return WebAppContext
* @throws JettyBootstrapException
* on failed
*/
public WebAppContext addSelf(String contextPath) throws JettyBootstrapException {
return addExplodedWarAppFromClasspath(RESOURCE_WEBAPP, null, contextPath);
}
/**
* Add Handler
*
* @param handler
* Jetty Handler
* @return Handler
* @throws JettyBootstrapException
* on failed
*/
public Handler addHandler(Handler handler) throws JettyBootstrapException {
JettyHandler jettyHandler = new JettyHandler();
jettyHandler.setHandler(handler);
handlers.addHandler(handler);
return handler;
}
/**
* Get the jetty {@link Server} Object. Calls {@link #initServer(IJettyConfiguration)} if not initialized yet.
*
* @return the contained jetty {@link Server} Object.
* @throws JettyBootstrapException
* if an error occurs during {@link #initServer(IJettyConfiguration)}
*/
public Server getServer() throws JettyBootstrapException {
initServer(getConfiguration());
return server;
}
/**
* Initialize Jetty server using the given {@link IJettyConfiguration}. Basically creates the server, set connectors, handlers and adds the shutdown hook.
*
* @param iJettyConfiguration
* Jetty Configuration
* @throws JettyBootstrapException
* on failure
*/
protected void initServer(IJettyConfiguration iJettyConfiguration) throws JettyBootstrapException {
if (server == null) {
server = createServer(iJettyConfiguration);
server.setConnectors(createConnectors(iJettyConfiguration, server));
server.setHandler(handlers);
createShutdownHook(iJettyConfiguration);
}
}
/**
* Parse the {@link IJettyConfiguration}, validate the configuration and initialize it if necessary. Clean temp directory if necessary and generates SSL keystore when
* necessary.
*
* @return IJettyConfiguration Jetty Configuration
* @throws JettyBootstrapException
* on failure
*/
protected IJettyConfiguration getConfiguration() throws JettyBootstrapException {
if (!isInitializedConfiguration) {
logger.debug("Init Configuration...");
logger.trace("Check Temp Directory...");
if (iJettyConfiguration.getTempDirectory() == null) {
iJettyConfiguration.setTempDirectory(TEMP_DIRECTORY_DEFAULT);
}
if (iJettyConfiguration.getTempDirectory().exists() && iJettyConfiguration.isCleanTempDir()) {
logger.trace("Clean Temp Directory...");
try {
FileUtils.deleteDirectory(iJettyConfiguration.getTempDirectory());
} catch (IOException e) {
throw new JettyBootstrapException("Can't clean temporary directory");
}
}
if (!iJettyConfiguration.getTempDirectory().exists() && !iJettyConfiguration.getTempDirectory().mkdirs()) {
throw new JettyBootstrapException("Can't create temporary directory");
}
logger.trace("Check required properties...");
if (iJettyConfiguration.getHost() == null || iJettyConfiguration.getHost().isEmpty()) {
throw new JettyBootstrapException("Host not specified");
}
logger.trace("Check connectors...");
if (iJettyConfiguration.hasJettyConnector(JettyConnector.HTTPS) &&
(iJettyConfiguration.getSslKeyStorePath() == null || iJettyConfiguration.getSslKeyStorePath().isEmpty())) {
File keystoreFile = new File(iJettyConfiguration.getTempDirectory().getPath() + File.separator + DEFAULT_KEYSTORE_FILENAME);
if (!keystoreFile.exists()) {
try {
JettyKeystore jettyKeystore = new JettyKeystore(DEFAULT_KEYSTORE_DOMAINNAME, DEFAULT_KEYSTORE_ALIAS, DEFAULT_KEYSTORE_PASSWORD);
jettyKeystore.generateAndSave(keystoreFile);
} catch (JettyKeystoreException e) {
throw new JettyBootstrapException("Can't generate keyStore", e);
}
}
iJettyConfiguration.setSslKeyStorePath(keystoreFile.getPath());
iJettyConfiguration.setSslKeyStorePassword(DEFAULT_KEYSTORE_PASSWORD);
}
if (iJettyConfiguration.isRedirectWebAppsOnHttpsConnector() &&
(!iJettyConfiguration.hasJettyConnector(JettyConnector.HTTP) || !iJettyConfiguration.hasJettyConnector(JettyConnector.HTTPS))) {
throw new JettyBootstrapException("You can't redirect all from HTTP to HTTPS Connector if both connectors are not setted");
}
isInitializedConfiguration = true;
logger.trace("Configuration : {}", iJettyConfiguration);
}
return iJettyConfiguration;
}
/**
* Convenient method used to build and return a new {@link Server}.
*
* @param iJettyConfiguration
* Jetty Configuration
* @return Server
*/
protected Server createServer(IJettyConfiguration iJettyConfiguration) {
logger.trace("Create Jetty Server...");
Server server = new Server(new QueuedThreadPool(iJettyConfiguration.getMaxThreads()));
server.setStopAtShutdown(false); // Reimplemented. See
// @IJettyConfiguration.stopAtShutdown
server.setStopTimeout(iJettyConfiguration.getStopTimeout());
return server;
}
/**
* Creates and returns the necessary {@link ServerConnector} based on the given {@link IJettyConfiguration}.
*
* @param iJettyConfiguration
* Jetty Configuration
* @param server
* the server to
* @return Connector[]
*/
protected Connector[] createConnectors(IJettyConfiguration iJettyConfiguration, Server server) {
logger.trace("Creating Jetty Connectors...");
List<Connector> connectors = new ArrayList<Connector>();
if (iJettyConfiguration.hasJettyConnector(JettyConnector.HTTP)) {
logger.trace("Adding HTTP Connector...");
ServerConnector serverConnector;
if (iJettyConfiguration.hasJettyConnector(JettyConnector.HTTPS)) {
HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.setSecurePort(iJettyConfiguration.getSslPort());
httpConfiguration.setSecureScheme(HttpScheme.HTTPS.asString());
HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory(httpConfiguration);
serverConnector = new ServerConnector(server, httpConnectionFactory);
} else {
serverConnector = new ServerConnector(server);
}
serverConnector.setIdleTimeout(iJettyConfiguration.getIdleTimeout());
serverConnector.setHost(iJettyConfiguration.getHost());
serverConnector.setPort(iJettyConfiguration.getPort());
connectors.add(serverConnector);
}
if (iJettyConfiguration.hasJettyConnector(JettyConnector.HTTPS)) {
logger.trace("Adding HTTPS Connector...");
SslContextFactory sslContextFactory = new SslContextFactory(iJettyConfiguration.getSslKeyStorePath());
sslContextFactory.setKeyStorePassword(iJettyConfiguration.getSslKeyStorePassword());
ServerConnector serverConnector = new ServerConnector(server, sslContextFactory);
serverConnector.setIdleTimeout(iJettyConfiguration.getIdleTimeout());
serverConnector.setHost(iJettyConfiguration.getHost());
serverConnector.setPort(iJettyConfiguration.getSslPort());
connectors.add(serverConnector);
}
return connectors.toArray(new Connector[connectors.size()]);
}
/**
* Convenient method used to gracefully stop Jetty server. Invoked by the registered shutdown hook.
*
* @param iJettyConfiguration
* Jetty Configuration
*/
protected void shutdown(IJettyConfiguration iJettyConfiguration) {
try {
if (iJettyConfiguration.isStopAtShutdown()) {
logger.debug("Shutting Down...");
stopServer();
}
} catch (Exception e) {
logger.error("Shutdown", e);
}
}
/**
* Create Shutdown Hook.
*
* @param iJettyConfiguration
* Jetty Configuration
*/
private void createShutdownHook(final IJettyConfiguration iJettyConfiguration) {
logger.trace("Creating Jetty ShutdownHook...");
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
shutdown(iJettyConfiguration);
}
});
}
}
| - Don't add Shutdown hook if stopAtShutdown is not setted on
configuration
| jetty-bootstrap/src/main/java/org/teknux/jettybootstrap/JettyBootstrap.java | - Don't add Shutdown hook if stopAtShutdown is not setted on configuration |
|
Java | apache-2.0 | 73475dea9ae773eefb22b2cc4fb9cec56737be05 | 0 | wendal/nutz-book-project,sunhai1988/nutz-book-project,wendal/nutz-book-project,sunhai1988/nutz-book-project,sunhai1988/nutz-book-project,wendal/nutz-book-project,sunhai1988/nutz-book-project,wendal/nutz-book-project | package net.wendal.nutzbook.service.yvr;
import static net.wendal.nutzbook.bean.CResult._fail;
import static net.wendal.nutzbook.bean.CResult._ok;
import static net.wendal.nutzbook.util.RedisInterceptor.jedis;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.FieldFilter;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.Daos;
import org.nutz.integration.zbus.ZBusProducer;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.lang.Strings;
import org.nutz.lang.random.R;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import net.wendal.nutzbook.bean.CResult;
import net.wendal.nutzbook.bean.User;
import net.wendal.nutzbook.bean.UserProfile;
import net.wendal.nutzbook.bean.yvr.Topic;
import net.wendal.nutzbook.bean.yvr.TopicReply;
import net.wendal.nutzbook.bean.yvr.TopicTag;
import net.wendal.nutzbook.bean.yvr.TopicType;
import net.wendal.nutzbook.service.PushService;
import net.wendal.nutzbook.util.RedisKey;
import net.wendal.nutzbook.util.Toolkit;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
@IocBean(create="init")
public class YvrService implements RedisKey {
private static final Log log = Logs.get();
@Inject
protected Dao dao;
// 用于查询Topic和TopicReply时不查询content属性
protected Dao daoNoContent;
@Inject
protected TopicSearchService topicSearchService;
@Inject
protected PushService pushService;
// TODO 改成发布-订阅模式
@Inject("java:$zbus.getProducer('topic-watch')")
protected ZBusProducer topicWatchProducer;
@Inject("java:$conf.get('topic.image.dir')")
protected String imageDir;
@Inject("java:$conf.get('topic.global.watchers')")
protected String topicGlobalWatchers;
protected Set<Integer> globalWatcherIds = new HashSet<>();
@Aop("redis")
public void fillTopic(Topic topic, Map<Integer, UserProfile> authors) {
if (topic.getUserId() == 0)
topic.setUserId(1);
topic.setAuthor(_cacheFetch(authors, topic.getUserId()));
Double reply_count = jedis().zscore(RKEY_REPLY_COUNT, topic.getId());
topic.setReplyCount(reply_count == null ? 0 : reply_count.intValue());
if (topic.getReplyCount() > 0) {
String replyId = jedis().hget(RKEY_REPLY_LAST, topic.getId());
TopicReply reply = daoNoContent.fetch(TopicReply.class, replyId);
if (reply != null) {
if (reply.getUserId() == 0)
reply.setUserId(1);
reply.setAuthor(_cacheFetch(authors, reply.getUserId()));
topic.setLastComment(reply);
}
}
Double visited = jedis().zscore(RKEY_TOPIC_VISIT, topic.getId());
topic.setVisitCount((visited == null) ? 0 : visited.intValue());
}
protected UserProfile _cacheFetch(Map<Integer, UserProfile> authors, int userId) {
if (authors == null)
return null;
UserProfile author = authors.get(userId);
if (author == null) {
author = dao.fetch(UserProfile.class, userId);
authors.put(userId, author);
}
return author;
}
@Aop("redis")
public String accessToken(String loginname) {
return jedis().hget(RKEY_USER_ACCESSTOKEN, loginname);
}
@Aop("redis")
public String accessToken(UserProfile profile) {
String loginname = profile.getLoginname();
String at = jedis().hget(RKEY_USER_ACCESSTOKEN, loginname);
if (at == null) {
// 双向绑定
at = R.UU32();
jedis().hset(RKEY_USER_ACCESSTOKEN, loginname, at);
jedis().hset(RKEY_USER_ACCESSTOKEN2, at, loginname);
jedis().hset(RKEY_USER_ACCESSTOKEN3, at, ""+profile.getUserId());
}
return at;
}
@Aop("redis")
public void resetAccessToken(String loginname) {
String at = jedis().hget(RKEY_USER_ACCESSTOKEN, loginname); {
jedis().hdel(RKEY_USER_ACCESSTOKEN, loginname);
jedis().hdel(RKEY_USER_ACCESSTOKEN2, at);
jedis().hdel(RKEY_USER_ACCESSTOKEN3, at);
}
}
@Aop("redis")
public int getUserByAccessToken(String at) {
String uid_str = jedis().hget(RKEY_USER_ACCESSTOKEN3, at);
if (uid_str == null)
return -1;
return Integer.parseInt(uid_str);
}
@Aop("redis")
public CResult add(Topic topic, int userId) {
if (userId < 1) {
return _fail("请先登录");
}
if (Strings.isBlank(topic.getTitle()) || topic.getTitle().length() > 100 || topic.getTitle().length() < 5) {
return _fail("标题长度不合法");
}
if (Strings.isBlank(topic.getContent()) || topic.getContent().length() > 20000) {
return _fail("内容不合法");
}
if (topic.getTags() != null && topic.getTags().size() > 10) {
return _fail("最多只能有10个tag");
}
if (0 != dao.count(Topic.class, Cnd.where("title", "=", topic.getTitle().trim()))) {
return _fail("相同标题已经发过了");
}
topic.setTitle(Strings.escapeHtml(topic.getTitle().trim()));
topic.setUserId(userId);
topic.setTop(false);
topic.setTags(new HashSet<>());
if (topic.getType() == null)
topic.setType(TopicType.ask);
topic.setContent(Toolkit.filteContent(topic.getContent()));
dao.insert(topic);
try {
topicSearchService.add(topic);
} catch (Exception e) {
}
// 如果是ask类型,把帖子加入到 "未回复"列表
Pipeline pipe = jedis().pipelined();
if (TopicType.ask.equals(topic.getType())) {
pipe.zadd(RKEY_TOPIC_NOREPLY, System.currentTimeMillis(), topic.getId());
}
pipe.zadd(RKEY_TOPIC_UPDATE + topic.getType(), System.currentTimeMillis(), topic.getId());
pipe.zadd(RKEY_TOPIC_UPDATE_ALL, System.currentTimeMillis(), topic.getId());
pipe.zincrby(RKEY_USER_SCORE, 100, ""+userId);
pipe.sync();
for (Integer watcherId : globalWatcherIds) {
if (watcherId != userId)
pushUser(watcherId, "新帖:" + topic.getTitle(), topic.getId());
}
return _ok(topic.getId());
}
@Aop("redis")
public CResult addReply(final String topicId, final TopicReply reply, final int userId) {
if (userId < 1)
return _fail("请先登录");
if (reply == null || reply.getContent() == null || reply.getContent().trim().isEmpty()) {
return _fail("内容不能为空");
}
final String cnt = reply.getContent().trim();
if (cnt.length() < 2 || cnt.length() > 10000) {
return _fail("内容太长或太短了");
}
final Topic topic = daoNoContent.fetch(Topic.class, topicId); // TODO 改成只fetch出type属性
if (topic == null) {
return _fail("主题不存在");
}
reply.setTopicId(topicId);
reply.setUserId(userId);
reply.setContent(Toolkit.filteContent(reply.getContent()));
dao.insert(reply);
// 更新topic的时间戳
Pipeline pipe = jedis().pipelined();
if (topic.isTop()) {
pipe.zadd(RKEY_TOPIC_TOP, reply.getCreateTime().getTime(), topicId);
} else {
pipe.zadd(RKEY_TOPIC_UPDATE + topic.getType(), reply.getCreateTime().getTime(), topicId);
pipe.zadd(RKEY_TOPIC_UPDATE_ALL, reply.getCreateTime().getTime(), topicId);
}
pipe.zrem(RKEY_TOPIC_NOREPLY, topicId);
if (topic.getTags() != null) {
for (String tag : topic.getTags()) {
pipe.zadd(RKEY_TOPIC_TAG+tag.toLowerCase().trim(), reply.getCreateTime().getTime(), topicId);
}
}
pipe.hset(RKEY_REPLY_LAST, topicId, reply.getId());
pipe.zincrby(RKEY_REPLY_COUNT, 1, topicId);
pipe.zincrby(RKEY_USER_SCORE, 10, ""+userId);
pipe.sync();
// 通知页面刷新
topicWatchProducer.async(topicId);
String replyAuthorName = dao.fetch(User.class, userId).getName();
// 通知原本的作者
if (topic.getUserId() != userId) {
String alert = replyAuthorName + "回复了您的帖子";
pushUser(topic.getUserId(), alert, topicId);
}
Set<String> ats = findAt(cnt, 5);
for (String at : ats) {
User user = dao.fetch(User.class, at);
if (user == null)
continue;
if (topic.getUserId() == user.getId())
continue; // 前面已经发过了
if (userId == user.getId())
continue; // 自己@自己, 忽略
String alert = replyAuthorName + "在帖子回复中@了你";
pushUser(user.getId(), alert, topicId);
}
return _ok(reply.getId());
}
@Aop("redis")
public CResult replyUp(String replyId, int userId) {
if (userId < 1)
return _fail("你还没登录呢");
if (1 != dao.count(TopicReply.class, Cnd.where("id", "=", replyId))) {
return _fail("没这条评论");
}
String key = RKEY_REPLY_LIKE + replyId;
Double t = jedis().zscore(key, "" + userId);
if (t != null) {
jedis().zrem(key, userId + "");
return _ok("down");
} else {
jedis().zadd(key, System.currentTimeMillis(), userId + "");
return _ok("up");
}
}
protected void pushUser(int userId, String alert, String topic_id) {
Map<String, String> extras = new HashMap<String, String>();
extras.put("topic_id", topic_id);
pushService.alert(userId, alert, extras);
}
public List<Topic> getRecentTopics(int userId) {
List<Topic> recent_topics = daoNoContent().query(Topic.class, Cnd.where("userId", "=", userId).desc("createTime"), dao.createPager(1, 5));
Map<Integer, UserProfile> authors = new HashMap<Integer, UserProfile>();
if (!recent_topics.isEmpty()) {
for (Topic topic : recent_topics) {
fillTopic(topic, authors);
}
}
return recent_topics;
}
public List<Topic> getRecentReplyTopics(int userId) {
Map<Integer, UserProfile> authors = new HashMap<Integer, UserProfile>();
Sql sql = Sqls.queryString("select DISTINCT topicId from t_topic_reply $cnd").setEntity(dao.getEntity(TopicReply.class)).setVar("cnd", Cnd.where("userId", "=", userId).desc("createTime"));
sql.setPager(dao.createPager(1, 5));
String[] replies_topic_ids = dao.execute(sql).getObject(String[].class);
List<Topic> recent_replies = new ArrayList<Topic>();
for (String topic_id : replies_topic_ids) {
Topic _topic = dao.fetch(Topic.class, topic_id);
if (_topic == null)
continue;
recent_replies.add(_topic);
}
if (!recent_replies.isEmpty()) {
for (Topic topic : recent_replies) {
fillTopic(topic, authors);
}
}
return recent_replies;
}
@Aop("redis")
public int getUserScore(int userId) {
Double score = jedis().zscore(RKEY_USER_SCORE, ""+userId);
if (score == null) {
return 0;
} else {
return score.intValue();
}
}
public NutMap upload(TempFile tmp, int userId) throws IOException {
NutMap re = new NutMap();
if (userId < 1)
return re.setv("msg", "请先登陆!");
if (tmp == null || tmp.getFile().length() == 0) {
return re.setv("msg", "空文件");
}
if (tmp.getFile().length() > 5 * 1024 * 1024) {
return re.setv("msg", "文件太大了");
}
String id = R.UU32();
String path = "/" + id.substring(0, 2) + "/" + id.substring(2);
File f = new File(imageDir + path);
Files.createNewFile(f);
Files.copyFile(tmp.getFile(), f);
tmp.getFile().delete();
re.put("url", Mvcs.getServletContext().getContextPath()+"/yvr/upload" + path);
re.setv("success", true);
return re;
}
public Dao daoNoContent() {
return daoNoContent;
}
public void init() {
daoNoContent = Daos.ext(dao, FieldFilter.locked(Topic.class, "content").set(TopicReply.class, null, "content", false));
if (topicGlobalWatchers != null) {
for (String username : Strings.splitIgnoreBlank(topicGlobalWatchers)) {
User user = dao.fetch(User.class, username);
if (user == null) {
log.infof("no such user[name=%s] for topic watch", username);
continue;
}
globalWatcherIds.add(user.getId());
}
}
}
static Pattern atPattern = Pattern.compile("@([a-zA-Z0-9\\_]{4,20}\\s)");
public static void main(String[] args) {
String cnt = "@wendal @zozoh 这样可以吗?@qq_addfdf";
System.out.println(findAt(cnt, 100));
}
public static Set<String> findAt(String cnt, int limit) {
Set<String> ats = new HashSet<String>();
Matcher matcher = atPattern.matcher(cnt+" ");
int start = 0;
int end = 0;
while (end < cnt.length() && matcher.find(end)) {
start = matcher.start();
end = matcher.end();
ats.add(cnt.substring(start+1, end-1).trim().toLowerCase());
if (limit <= ats.size())
break;
}
return ats;
}
@Aop("redis")
public boolean updateTags(String topicId, @Param("tags")Set<String> tags) {
if (Strings.isBlank(topicId) || tags == null) {
return false;
}
Topic topic = daoNoContent.fetch(Topic.class, topicId);
if (topic == null)
return false;
Set<String> oldTags = topic.getTags();
if (oldTags == null)
oldTags = new HashSet<>();
log.debugf("update from '%s' to '%s'", oldTags, tags);
topic.setTags(tags);
dao.update(topic, "tags");
Set<String> newTags = new HashSet<>(tags);
newTags.removeAll(oldTags);
Set<String> removeTags = new HashSet<>(oldTags);;
removeTags.remove(tags);
fillTopic(topic, null);
Date lastReplyTime = topic.getCreateTime();
if (topic.getLastComment() != null)
lastReplyTime = topic.getLastComment().getCreateTime();
Pipeline pipe = jedis().pipelined();
for (String tag : removeTags) {
pipe.zrem(RKEY_TOPIC_TAG+tag.toLowerCase().trim(), topic.getId());
pipe.zincrby(RKEY_TOPIC_TAG_COUNT, -1, tag.toLowerCase().trim());
}
for (String tag : newTags) {
pipe.zadd(RKEY_TOPIC_TAG+tag.toLowerCase().trim(), lastReplyTime.getTime(), topic.getId());
pipe.zincrby(RKEY_TOPIC_TAG_COUNT, 1, tag.toLowerCase().trim());
}
pipe.sync();
return true;
}
@Aop("redis")
public List<Topic> fetchTop() {
List<Topic> list = new ArrayList<>();
Map<Integer, UserProfile> authors = new HashMap<>();
for(String id :jedis().zrevrangeByScore(RKEY_TOPIC_TOP, Long.MAX_VALUE, 0)) {
Topic topic = daoNoContent.fetch(Topic.class, id);
if (topic == null)
continue;
fillTopic(topic, authors);
list.add(topic);
}
return list;
}
@Aop("redis")
public List<TopicTag> fetchTopTags() {
Set<String> names = jedis().zrevrangeByScore(RKEY_TOPIC_TAG_COUNT, Long.MAX_VALUE, 0, 0, 20);
List<TopicTag> tags = new ArrayList<>();
List<Response<Double>> tmps = new ArrayList<>();
Pipeline pipe = jedis().pipelined();
for (String name: names) {
tmps.add(pipe.zscore(RKEY_TOPIC_TAG_COUNT, name));
tags.add(new TopicTag(name, 0));
}
pipe.sync();
Iterator<TopicTag> it = tags.iterator();
for (Response<Double> response : tmps) {
it.next().setCount(response.get().intValue());
}
return tags;
}
@Aop("redis")
public boolean checkNonce(String nonce, String time) {
try {
long t = Long.parseLong(time);
if (System.currentTimeMillis() - t > 10*60*1000) {
return false;
}
String key = "at:nonce:"+nonce;
Long re = jedis().setnx(key, "");
if (re == 0) {
return false;
}
jedis().expire(key, 10*60);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
| src/main/java/net/wendal/nutzbook/service/yvr/YvrService.java | package net.wendal.nutzbook.service.yvr;
import static net.wendal.nutzbook.bean.CResult._fail;
import static net.wendal.nutzbook.bean.CResult._ok;
import static net.wendal.nutzbook.util.RedisInterceptor.jedis;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.FieldFilter;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.Daos;
import org.nutz.integration.zbus.ZBusProducer;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.lang.Strings;
import org.nutz.lang.random.R;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import net.wendal.nutzbook.bean.CResult;
import net.wendal.nutzbook.bean.User;
import net.wendal.nutzbook.bean.UserProfile;
import net.wendal.nutzbook.bean.yvr.Topic;
import net.wendal.nutzbook.bean.yvr.TopicReply;
import net.wendal.nutzbook.bean.yvr.TopicTag;
import net.wendal.nutzbook.bean.yvr.TopicType;
import net.wendal.nutzbook.service.PushService;
import net.wendal.nutzbook.util.RedisKey;
import net.wendal.nutzbook.util.Toolkit;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
@IocBean(create="init")
public class YvrService implements RedisKey {
private static final Log log = Logs.get();
@Inject
protected Dao dao;
// 用于查询Topic和TopicReply时不查询content属性
protected Dao daoNoContent;
@Inject
protected TopicSearchService topicSearchService;
@Inject
protected PushService pushService;
// TODO 改成发布-订阅模式
@Inject("java:$zbus.getProducer('topic-watch')")
protected ZBusProducer topicWatchProducer;
@Inject("java:$conf.get('topic.image.dir')")
protected String imageDir;
@Inject("java:$conf.get('topic.global.watchers')")
protected String topicGlobalWatchers;
protected Set<Integer> globalWatcherIds = new HashSet<>();
@Aop("redis")
public void fillTopic(Topic topic, Map<Integer, UserProfile> authors) {
if (topic.getUserId() == 0)
topic.setUserId(1);
topic.setAuthor(_cacheFetch(authors, topic.getUserId()));
Double reply_count = jedis().zscore(RKEY_REPLY_COUNT, topic.getId());
topic.setReplyCount(reply_count == null ? 0 : reply_count.intValue());
if (topic.getReplyCount() > 0) {
String replyId = jedis().hget(RKEY_REPLY_LAST, topic.getId());
TopicReply reply = daoNoContent.fetch(TopicReply.class, replyId);
if (reply != null) {
if (reply.getUserId() == 0)
reply.setUserId(1);
reply.setAuthor(_cacheFetch(authors, reply.getUserId()));
topic.setLastComment(reply);
}
}
Double visited = jedis().zscore(RKEY_TOPIC_VISIT, topic.getId());
topic.setVisitCount((visited == null) ? 0 : visited.intValue());
}
protected UserProfile _cacheFetch(Map<Integer, UserProfile> authors, int userId) {
if (authors == null)
return null;
UserProfile author = authors.get(userId);
if (author == null) {
author = dao.fetch(UserProfile.class, userId);
authors.put(userId, author);
}
return author;
}
@Aop("redis")
public String accessToken(String loginname) {
return jedis().hget(RKEY_USER_ACCESSTOKEN, loginname);
}
@Aop("redis")
public String accessToken(UserProfile profile) {
String loginname = profile.getLoginname();
String at = jedis().hget(RKEY_USER_ACCESSTOKEN, loginname);
if (at == null) {
// 双向绑定
at = R.UU32();
jedis().hset(RKEY_USER_ACCESSTOKEN, loginname, at);
jedis().hset(RKEY_USER_ACCESSTOKEN2, at, loginname);
jedis().hset(RKEY_USER_ACCESSTOKEN3, at, ""+profile.getUserId());
}
return at;
}
@Aop("redis")
public void resetAccessToken(String loginname) {
String at = jedis().hget(RKEY_USER_ACCESSTOKEN, loginname); {
jedis().hdel(RKEY_USER_ACCESSTOKEN, loginname);
jedis().hdel(RKEY_USER_ACCESSTOKEN2, at);
jedis().hdel(RKEY_USER_ACCESSTOKEN3, at);
}
}
@Aop("redis")
public int getUserByAccessToken(String at) {
String uid_str = jedis().hget(RKEY_USER_ACCESSTOKEN3, at);
if (uid_str == null)
return -1;
return Integer.parseInt(uid_str);
}
@Aop("redis")
public CResult add(Topic topic, int userId) {
if (userId < 1) {
return _fail("请先登录");
}
if (Strings.isBlank(topic.getTitle()) || topic.getTitle().length() > 100 || topic.getTitle().length() < 5) {
return _fail("标题长度不合法");
}
if (Strings.isBlank(topic.getContent()) || topic.getContent().length() > 20000) {
return _fail("内容不合法");
}
if (topic.getTags() != null && topic.getTags().size() > 10) {
return _fail("最多只能有10个tag");
}
if (0 != dao.count(Topic.class, Cnd.where("title", "=", topic.getTitle().trim()))) {
return _fail("相同标题已经发过了");
}
topic.setTitle(Strings.escapeHtml(topic.getTitle().trim()));
topic.setUserId(userId);
topic.setTop(false);
topic.setTags(new HashSet<>());
if (topic.getType() == null)
topic.setType(TopicType.ask);
topic.setContent(Toolkit.filteContent(topic.getContent()));
dao.insert(topic);
try {
topicSearchService.add(topic);
} catch (Exception e) {
}
// 如果是ask类型,把帖子加入到 "未回复"列表
Pipeline pipe = jedis().pipelined();
if (TopicType.ask.equals(topic.getType())) {
pipe.zadd(RKEY_TOPIC_NOREPLY, System.currentTimeMillis(), topic.getId());
}
pipe.zadd(RKEY_TOPIC_UPDATE + topic.getType(), System.currentTimeMillis(), topic.getId());
pipe.zadd(RKEY_TOPIC_UPDATE_ALL, System.currentTimeMillis(), topic.getId());
pipe.zincrby(RKEY_USER_SCORE, 100, ""+userId);
pipe.sync();
for (Integer watcherId : globalWatcherIds) {
if (watcherId != userId)
pushUser(watcherId, "新帖:" + topic.getTitle(), topic.getId());
}
return _ok(topic.getId());
}
@Aop("redis")
public CResult addReply(final String topicId, final TopicReply reply, final int userId) {
if (userId < 1)
return _fail("请先登录");
if (reply == null || reply.getContent() == null || reply.getContent().trim().isEmpty()) {
return _fail("内容不能为空");
}
final String cnt = reply.getContent().trim();
if (cnt.length() < 2 || cnt.length() > 10000) {
return _fail("内容太长或太短了");
}
final Topic topic = daoNoContent.fetch(Topic.class, topicId); // TODO 改成只fetch出type属性
if (topic == null) {
return _fail("主题不存在");
}
reply.setTopicId(topicId);
reply.setUserId(userId);
reply.setContent(Toolkit.filteContent(reply.getContent()));
dao.insert(reply);
// 更新topic的时间戳
Pipeline pipe = jedis().pipelined();
if (topic.isTop()) {
pipe.zadd(RKEY_TOPIC_TOP, reply.getCreateTime().getTime(), topicId);
} else {
pipe.zadd(RKEY_TOPIC_UPDATE + topic.getType(), reply.getCreateTime().getTime(), topicId);
pipe.zadd(RKEY_TOPIC_UPDATE_ALL, reply.getCreateTime().getTime(), topicId);
}
pipe.zrem(RKEY_TOPIC_NOREPLY, topicId);
if (topic.getTags() != null) {
for (String tag : topic.getTags()) {
pipe.zadd(RKEY_TOPIC_TAG+tag.toLowerCase().trim(), reply.getCreateTime().getTime(), topicId);
}
}
pipe.hset(RKEY_REPLY_LAST, topicId, reply.getId());
pipe.zincrby(RKEY_REPLY_COUNT, 1, topicId);
pipe.zincrby(RKEY_USER_SCORE, 10, ""+userId);
pipe.sync();
// 通知页面刷新
topicWatchProducer.async(topicId);
String replyAuthorName = dao.fetch(User.class, userId).getName();
// 通知原本的作者
if (topic.getUserId() != userId) {
String alert = replyAuthorName + "回复了您的帖子";
pushUser(topic.getUserId(), alert, topicId);
}
Set<String> ats = findAt(cnt, 5);
for (String at : ats) {
User user = dao.fetch(User.class, at);
if (user == null)
continue;
if (topic.getUserId() == user.getId())
continue; // 前面已经发过了
if (userId == user.getId())
continue; // 自己@自己, 忽略
String alert = replyAuthorName + "在帖子回复中@了你";
pushUser(user.getId(), alert, topicId);
}
return _ok(reply.getId());
}
@Aop("redis")
public CResult replyUp(String replyId, int userId) {
if (userId < 1)
return _fail("你还没登录呢");
if (1 != dao.count(TopicReply.class, Cnd.where("id", "=", replyId))) {
return _fail("没这条评论");
}
String key = RKEY_REPLY_LIKE + replyId;
Double t = jedis().zscore(key, "" + userId);
if (t != null) {
jedis().zrem(key, userId + "");
return _ok("down");
} else {
jedis().zadd(key, System.currentTimeMillis(), userId + "");
return _ok("up");
}
}
protected void pushUser(int userId, String alert, String topic_id) {
Map<String, String> extras = new HashMap<String, String>();
extras.put("topic_id", topic_id);
pushService.alert(userId, alert, extras);
}
public List<Topic> getRecentTopics(int userId) {
List<Topic> recent_topics = daoNoContent().query(Topic.class, Cnd.where("userId", "=", userId).desc("createTime"), dao.createPager(1, 5));
Map<Integer, UserProfile> authors = new HashMap<Integer, UserProfile>();
if (!recent_topics.isEmpty()) {
for (Topic topic : recent_topics) {
fillTopic(topic, authors);
}
}
return recent_topics;
}
public List<Topic> getRecentReplyTopics(int userId) {
Map<Integer, UserProfile> authors = new HashMap<Integer, UserProfile>();
Sql sql = Sqls.queryString("select DISTINCT topicId from t_topic_reply $cnd").setEntity(dao.getEntity(TopicReply.class)).setVar("cnd", Cnd.where("userId", "=", userId).desc("createTime"));
sql.setPager(dao.createPager(1, 5));
String[] replies_topic_ids = dao.execute(sql).getObject(String[].class);
List<Topic> recent_replies = new ArrayList<Topic>();
for (String topic_id : replies_topic_ids) {
Topic _topic = dao.fetch(Topic.class, topic_id);
if (_topic == null)
continue;
recent_replies.add(_topic);
}
if (!recent_replies.isEmpty()) {
for (Topic topic : recent_replies) {
fillTopic(topic, authors);
}
}
return recent_replies;
}
@Aop("redis")
public int getUserScore(int userId) {
Double score = jedis().zscore(RKEY_USER_SCORE, ""+userId);
if (score == null) {
return 0;
} else {
return score.intValue();
}
}
public NutMap upload(TempFile tmp, int userId) throws IOException {
NutMap re = new NutMap();
if (userId < 1)
return re.setv("msg", "请先登陆!");
if (tmp == null || tmp.getFile().length() == 0) {
return re.setv("msg", "空文件");
}
if (tmp.getFile().length() > 2 * 1024 * 1024) {
return re.setv("msg", "文件太大了");
}
String id = R.UU32();
String path = "/" + id.substring(0, 2) + "/" + id.substring(2);
File f = new File(imageDir + path);
Files.createNewFile(f);
Files.copyFile(tmp.getFile(), f);
tmp.getFile().delete();
re.put("url", Mvcs.getServletContext().getContextPath()+"/yvr/upload" + path);
re.setv("success", true);
return re;
}
public Dao daoNoContent() {
return daoNoContent;
}
public void init() {
daoNoContent = Daos.ext(dao, FieldFilter.locked(Topic.class, "content").set(TopicReply.class, null, "content", false));
if (topicGlobalWatchers != null) {
for (String username : Strings.splitIgnoreBlank(topicGlobalWatchers)) {
User user = dao.fetch(User.class, username);
if (user == null) {
log.infof("no such user[name=%s] for topic watch", username);
continue;
}
globalWatcherIds.add(user.getId());
}
}
}
static Pattern atPattern = Pattern.compile("@([a-zA-Z0-9\\_]{4,20}\\s)");
public static void main(String[] args) {
String cnt = "@wendal @zozoh 这样可以吗?@qq_addfdf";
System.out.println(findAt(cnt, 100));
}
public static Set<String> findAt(String cnt, int limit) {
Set<String> ats = new HashSet<String>();
Matcher matcher = atPattern.matcher(cnt+" ");
int start = 0;
int end = 0;
while (end < cnt.length() && matcher.find(end)) {
start = matcher.start();
end = matcher.end();
ats.add(cnt.substring(start+1, end-1).trim().toLowerCase());
if (limit <= ats.size())
break;
}
return ats;
}
@Aop("redis")
public boolean updateTags(String topicId, @Param("tags")Set<String> tags) {
if (Strings.isBlank(topicId) || tags == null) {
return false;
}
Topic topic = daoNoContent.fetch(Topic.class, topicId);
if (topic == null)
return false;
Set<String> oldTags = topic.getTags();
if (oldTags == null)
oldTags = new HashSet<>();
log.debugf("update from '%s' to '%s'", oldTags, tags);
topic.setTags(tags);
dao.update(topic, "tags");
Set<String> newTags = new HashSet<>(tags);
newTags.removeAll(oldTags);
Set<String> removeTags = new HashSet<>(oldTags);;
removeTags.remove(tags);
fillTopic(topic, null);
Date lastReplyTime = topic.getCreateTime();
if (topic.getLastComment() != null)
lastReplyTime = topic.getLastComment().getCreateTime();
Pipeline pipe = jedis().pipelined();
for (String tag : removeTags) {
pipe.zrem(RKEY_TOPIC_TAG+tag.toLowerCase().trim(), topic.getId());
pipe.zincrby(RKEY_TOPIC_TAG_COUNT, -1, tag.toLowerCase().trim());
}
for (String tag : newTags) {
pipe.zadd(RKEY_TOPIC_TAG+tag.toLowerCase().trim(), lastReplyTime.getTime(), topic.getId());
pipe.zincrby(RKEY_TOPIC_TAG_COUNT, 1, tag.toLowerCase().trim());
}
pipe.sync();
return true;
}
@Aop("redis")
public List<Topic> fetchTop() {
List<Topic> list = new ArrayList<>();
Map<Integer, UserProfile> authors = new HashMap<>();
for(String id :jedis().zrevrangeByScore(RKEY_TOPIC_TOP, Long.MAX_VALUE, 0)) {
Topic topic = daoNoContent.fetch(Topic.class, id);
if (topic == null)
continue;
fillTopic(topic, authors);
list.add(topic);
}
return list;
}
@Aop("redis")
public List<TopicTag> fetchTopTags() {
Set<String> names = jedis().zrevrangeByScore(RKEY_TOPIC_TAG_COUNT, Long.MAX_VALUE, 0, 0, 20);
List<TopicTag> tags = new ArrayList<>();
List<Response<Double>> tmps = new ArrayList<>();
Pipeline pipe = jedis().pipelined();
for (String name: names) {
tmps.add(pipe.zscore(RKEY_TOPIC_TAG_COUNT, name));
tags.add(new TopicTag(name, 0));
}
pipe.sync();
Iterator<TopicTag> it = tags.iterator();
for (Response<Double> response : tmps) {
it.next().setCount(response.get().intValue());
}
return tags;
}
@Aop("redis")
public boolean checkNonce(String nonce, String time) {
try {
long t = Long.parseLong(time);
if (System.currentTimeMillis() - t > 10*60*1000) {
return false;
}
String key = "at:nonce:"+nonce;
Long re = jedis().setnx(key, "");
if (re == 0) {
return false;
}
jedis().expire(key, 10*60);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
| change: 图片的大小限制扩展到5mb
| src/main/java/net/wendal/nutzbook/service/yvr/YvrService.java | change: 图片的大小限制扩展到5mb |
|
Java | apache-2.0 | 14ba5967fd61a48561cd8a2f60adcda740618cdd | 0 | gavinking/UniversalMusicPlayer | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//package com.example.android.uamp.playback;
//
//import android.content.BroadcastReceiver;
//import android.content.Context;
//import android.content.Intent;
//import android.content.IntentFilter;
//import android.media.AudioManager;
//import android.media.MediaPlayer;
//import android.net.wifi.WifiManager;
//import android.os.PowerManager;
//import android.media.MediaMetadata;
//import android.media.session.PlaybackState;
//import android.text.TextUtils;
//
//import com.example.android.uamp.MusicService;
//import com.example.android.uamp.model.MusicProvider;
//import com.example.android.uamp.model.MusicProviderSource;
//import com.example.android.uamp.model.customMetadataTrackSource_;
//import com.example.android.uamp.utils.LogHelper;
//import com.example.android.uamp.utils.MediaIDHelper;
//
//import java.io.IOException;
//
//import static android.media.MediaPlayer.OnCompletionListener;
//import static android.media.MediaPlayer.OnErrorListener;
//import static android.media.MediaPlayer.OnPreparedListener;
//import static android.media.MediaPlayer.OnSeekCompleteListener;
//import static android.media.session.MediaSession.QueueItem;
//
///**
// * A class that implements local media playback using {@link android.media.MediaPlayer}
// */
//public class LocalPlayback implements Playback, AudioManager.OnAudioFocusChangeListener,
// OnCompletionListener, OnErrorListener, OnPreparedListener, OnSeekCompleteListener {
//
// private static final String TAG = LogHelper.makeLogTag(LocalPlayback.class);
//
// // The volume we set the media player to when we lose audio focus, but are
// // allowed to reduce the volume instead of stopping playback.
// public static final float VOLUME_DUCK = 0.2f;
// // The volume we set the media player when we have audio focus.
// public static final float VOLUME_NORMAL = 1.0f;
//
// // we don't have audio focus, and can't duck (play at a low volume)
// private static final int AUDIO_NO_FOCUS_NO_DUCK = 0;
// // we don't have focus, but can duck (play at a low volume)
// private static final int AUDIO_NO_FOCUS_CAN_DUCK = 1;
// // we have full audio focus
// private static final int AUDIO_FOCUSED = 2;
//
// private final Context mContext;
// private final WifiManager.WifiLock mWifiLock;
// private int mState;
// private boolean mPlayOnFocusGain;
// private Callback mCallback;
// private final MusicProvider mMusicProvider;
// private volatile boolean mAudioNoisyReceiverRegistered;
// private volatile int mCurrentPosition;
// private volatile String mCurrentMediaId;
//
// // Type of audio focus we have:
// private int mAudioFocus = AUDIO_NO_FOCUS_NO_DUCK;
// private final AudioManager mAudioManager;
// private MediaPlayer mMediaPlayer;
//
// private final IntentFilter mAudioNoisyIntentFilter =
// new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
//
// private final BroadcastReceiver mAudioNoisyReceiver = new BroadcastReceiver() {
// @Override
// public void onReceive(Context context, Intent intent) {
// if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
// LogHelper.d(TAG, "Headphones disconnected.");
// if (isPlaying()) {
// Intent i = new Intent(context, MusicService.class);
// i.setAction(MusicService.ACTION_CMD);
// i.putExtra(MusicService.CMD_NAME, MusicService.CMD_PAUSE);
// mContext.startService(i);
// }
// }
// }
// };
//
// public LocalPlayback(Context context, MusicProvider musicProvider) {
// this.mContext = context;
// this.mMusicProvider = musicProvider;
// this.mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
// // Create the Wifi lock (this does not acquire the lock, this just creates it)
// this.mWifiLock = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE))
// .createWifiLock(WifiManager.WIFI_MODE_FULL, "uAmp_lock");
// this.mState = PlaybackState.STATE_NONE;
// }
//
// @Override
// public void start() {
// }
//
// @Override
// public void stop(boolean notifyListeners) {
// mState = PlaybackState.STATE_STOPPED;
// if (notifyListeners && mCallback != null) {
// mCallback.onPlaybackStatusChanged(mState);
// }
// mCurrentPosition = getCurrentStreamPosition();
// // Give up Audio focus
// giveUpAudioFocus();
// unregisterAudioNoisyReceiver();
// // Relax all resources
// relaxResources(true);
// }
//
// @Override
// public void setState(int state) {
// this.mState = state;
// }
//
// @Override
// public int getState() {
// return mState;
// }
//
// @Override
// public boolean isConnected() {
// return true;
// }
//
// @Override
// public boolean isPlaying() {
// return mPlayOnFocusGain || (mMediaPlayer != null && mMediaPlayer.isPlaying());
// }
//
// @Override
// public int getCurrentStreamPosition() {
// return mMediaPlayer != null ?
// mMediaPlayer.getCurrentPosition() : mCurrentPosition;
// }
//
// @Override
// public void updateLastKnownStreamPosition() {
// if (mMediaPlayer != null) {
// mCurrentPosition = mMediaPlayer.getCurrentPosition();
// }
// }
//
// @Override
// public void play(QueueItem item) {
// mPlayOnFocusGain = true;
// tryToGetAudioFocus();
// registerAudioNoisyReceiver();
// String mediaId = item.getDescription().getMediaId();
// boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId);
// if (mediaHasChanged) {
// mCurrentPosition = 0;
// mCurrentMediaId = mediaId;
// }
//
// if (mState == PlaybackState.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) {
// configMediaPlayerState();
// } else {
// mState = PlaybackState.STATE_STOPPED;
// relaxResources(false); // release everything except MediaPlayer
// MediaMetadata track = mMusicProvider.getMusic(
// MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId()));
//
// //noinspection ResourceType
// String source = track.getString(customMetadataTrackSource_.get_());
// if (source != null) {
// source = source.replaceAll(" ", "%20"); // Escape spaces for URLs
// }
//
// try {
// createMediaPlayerIfNeeded();
//
// mState = PlaybackState.STATE_BUFFERING;
//
// mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mMediaPlayer.setDataSource(source);
//
// // Starts preparing the media player in the background. When
// // it's done, it will call our OnPreparedListener (that is,
// // the onPrepared() method on this class, since we set the
// // listener to 'this'). Until the media player is prepared,
// // we *cannot* call start() on it!
// mMediaPlayer.prepareAsync();
//
// // If we are streaming from the internet, we want to hold a
// // Wifi lock, which prevents the Wifi radio from going to
// // sleep while the song is playing.
// mWifiLock.acquire();
//
// if (mCallback != null) {
// mCallback.onPlaybackStatusChanged(mState);
// }
//
// } catch (IOException ex) {
// LogHelper.e(TAG, ex, "Exception playing song");
// if (mCallback != null) {
// mCallback.onError(ex.getMessage());
// }
// }
// }
// }
//
// @Override
// public void pause() {
// if (mState == PlaybackState.STATE_PLAYING) {
// // Pause media player and cancel the 'foreground service' state.
// if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
// mMediaPlayer.pause();
// mCurrentPosition = mMediaPlayer.getCurrentPosition();
// }
// // while paused, retain the MediaPlayer but give up audio focus
// relaxResources(false);
// }
// mState = PlaybackState.STATE_PAUSED;
// if (mCallback != null) {
// mCallback.onPlaybackStatusChanged(mState);
// }
// unregisterAudioNoisyReceiver();
// }
//
// @Override
// public void seekTo(int position) {
// LogHelper.d(TAG, "seekTo called with ", position);
//
// if (mMediaPlayer == null) {
// // If we do not have a current media player, simply update the current position
// mCurrentPosition = position;
// } else {
// if (mMediaPlayer.isPlaying()) {
// mState = PlaybackState.STATE_BUFFERING;
// }
// registerAudioNoisyReceiver();
// mMediaPlayer.seekTo(position);
// if (mCallback != null) {
// mCallback.onPlaybackStatusChanged(mState);
// }
// }
// }
//
// @Override
// public void setCallback(Callback callback) {
// this.mCallback = callback;
// }
//
// @Override
// public void setCurrentStreamPosition(int pos) {
// this.mCurrentPosition = pos;
// }
//
// @Override
// public void setCurrentMediaId(String mediaId) {
// this.mCurrentMediaId = mediaId;
// }
//
// @Override
// public String getCurrentMediaId() {
// return mCurrentMediaId;
// }
//
// /**
// * Try to get the system audio focus.
// */
// private void tryToGetAudioFocus() {
// LogHelper.d(TAG, "tryToGetAudioFocus");
// int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
// AudioManager.AUDIOFOCUS_GAIN);
// if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// mAudioFocus = AUDIO_FOCUSED;
// } else {
// mAudioFocus = AUDIO_NO_FOCUS_NO_DUCK;
// }
// }
//
// /**
// * Give up the audio focus.
// */
// private void giveUpAudioFocus() {
// LogHelper.d(TAG, "giveUpAudioFocus");
// if (mAudioManager.abandonAudioFocus(this) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// mAudioFocus = AUDIO_NO_FOCUS_NO_DUCK;
// }
// }
//
// /**
// * Reconfigures MediaPlayer according to audio focus settings and
// * starts/restarts it. This method starts/restarts the MediaPlayer
// * respecting the current audio focus state. So if we have focus, it will
// * play normally; if we don't have focus, it will either leave the
// * MediaPlayer paused or set it to a low volume, depending on what is
// * allowed by the current focus settings. This method assumes mPlayer !=
// * null, so if you are calling it, you have to do so from a context where
// * you are sure this is the case.
// */
// private void configMediaPlayerState() {
// LogHelper.d(TAG, "configMediaPlayerState. mAudioFocus=", mAudioFocus);
// if (mAudioFocus == AUDIO_NO_FOCUS_NO_DUCK) {
// // If we don't have audio focus and can't duck, we have to pause,
// if (mState == PlaybackState.STATE_PLAYING) {
// pause();
// }
// } else { // we have audio focus:
// registerAudioNoisyReceiver();
// if (mAudioFocus == AUDIO_NO_FOCUS_CAN_DUCK) {
// mMediaPlayer.setVolume(VOLUME_DUCK, VOLUME_DUCK); // we'll be relatively quiet
// } else {
// if (mMediaPlayer != null) {
// mMediaPlayer.setVolume(VOLUME_NORMAL, VOLUME_NORMAL); // we can be loud again
// } // else do something for remote client.
// }
// // If we were playing when we lost focus, we need to resume playing.
// if (mPlayOnFocusGain) {
// if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
// LogHelper.d(TAG,"configMediaPlayerState startMediaPlayer. seeking to ",
// mCurrentPosition);
// if (mCurrentPosition == mMediaPlayer.getCurrentPosition()) {
// mMediaPlayer.start();
// mState = PlaybackState.STATE_PLAYING;
// } else {
// mMediaPlayer.seekTo(mCurrentPosition);
// mState = PlaybackState.STATE_BUFFERING;
// }
// }
// mPlayOnFocusGain = false;
// }
// }
// if (mCallback != null) {
// mCallback.onPlaybackStatusChanged(mState);
// }
// }
//
// /**
// * Called by AudioManager on audio focus changes.
// * Implementation of {@link android.media.AudioManager.OnAudioFocusChangeListener}
// */
// @Override
// public void onAudioFocusChange(int focusChange) {
// LogHelper.d(TAG, "onAudioFocusChange. focusChange=", focusChange);
// if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// // We have gained focus:
// mAudioFocus = AUDIO_FOCUSED;
//
// } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS ||
// focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
// focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
// // We have lost focus. If we can duck (low playback volume), we can keep playing.
// // Otherwise, we need to pause the playback.
// boolean canDuck = focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK;
// mAudioFocus = canDuck ? AUDIO_NO_FOCUS_CAN_DUCK : AUDIO_NO_FOCUS_NO_DUCK;
//
// // If we are playing, we need to reset media player by calling configMediaPlayerState
// // with mAudioFocus properly set.
// if (mState == PlaybackState.STATE_PLAYING && !canDuck) {
// // If we don't have audio focus and can't duck, we save the information that
// // we were playing, so that we can resume playback once we get the focus back.
// mPlayOnFocusGain = true;
// }
// } else {
// LogHelper.e(TAG, "onAudioFocusChange: Ignoring unsupported focusChange: ", focusChange);
// }
// configMediaPlayerState();
// }
//
// /**
// * Called when MediaPlayer has completed a seek
// *
// * @see OnSeekCompleteListener
// */
// @Override
// public void onSeekComplete(MediaPlayer mp) {
// LogHelper.d(TAG, "onSeekComplete from MediaPlayer:", mp.getCurrentPosition());
// mCurrentPosition = mp.getCurrentPosition();
// if (mState == PlaybackState.STATE_BUFFERING) {
// registerAudioNoisyReceiver();
// mMediaPlayer.start();
// mState = PlaybackState.STATE_PLAYING;
// }
// if (mCallback != null) {
// mCallback.onPlaybackStatusChanged(mState);
// }
// }
//
// /**
// * Called when media player is done playing current song.
// *
// * @see OnCompletionListener
// */
// @Override
// public void onCompletion(MediaPlayer player) {
// LogHelper.d(TAG, "onCompletion from MediaPlayer");
// // The media player finished playing the current song, so we go ahead
// // and start the next.
// if (mCallback != null) {
// mCallback.onCompletion();
// }
// }
//
// /**
// * Called when media player is done preparing.
// *
// * @see OnPreparedListener
// */
// @Override
// public void onPrepared(MediaPlayer player) {
// LogHelper.d(TAG, "onPrepared from MediaPlayer");
// // The media player is done preparing. That means we can start playing if we
// // have audio focus.
// configMediaPlayerState();
// }
//
// /**
// * Called when there's an error playing media. When this happens, the media
// * player goes to the Error state. We warn the user about the error and
// * reset the media player.
// *
// * @see OnErrorListener
// */
// @Override
// public boolean onError(MediaPlayer mp, int what, int extra) {
// LogHelper.e(TAG, "Media player error: what=" + what + ", extra=" + extra);
// if (mCallback != null) {
// mCallback.onError("MediaPlayer error " + what + " (" + extra + ")");
// }
// return true; // true indicates we handled the error
// }
//
// /**
// * Makes sure the media player exists and has been reset. This will create
// * the media player if needed, or reset the existing media player if one
// * already exists.
// */
// private void createMediaPlayerIfNeeded() {
// LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? ", (mMediaPlayer==null));
// if (mMediaPlayer == null) {
// mMediaPlayer = new MediaPlayer();
//
// // Make sure the media player will acquire a wake-lock while
// // playing. If we don't do that, the CPU might go to sleep while the
// // song is playing, causing playback to stop.
// mMediaPlayer.setWakeMode(mContext.getApplicationContext(),
// PowerManager.PARTIAL_WAKE_LOCK);
//
// // we want the media player to notify us when it's ready preparing,
// // and when it's done playing:
// mMediaPlayer.setOnPreparedListener(this);
// mMediaPlayer.setOnCompletionListener(this);
// mMediaPlayer.setOnErrorListener(this);
// mMediaPlayer.setOnSeekCompleteListener(this);
// } else {
// mMediaPlayer.reset();
// }
// }
//
// /**
// * Releases resources used by the service for playback. This includes the
// * "foreground service" status, the wake locks and possibly the MediaPlayer.
// *
// * @param releaseMediaPlayer Indicates whether the Media Player should also
// * be released or not
// */
// private void relaxResources(boolean releaseMediaPlayer) {
// LogHelper.d(TAG, "relaxResources. releaseMediaPlayer=", releaseMediaPlayer);
//
// // stop and release the Media Player, if it's available
// if (releaseMediaPlayer && mMediaPlayer != null) {
// mMediaPlayer.reset();
// mMediaPlayer.release();
// mMediaPlayer = null;
// }
//
// // we can also release the Wifi lock, if we're holding it
// if (mWifiLock.isHeld()) {
// mWifiLock.release();
// }
// }
//
// private void registerAudioNoisyReceiver() {
// if (!mAudioNoisyReceiverRegistered) {
// mContext.registerReceiver(mAudioNoisyReceiver, mAudioNoisyIntentFilter);
// mAudioNoisyReceiverRegistered = true;
// }
// }
//
// private void unregisterAudioNoisyReceiver() {
// if (mAudioNoisyReceiverRegistered) {
// mContext.unregisterReceiver(mAudioNoisyReceiver);
// mAudioNoisyReceiverRegistered = false;
// }
// }
//}
| mobile/src/main/ceylon/com/example/android/uamp/playback/LocalPlayback.java | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.playback;
//
//import android.content.BroadcastReceiver;
//import android.content.Context;
//import android.content.Intent;
//import android.content.IntentFilter;
//import android.media.AudioManager;
//import android.media.MediaPlayer;
//import android.net.wifi.WifiManager;
//import android.os.PowerManager;
//import android.media.MediaMetadata;
//import android.media.session.PlaybackState;
//import android.text.TextUtils;
//
//import com.example.android.uamp.MusicService;
//import com.example.android.uamp.model.MusicProvider;
//import com.example.android.uamp.model.MusicProviderSource;
//import com.example.android.uamp.model.customMetadataTrackSource_;
//import com.example.android.uamp.utils.LogHelper;
//import com.example.android.uamp.utils.MediaIDHelper;
//
//import java.io.IOException;
//
//import static android.media.MediaPlayer.OnCompletionListener;
//import static android.media.MediaPlayer.OnErrorListener;
//import static android.media.MediaPlayer.OnPreparedListener;
//import static android.media.MediaPlayer.OnSeekCompleteListener;
//import static android.media.session.MediaSession.QueueItem;
//
///**
// * A class that implements local media playback using {@link android.media.MediaPlayer}
// */
//public class LocalPlayback implements Playback, AudioManager.OnAudioFocusChangeListener,
// OnCompletionListener, OnErrorListener, OnPreparedListener, OnSeekCompleteListener {
//
// private static final String TAG = LogHelper.makeLogTag(LocalPlayback.class);
//
// // The volume we set the media player to when we lose audio focus, but are
// // allowed to reduce the volume instead of stopping playback.
// public static final float VOLUME_DUCK = 0.2f;
// // The volume we set the media player when we have audio focus.
// public static final float VOLUME_NORMAL = 1.0f;
//
// // we don't have audio focus, and can't duck (play at a low volume)
// private static final int AUDIO_NO_FOCUS_NO_DUCK = 0;
// // we don't have focus, but can duck (play at a low volume)
// private static final int AUDIO_NO_FOCUS_CAN_DUCK = 1;
// // we have full audio focus
// private static final int AUDIO_FOCUSED = 2;
//
// private final Context mContext;
// private final WifiManager.WifiLock mWifiLock;
// private int mState;
// private boolean mPlayOnFocusGain;
// private Callback mCallback;
// private final MusicProvider mMusicProvider;
// private volatile boolean mAudioNoisyReceiverRegistered;
// private volatile int mCurrentPosition;
// private volatile String mCurrentMediaId;
//
// // Type of audio focus we have:
// private int mAudioFocus = AUDIO_NO_FOCUS_NO_DUCK;
// private final AudioManager mAudioManager;
// private MediaPlayer mMediaPlayer;
//
// private final IntentFilter mAudioNoisyIntentFilter =
// new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
//
// private final BroadcastReceiver mAudioNoisyReceiver = new BroadcastReceiver() {
// @Override
// public void onReceive(Context context, Intent intent) {
// if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
// LogHelper.d(TAG, "Headphones disconnected.");
// if (isPlaying()) {
// Intent i = new Intent(context, MusicService.class);
// i.setAction(MusicService.ACTION_CMD);
// i.putExtra(MusicService.CMD_NAME, MusicService.CMD_PAUSE);
// mContext.startService(i);
// }
// }
// }
// };
//
// public LocalPlayback(Context context, MusicProvider musicProvider) {
// this.mContext = context;
// this.mMusicProvider = musicProvider;
// this.mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
// // Create the Wifi lock (this does not acquire the lock, this just creates it)
// this.mWifiLock = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE))
// .createWifiLock(WifiManager.WIFI_MODE_FULL, "uAmp_lock");
// this.mState = PlaybackState.STATE_NONE;
// }
//
// @Override
// public void start() {
// }
//
// @Override
// public void stop(boolean notifyListeners) {
// mState = PlaybackState.STATE_STOPPED;
// if (notifyListeners && mCallback != null) {
// mCallback.onPlaybackStatusChanged(mState);
// }
// mCurrentPosition = getCurrentStreamPosition();
// // Give up Audio focus
// giveUpAudioFocus();
// unregisterAudioNoisyReceiver();
// // Relax all resources
// relaxResources(true);
// }
//
// @Override
// public void setState(int state) {
// this.mState = state;
// }
//
// @Override
// public int getState() {
// return mState;
// }
//
// @Override
// public boolean isConnected() {
// return true;
// }
//
// @Override
// public boolean isPlaying() {
// return mPlayOnFocusGain || (mMediaPlayer != null && mMediaPlayer.isPlaying());
// }
//
// @Override
// public int getCurrentStreamPosition() {
// return mMediaPlayer != null ?
// mMediaPlayer.getCurrentPosition() : mCurrentPosition;
// }
//
// @Override
// public void updateLastKnownStreamPosition() {
// if (mMediaPlayer != null) {
// mCurrentPosition = mMediaPlayer.getCurrentPosition();
// }
// }
//
// @Override
// public void play(QueueItem item) {
// mPlayOnFocusGain = true;
// tryToGetAudioFocus();
// registerAudioNoisyReceiver();
// String mediaId = item.getDescription().getMediaId();
// boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId);
// if (mediaHasChanged) {
// mCurrentPosition = 0;
// mCurrentMediaId = mediaId;
// }
//
// if (mState == PlaybackState.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) {
// configMediaPlayerState();
// } else {
// mState = PlaybackState.STATE_STOPPED;
// relaxResources(false); // release everything except MediaPlayer
// MediaMetadata track = mMusicProvider.getMusic(
// MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId()));
//
// //noinspection ResourceType
// String source = track.getString(customMetadataTrackSource_.get_());
// if (source != null) {
// source = source.replaceAll(" ", "%20"); // Escape spaces for URLs
// }
//
// try {
// createMediaPlayerIfNeeded();
//
// mState = PlaybackState.STATE_BUFFERING;
//
// mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mMediaPlayer.setDataSource(source);
//
// // Starts preparing the media player in the background. When
// // it's done, it will call our OnPreparedListener (that is,
// // the onPrepared() method on this class, since we set the
// // listener to 'this'). Until the media player is prepared,
// // we *cannot* call start() on it!
// mMediaPlayer.prepareAsync();
//
// // If we are streaming from the internet, we want to hold a
// // Wifi lock, which prevents the Wifi radio from going to
// // sleep while the song is playing.
// mWifiLock.acquire();
//
// if (mCallback != null) {
// mCallback.onPlaybackStatusChanged(mState);
// }
//
// } catch (IOException ex) {
// LogHelper.e(TAG, ex, "Exception playing song");
// if (mCallback != null) {
// mCallback.onError(ex.getMessage());
// }
// }
// }
// }
//
// @Override
// public void pause() {
// if (mState == PlaybackState.STATE_PLAYING) {
// // Pause media player and cancel the 'foreground service' state.
// if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
// mMediaPlayer.pause();
// mCurrentPosition = mMediaPlayer.getCurrentPosition();
// }
// // while paused, retain the MediaPlayer but give up audio focus
// relaxResources(false);
// }
// mState = PlaybackState.STATE_PAUSED;
// if (mCallback != null) {
// mCallback.onPlaybackStatusChanged(mState);
// }
// unregisterAudioNoisyReceiver();
// }
//
// @Override
// public void seekTo(int position) {
// LogHelper.d(TAG, "seekTo called with ", position);
//
// if (mMediaPlayer == null) {
// // If we do not have a current media player, simply update the current position
// mCurrentPosition = position;
// } else {
// if (mMediaPlayer.isPlaying()) {
// mState = PlaybackState.STATE_BUFFERING;
// }
// registerAudioNoisyReceiver();
// mMediaPlayer.seekTo(position);
// if (mCallback != null) {
// mCallback.onPlaybackStatusChanged(mState);
// }
// }
// }
//
// @Override
// public void setCallback(Callback callback) {
// this.mCallback = callback;
// }
//
// @Override
// public void setCurrentStreamPosition(int pos) {
// this.mCurrentPosition = pos;
// }
//
// @Override
// public void setCurrentMediaId(String mediaId) {
// this.mCurrentMediaId = mediaId;
// }
//
// @Override
// public String getCurrentMediaId() {
// return mCurrentMediaId;
// }
//
// /**
// * Try to get the system audio focus.
// */
// private void tryToGetAudioFocus() {
// LogHelper.d(TAG, "tryToGetAudioFocus");
// int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
// AudioManager.AUDIOFOCUS_GAIN);
// if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// mAudioFocus = AUDIO_FOCUSED;
// } else {
// mAudioFocus = AUDIO_NO_FOCUS_NO_DUCK;
// }
// }
//
// /**
// * Give up the audio focus.
// */
// private void giveUpAudioFocus() {
// LogHelper.d(TAG, "giveUpAudioFocus");
// if (mAudioManager.abandonAudioFocus(this) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// mAudioFocus = AUDIO_NO_FOCUS_NO_DUCK;
// }
// }
//
// /**
// * Reconfigures MediaPlayer according to audio focus settings and
// * starts/restarts it. This method starts/restarts the MediaPlayer
// * respecting the current audio focus state. So if we have focus, it will
// * play normally; if we don't have focus, it will either leave the
// * MediaPlayer paused or set it to a low volume, depending on what is
// * allowed by the current focus settings. This method assumes mPlayer !=
// * null, so if you are calling it, you have to do so from a context where
// * you are sure this is the case.
// */
// private void configMediaPlayerState() {
// LogHelper.d(TAG, "configMediaPlayerState. mAudioFocus=", mAudioFocus);
// if (mAudioFocus == AUDIO_NO_FOCUS_NO_DUCK) {
// // If we don't have audio focus and can't duck, we have to pause,
// if (mState == PlaybackState.STATE_PLAYING) {
// pause();
// }
// } else { // we have audio focus:
// registerAudioNoisyReceiver();
// if (mAudioFocus == AUDIO_NO_FOCUS_CAN_DUCK) {
// mMediaPlayer.setVolume(VOLUME_DUCK, VOLUME_DUCK); // we'll be relatively quiet
// } else {
// if (mMediaPlayer != null) {
// mMediaPlayer.setVolume(VOLUME_NORMAL, VOLUME_NORMAL); // we can be loud again
// } // else do something for remote client.
// }
// // If we were playing when we lost focus, we need to resume playing.
// if (mPlayOnFocusGain) {
// if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
// LogHelper.d(TAG,"configMediaPlayerState startMediaPlayer. seeking to ",
// mCurrentPosition);
// if (mCurrentPosition == mMediaPlayer.getCurrentPosition()) {
// mMediaPlayer.start();
// mState = PlaybackState.STATE_PLAYING;
// } else {
// mMediaPlayer.seekTo(mCurrentPosition);
// mState = PlaybackState.STATE_BUFFERING;
// }
// }
// mPlayOnFocusGain = false;
// }
// }
// if (mCallback != null) {
// mCallback.onPlaybackStatusChanged(mState);
// }
// }
//
// /**
// * Called by AudioManager on audio focus changes.
// * Implementation of {@link android.media.AudioManager.OnAudioFocusChangeListener}
// */
// @Override
// public void onAudioFocusChange(int focusChange) {
// LogHelper.d(TAG, "onAudioFocusChange. focusChange=", focusChange);
// if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// // We have gained focus:
// mAudioFocus = AUDIO_FOCUSED;
//
// } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS ||
// focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
// focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
// // We have lost focus. If we can duck (low playback volume), we can keep playing.
// // Otherwise, we need to pause the playback.
// boolean canDuck = focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK;
// mAudioFocus = canDuck ? AUDIO_NO_FOCUS_CAN_DUCK : AUDIO_NO_FOCUS_NO_DUCK;
//
// // If we are playing, we need to reset media player by calling configMediaPlayerState
// // with mAudioFocus properly set.
// if (mState == PlaybackState.STATE_PLAYING && !canDuck) {
// // If we don't have audio focus and can't duck, we save the information that
// // we were playing, so that we can resume playback once we get the focus back.
// mPlayOnFocusGain = true;
// }
// } else {
// LogHelper.e(TAG, "onAudioFocusChange: Ignoring unsupported focusChange: ", focusChange);
// }
// configMediaPlayerState();
// }
//
// /**
// * Called when MediaPlayer has completed a seek
// *
// * @see OnSeekCompleteListener
// */
// @Override
// public void onSeekComplete(MediaPlayer mp) {
// LogHelper.d(TAG, "onSeekComplete from MediaPlayer:", mp.getCurrentPosition());
// mCurrentPosition = mp.getCurrentPosition();
// if (mState == PlaybackState.STATE_BUFFERING) {
// registerAudioNoisyReceiver();
// mMediaPlayer.start();
// mState = PlaybackState.STATE_PLAYING;
// }
// if (mCallback != null) {
// mCallback.onPlaybackStatusChanged(mState);
// }
// }
//
// /**
// * Called when media player is done playing current song.
// *
// * @see OnCompletionListener
// */
// @Override
// public void onCompletion(MediaPlayer player) {
// LogHelper.d(TAG, "onCompletion from MediaPlayer");
// // The media player finished playing the current song, so we go ahead
// // and start the next.
// if (mCallback != null) {
// mCallback.onCompletion();
// }
// }
//
// /**
// * Called when media player is done preparing.
// *
// * @see OnPreparedListener
// */
// @Override
// public void onPrepared(MediaPlayer player) {
// LogHelper.d(TAG, "onPrepared from MediaPlayer");
// // The media player is done preparing. That means we can start playing if we
// // have audio focus.
// configMediaPlayerState();
// }
//
// /**
// * Called when there's an error playing media. When this happens, the media
// * player goes to the Error state. We warn the user about the error and
// * reset the media player.
// *
// * @see OnErrorListener
// */
// @Override
// public boolean onError(MediaPlayer mp, int what, int extra) {
// LogHelper.e(TAG, "Media player error: what=" + what + ", extra=" + extra);
// if (mCallback != null) {
// mCallback.onError("MediaPlayer error " + what + " (" + extra + ")");
// }
// return true; // true indicates we handled the error
// }
//
// /**
// * Makes sure the media player exists and has been reset. This will create
// * the media player if needed, or reset the existing media player if one
// * already exists.
// */
// private void createMediaPlayerIfNeeded() {
// LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? ", (mMediaPlayer==null));
// if (mMediaPlayer == null) {
// mMediaPlayer = new MediaPlayer();
//
// // Make sure the media player will acquire a wake-lock while
// // playing. If we don't do that, the CPU might go to sleep while the
// // song is playing, causing playback to stop.
// mMediaPlayer.setWakeMode(mContext.getApplicationContext(),
// PowerManager.PARTIAL_WAKE_LOCK);
//
// // we want the media player to notify us when it's ready preparing,
// // and when it's done playing:
// mMediaPlayer.setOnPreparedListener(this);
// mMediaPlayer.setOnCompletionListener(this);
// mMediaPlayer.setOnErrorListener(this);
// mMediaPlayer.setOnSeekCompleteListener(this);
// } else {
// mMediaPlayer.reset();
// }
// }
//
// /**
// * Releases resources used by the service for playback. This includes the
// * "foreground service" status, the wake locks and possibly the MediaPlayer.
// *
// * @param releaseMediaPlayer Indicates whether the Media Player should also
// * be released or not
// */
// private void relaxResources(boolean releaseMediaPlayer) {
// LogHelper.d(TAG, "relaxResources. releaseMediaPlayer=", releaseMediaPlayer);
//
// // stop and release the Media Player, if it's available
// if (releaseMediaPlayer && mMediaPlayer != null) {
// mMediaPlayer.reset();
// mMediaPlayer.release();
// mMediaPlayer = null;
// }
//
// // we can also release the Wifi lock, if we're holding it
// if (mWifiLock.isHeld()) {
// mWifiLock.release();
// }
// }
//
// private void registerAudioNoisyReceiver() {
// if (!mAudioNoisyReceiverRegistered) {
// mContext.registerReceiver(mAudioNoisyReceiver, mAudioNoisyIntentFilter);
// mAudioNoisyReceiverRegistered = true;
// }
// }
//
// private void unregisterAudioNoisyReceiver() {
// if (mAudioNoisyReceiverRegistered) {
// mContext.unregisterReceiver(mAudioNoisyReceiver);
// mAudioNoisyReceiverRegistered = false;
// }
// }
//}
| very minor
| mobile/src/main/ceylon/com/example/android/uamp/playback/LocalPlayback.java | very minor |
|
Java | apache-2.0 | abe12037479751f7269ce5e759f4cca4a23847ca | 0 | DesignAndDeploy/dnd,DesignAndDeploy/dnd,DesignAndDeploy/dnd | package edu.teco.dnd.eclipse;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.ui.part.FileEditorInput;
import edu.teco.dnd.blocks.FunctionBlock;
import edu.teco.dnd.blocks.InvalidFunctionBlockException;
import edu.teco.dnd.deploy.Constraint;
import edu.teco.dnd.deploy.Distribution;
import edu.teco.dnd.deploy.Distribution.BlockTarget;
import edu.teco.dnd.deploy.DistributionGenerator;
import edu.teco.dnd.deploy.MinimalModuleCountEvaluator;
import edu.teco.dnd.deploy.UserConstraints;
import edu.teco.dnd.graphiti.model.FunctionBlockModel;
import edu.teco.dnd.module.Module;
/**
* Planung: Gebraucht: - Verfügbare Anwendungen anzeigen - Anwendung anwählen -
* Verteilungsalgorithmus auswählen - Fest im Code einbinden? - Verteilung
* erstellen lassen und anzeigen - Verteilung bestätigen
*
*/
public class ViewDeploy extends EditorPart implements ModuleManagerListener {
/**
* The logger for this class.
*/
private static final Logger LOGGER = LogManager.getLogger(ViewDeploy.class);
private Display display;
private Activator activator;
private ModuleManager manager;
private ArrayList<UUID> idList = new ArrayList<UUID>();
private Collection<FunctionBlock> functionBlocks;
private Map<TableItem, FunctionBlock> mapItemToBlock;
private Map<FunctionBlock, BlockTarget> mapBlockToTarget;
private Button serverButton;
private Button updateButton; // Button to update moduleCombo
private Button createButton; // Button to create deployment
private Button deployButton; // Button to deploy deployment
private Button constraintsButton;
private Label appName;
private Label blockSpecifications;
private Label blockLabel; // Block to edit specifications:
private Text blockName; // Name of Block
private Label module;
private Label place; // TODO: Problem: In Graphiti kann man auch schon den
// Ort festlegen => Redundanz / Inkonsistenz
private Combo moduleCombo;
private Text places;
private Table deployment; // Table to show blocks and current deployment
private int selectedIndex; // Index of selected field of moduleCombo
private UUID selectedID;
private TableItem selectedItem;
private FunctionBlock selectedBlock; // Functionblock to edit specs
/**
* Enthält für jeden Funktionsblock die UUID des Moduls, auf das er
* gewünscht ist, oder null, falls kein Modul vom User ausgewählt. Achtung:
* Kann UUIDs von Modulen enthalten, die nicht mehr laufen.
*
* Vielleicht gut: Constraints auch speichern, wenn Anwendung geschlossen
* wird.
*/
private Map<FunctionBlock, UUID> moduleConstraints = new HashMap<FunctionBlock, UUID>();
private Map<FunctionBlock, String> placeConstraints = new HashMap<FunctionBlock, String>();
@Override
public void setFocus() {
}
@Override
public void init(IEditorSite site, IEditorInput input)
throws PartInitException {
LOGGER.entry(site, input);
setSite(site);
setInput(input);
activator = Activator.getDefault();
display = Display.getCurrent();
manager = activator.getModuleManager();
if (display == null) {
display = Display.getDefault();
LOGGER.trace(
"Display.getCurrent() returned null, using Display.getDefault(): {}",
display);
}
manager.addModuleManagerListener(this);
LOGGER.exit();
mapBlockToTarget = new HashMap<FunctionBlock, BlockTarget>();
}
@Override
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout();
layout.numColumns = 4;
parent.setLayout(layout);
functionBlocks = new ArrayList<FunctionBlock>();
mapItemToBlock = new HashMap<TableItem, FunctionBlock>();
appName = new Label(parent, SWT.NONE);
appName.pack();
createServerButton(parent);
createBlockSpecsLabel(parent);
createDeploymentTable(parent);
createUpdateButton(parent);
createBlockLabel(parent);
createBlockName(parent);
createCreateButton(parent);
createModuleLabel(parent);
createmoduleCombo(parent);
createDeployButton(parent);
createPlaceLabel(parent);
createPlacesText(parent);
createConstraintsButton(parent);
loadBlocks(getEditorInput());
}
private void createServerButton(Composite parent) {
GridData data = new GridData();
data.horizontalAlignment = SWT.FILL;
serverButton = new Button(parent, SWT.NONE);
serverButton.setLayoutData(data);
if (activator.isRunning()) {
serverButton.setText("Stop server");
} else {
serverButton.setText("Start server");
}
serverButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
new Thread() {
@Override
public void run() {
if (ViewDeploy.this.activator.isRunning()) {
ViewDeploy.this.activator.shutdownServer();
} else {
ViewDeploy.this.activator.startServer();
}
}
}.run();
}
});
}
private void createDeploymentTable(Composite parent) {
GridData data = new GridData();
data.verticalSpan = 4;
data.horizontalAlignment = SWT.FILL;
data.verticalAlignment = SWT.FILL;
data.grabExcessVerticalSpace = true;
data.grabExcessHorizontalSpace = true;
deployment = new Table(parent, SWT.NONE);
deployment.setLinesVisible(true);
deployment.setHeaderVisible(true);
deployment.setLayoutData(data);
TableColumn column1 = new TableColumn(deployment, SWT.None);
column1.setText("Function Block");
TableColumn column2 = new TableColumn(deployment, SWT.NONE);
column2.setText("Module");
column2.setToolTipText("Deploy Block on this Module, if possible. No module selected means no constraint for deployment");
TableColumn column3 = new TableColumn(deployment, SWT.NONE);
column3.setText("place");
column3.setToolTipText("Deploy Block at this place, if possible. No place selected means no constraint for deployment");
TableColumn column4 = new TableColumn(deployment, SWT.NONE);
column4.setText("Deployed on:");
column4.setToolTipText("Module assigned to the Block by the deployment algorithm");
TableColumn column5 = new TableColumn(deployment, SWT.NONE);
column5.setText("Deployed at:");
column5.setToolTipText("Place the Block will be deployed to");
deployment.getColumn(0).pack();
deployment.getColumn(1).pack();
deployment.getColumn(2).pack();
deployment.getColumn(3).pack();
deployment.getColumn(4).pack();
deployment.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ViewDeploy.this.blockSelected();
}
});
}
private void createUpdateButton(Composite parent) {
GridData data = new GridData();
data.horizontalAlignment = SWT.FILL;
updateButton = new Button(parent, SWT.NONE);
updateButton.setLayoutData(data);
updateButton.setText("Update");
updateButton.setToolTipText("Updates information on moduleCombo");
updateButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ViewDeploy.this.update();
}
});
updateButton.pack();
}
private void createBlockSpecsLabel(Composite parent) {
GridData data = new GridData();
data.horizontalSpan = 2;
blockSpecifications = new Label(parent, SWT.NONE);
blockSpecifications.setText("Block Specifications:");
blockSpecifications.setLayoutData(data);
blockSpecifications.pack();
}
private void createCreateButton(Composite parent) {
GridData data = new GridData();
data.horizontalAlignment = SWT.FILL;
createButton = new Button(parent, SWT.NONE);
createButton.setLayoutData(data);
createButton.setText("Create Deployment");
createButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ViewDeploy.this.create();
}
});
}
private void createBlockLabel(Composite parent) {
blockLabel = new Label(parent, SWT.NONE);
blockLabel.setText("Name:");
blockLabel.pack();
}
private void createBlockName(Composite parent) {
GridData data = new GridData();
data.horizontalAlignment = SWT.FILL;
blockName = new Text(parent, SWT.NONE);
blockName.setLayoutData(data);
blockName.setText("(select block on the left)");
blockName.setEnabled(false);
blockName.pack();
}
private void createDeployButton(Composite parent) {
GridData data = new GridData();
data.verticalSpan = 3;
data.horizontalAlignment = SWT.FILL;
data.verticalAlignment = SWT.BEGINNING;
deployButton = new Button(parent, SWT.NONE);
deployButton.setText("Deploy");
deployButton
.setToolTipText("Submit the created deployment to deploy your application");
deployButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ViewDeploy.this.deploy();
}
});
deployButton.setLayoutData(data);
}
private void createModuleLabel(Composite parent) {
module = new Label(parent, SWT.NONE);
module.setText("Module:");
module.setToolTipText("Select a Module for this function block");
module.pack();
}
private void createmoduleCombo(Composite parent) {
GridData data = new GridData();
data.verticalAlignment = SWT.BEGINNING;
data.horizontalAlignment = SWT.FILL;
moduleCombo = new Combo(parent, SWT.NONE);
moduleCombo.setLayoutData(data);
moduleCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ViewDeploy.this.moduleSelected();
}
});
moduleCombo.setEnabled(false);
}
private void createPlaceLabel(Composite parent) {
GridData data = new GridData();
data.verticalAlignment = SWT.BEGINNING;
data.verticalSpan = 2;
place = new Label(parent, SWT.NONE);
place.setLayoutData(data);
place.setText("Place:");
place.setToolTipText("Select a place for this function block");
place.pack();
}
private void createPlacesText(Composite parent) {
GridData data = new GridData();
data.verticalAlignment = SWT.BEGINNING;
data.horizontalAlignment = SWT.FILL;
places = new Text(parent, SWT.NONE);
places.setToolTipText("Enter location for selected Function Block");
places.setLayoutData(data);
places.setEnabled(false);
}
private void createConstraintsButton(Composite parent) {
GridData data = new GridData();
data.horizontalAlignment = SWT.FILL;
data.verticalAlignment = SWT.BEGINNING;
constraintsButton = new Button(parent, SWT.NONE);
constraintsButton.setLayoutData(data);
constraintsButton.setText("Save constraints");
constraintsButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ViewDeploy.this.saveConstraints();
}
});
constraintsButton.setEnabled(false);
constraintsButton.pack();
}
/**
* Invoked whenever the Update Button is pressed.
*/
private void update() {
if (Activator.getDefault().isRunning()) {
warn("Not implemented yet. \n Later: Will update information on moduleCombo");
} else {
warn("Server not running");
}
}
/**
* Invoked whenever the Create Button is pressed.
*/
private void create() {
Collection<Module> moduleCollection = getModuleCollection();
if (functionBlocks.isEmpty()) {
warn("No blocks to distribute");
return;
}
if (moduleCollection.isEmpty()) {
warn("No modules to deploy on");
return;
}
Collection<Constraint> constraints = new ArrayList<Constraint>();
constraints
.add(new UserConstraints(moduleConstraints, placeConstraints));
DistributionGenerator generator = new DistributionGenerator(
new MinimalModuleCountEvaluator(), constraints);
Distribution dist = generator.getDistribution(functionBlocks,
moduleCollection);
if (dist.getMapping() == null) {
warn("No valid deployment exists");
} else {
mapBlockToTarget = dist.getMapping();
for (FunctionBlock block : mapBlockToTarget.keySet()) {
TableItem item = getItem(block); // TODO: Effizienter! dauert.
item.setText(1, mapBlockToTarget.get(block).getModule()
.getName());
item.setText(2, mapBlockToTarget.get(block).getModule()
.getLocation());
}
}
}
/**
* Invoked whenever the Deploy Button is pressed.
*/
private void deploy() {
if (mapBlockToTarget.isEmpty()) {
warn("No deployment created yet");
return;
}
// TODO: deploy map.
}
/**
* Invoked whenever a Function Block from the deploymentTable is selected.
*/
private void blockSelected() {
moduleCombo.setEnabled(true);
places.setEnabled(true);
constraintsButton.setEnabled(true);
blockName.setEnabled(true);
TableItem[] items = deployment.getSelection();
if (items.length == 1) {
selectedItem = items[0];
selectedBlock = mapItemToBlock.get(items[0]);
blockName.setText(selectedBlock.getBlockName());
if (placeConstraints.containsKey(selectedBlock)) {
places.setText(placeConstraints.get(selectedBlock));
} else {
places.setText("");
}
}
selectedIndex = -1;
selectedID = null;
}
/**
* Invoked whenever a Module from moduleCombo is selected.
*/
private void moduleSelected() {
selectedIndex = moduleCombo.getSelectionIndex();
selectedID = idList.get(selectedIndex);
}
private void saveConstraints() {
String text = places.getText();
if (!text.isEmpty() && selectedID != null) { // skfdjhasdfhsdfksjdhkfjhsdfkjsldkfjslkdjfsajdhfka
// bka bla bla bla lkj j
// sdf sdf
int cancel = warn("You entered both a place and a module. " +
"Keep in mind that if the module doesn't match the place," +
" no possible distribution will be found." +
" If you still want to save both the module and the place" +
" for this function block, press OK. " +
"If you want to abort, close this window.");
if (cancel == -4) {
return;
}
}
if (text.isEmpty()) {
placeConstraints.remove(selectedBlock);
} else {
placeConstraints.put(selectedBlock, text);
}
selectedItem.setText(2, text);
if (selectedID != null && selectedIndex > -1) {
moduleConstraints.put(selectedBlock, selectedID);
String module = moduleCombo.getItem(selectedIndex);
selectedItem.setText(1, module);
} else {
selectedItem.setText(1, "(no module assigned)");
moduleConstraints.remove(selectedBlock);
}
selectedBlock.setBlockName(this.blockName.getText());
selectedItem.setText(0, blockName.getText());
}
/**
* Adds a Module ID to the moduleCombo.
*
* @param id
* the ID to add
*/
private synchronized void addID(final UUID id) {
LOGGER.entry(id);
if (!idList.contains(id)) {
LOGGER.trace("id {} is new, adding", id);
moduleCombo.add(id.toString());
idList.add(id);
} else {
LOGGER.debug("trying to add existing id {}", id);
}
LOGGER.exit();
}
/**
* Removes a Module ID from the moduleCombo.
*
* @param id
* the ID to remove
*/
private synchronized void removeID(final UUID id) {
LOGGER.entry(id);
int index = idList.indexOf(id);
if (index >= 0) {
moduleCombo.remove(index);
idList.remove(index);
LOGGER.trace("found combo entry for id {}", id);
} else {
LOGGER.debug("trying to remove nonexistant id {}", id);
}
LOGGER.exit();
}
/**
* Tries to load function blocks from input.
*
* @param input
* the input of the editor
*/
private void loadBlocks(IEditorInput input) {
if (input instanceof FileEditorInput) {
try {
functionBlocks = loadInput((FileEditorInput) input);
} catch (IOException e) {
LOGGER.catching(e);
} catch (InvalidFunctionBlockException e) {
LOGGER.catching(e);
}
} else {
LOGGER.error("Input is not a FileEditorInput {}", input);
}
for (FunctionBlock block : functionBlocks) {
TableItem item = new TableItem(deployment, SWT.NONE);
if (block.getBlockName() != null) {
item.setText(0, block.getBlockName());
}
item.setText(1, "(no module assigned yet)");
item.setText(3, "(not deployed yet)");
mapItemToBlock.put(item, block);
}
}
/**
* Loads the given data flow graph. The file given in the editor input must
* be a valid graph. It is loaded and converted into actual FunctionBlocks.
*
* @param input
* the input of the editor
* @return a collection of FunctionBlocks that were defined in the model
* @throws IOException
* if reading fails
* @throws InvalidFunctionBlockException
* if converting the model into actual FunctionBlocks fails
*/
private Collection<FunctionBlock> loadInput(final FileEditorInput input)
throws IOException, InvalidFunctionBlockException {
LOGGER.entry(input);
Collection<FunctionBlock> blockList = new ArrayList<FunctionBlock>();
appName.setText(input.getFile().getName().replaceAll("\\.diagram", ""));
Set<IPath> paths = EclipseUtil.getAbsoluteBinPaths(input.getFile()
.getProject());
LOGGER.debug("using paths {}", paths);
URL[] urls = new URL[paths.size()];
String[] classpath = new String[paths.size()];
int i = 0;
for (IPath path : paths) {
urls[i] = path.toFile().toURI().toURL();
classpath[i] = path.toFile().getPath();
i++;
}
URLClassLoader classLoader = new URLClassLoader(urls, getClass()
.getClassLoader());
URI uri = URI.createURI(input.getURI().toASCIIString());
Resource resource = new XMIResourceImpl(uri);
resource.load(null);
for (EObject object : resource.getContents()) {
if (object instanceof FunctionBlockModel) {
LOGGER.trace("found FunctionBlock {}", object);
blockList.add(((FunctionBlockModel) object)
.createBlock(classLoader));
}
}
return blockList;
}
/**
* Opens a warning window with the given message.
*
* @param message
* Warning message
*/
private int warn(String message) {
Display display = Display.getCurrent();
Shell shell = new Shell(display);
MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
dialog.setText("Warning");
dialog.setMessage(message);
return dialog.open();
}
/**
* Returns a Collection of currently running modules that are already
* resolved. Does not contain modules that haven't been resolved from their
* UUID yet.
*
* @return collection of currently running modules to deploy on.
*/
private Collection<Module> getModuleCollection() {
Collection<Module> collection = new ArrayList<Module>();
Map<UUID, Module> map = manager.getMap();
for (UUID id : map.keySet()) {
Module m = map.get(id);
if (m != null) {
collection.add(m);
}
}
return collection;
}
/**
* Returns table item representing a given function block.
*
* @param block
* The block to find in the table
* @return item holding the block
*/
private TableItem getItem(FunctionBlock block) {
UUID id = block.getID();
for (TableItem i : mapItemToBlock.keySet()) {
if (mapItemToBlock.get(i).getID() == id) {
return i;
}
}
return null;
}
@Override
public void doSave(IProgressMonitor monitor) {
// TODO Auto-generated method stub
}
@Override
public void doSaveAs() {
// TODO Auto-generated method stub
}
@Override
public boolean isDirty() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isSaveAsAllowed() {
// TODO Auto-generated method stub
return false;
}
@Override
public void dispose() {
manager.removeModuleManagerListener(this);
}
@Override
public void moduleOnline(final UUID id) {
LOGGER.entry(id);
display.asyncExec(new Runnable() {
@Override
public void run() {
addID(id);
}
});
LOGGER.exit();
}
// TODO: Was tun, wenn auf modul deployt werden soll, das offline ist?
@Override
public void moduleOffline(final UUID id) {
LOGGER.entry(id);
display.asyncExec(new Runnable() {
@Override
public void run() {
removeID(id);
}
});
LOGGER.exit();
}
@Override
public void moduleResolved(final UUID id, final Module module) {
display.asyncExec(new Runnable() {
@Override
public void run() {
int index = idList.indexOf(id);
if (index < 0) {
addID(id);
} else {
String text = id.toString();
text.concat(" : ");
if (module.getName() != null) {
text.concat(module.getName());
}
moduleCombo.setItem(index, text);
// Falls das Modul schon einem FB zugeteilt wurde
if (moduleConstraints.containsValue(id)) {
// Überprüfe alle FB (können auch mehrere sein)
for (FunctionBlock block : moduleConstraints.keySet()) {
// Setze Text neu.
getItem(block).setText(1, text);
}
}
}
}
});
}
@Override
public void serverOnline(final Map<UUID, Module> modules) {
display.asyncExec(new Runnable() {
@Override
public void run() {
if (serverButton != null) {
serverButton.setText("Stop Server");
}
updateButton.setEnabled(true);
createButton.setEnabled(true);
deployButton.setEnabled(true);
moduleCombo.setToolTipText("");
synchronized (ViewDeploy.this) {
while (!idList.isEmpty()) {
removeID(idList.get(0)); // TODO: Unschön, aber geht
// hoffentlich?
}
for (UUID moduleID : modules.keySet()) {
addID(moduleID);
}
}
}
});
}
@Override
public void serverOffline() {
display.asyncExec(new Runnable() {
@Override
public void run() {
if (serverButton != null) {
serverButton.setText("Start Server");
}
updateButton.setEnabled(false);
createButton.setEnabled(false);
deployButton.setEnabled(false);
moduleCombo
.setToolTipText("You have to start the server to be able to select among running modules");
synchronized (ViewDeploy.this) {
while (!idList.isEmpty()) {
removeID(idList.get(0)); // TODO: Unschön, aber geht
// hoffentlich?
}
}
}
});
}
}
| DND/src/edu/teco/dnd/eclipse/ViewDeploy.java | package edu.teco.dnd.eclipse;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.ui.part.FileEditorInput;
import edu.teco.dnd.blocks.FunctionBlock;
import edu.teco.dnd.blocks.InvalidFunctionBlockException;
import edu.teco.dnd.deploy.Constraint;
import edu.teco.dnd.deploy.Distribution;
import edu.teco.dnd.deploy.Distribution.BlockTarget;
import edu.teco.dnd.deploy.DistributionGenerator;
import edu.teco.dnd.deploy.MinimalModuleCountEvaluator;
import edu.teco.dnd.deploy.UserConstraints;
import edu.teco.dnd.graphiti.model.FunctionBlockModel;
import edu.teco.dnd.module.Module;
/**
* Planung: Gebraucht: - Verfügbare Anwendungen anzeigen - Anwendung anwählen -
* Verteilungsalgorithmus auswählen - Fest im Code einbinden? - Verteilung
* erstellen lassen und anzeigen - Verteilung bestätigen
*
*/
public class ViewDeploy extends EditorPart implements ModuleManagerListener {
/**
* The logger for this class.
*/
private static final Logger LOGGER = LogManager.getLogger(ViewDeploy.class);
private Display display;
private Activator activator;
private ModuleManager manager;
private ArrayList<UUID> idList = new ArrayList<UUID>();
private Collection<FunctionBlock> functionBlocks;
private Map<TableItem, FunctionBlock> mapItemToBlock;
private Map<FunctionBlock, BlockTarget> mapBlockToTarget;
private Button serverButton;
private Button updateButton; // Button to update moduleCombo
private Button createButton; // Button to create deployment
private Button deployButton; // Button to deploy deployment
private Button constraintsButton;
private Label appName;
private Label blockSpecifications;
private Label blockLabel; // Block to edit specifications
private Label module;
private Label place; // TODO: Problem: In Graphiti kann man auch schon den
// Ort festlegen => Redundanz / Inkonsistenz
private Combo moduleCombo;
private Text places;
private Table deployment; // Table to show blocks and current deployment
private int selectedIndex; // Index of selected field of moduleCombo
private UUID selectedID;
private TableItem selectedItem;
private FunctionBlock selectedBlock; // Functionblock to edit specs
/**
* Enthält für jeden Funktionsblock die UUID des Moduls, auf das er
* gewünscht ist, oder null, falls kein Modul vom User ausgewählt. Achtung:
* Kann UUIDs von Modulen enthalten, die nicht mehr laufen.
*
* Vielleicht gut: Constraints auch speichern, wenn Anwendung geschlossen
* wird.
*/
private Map<FunctionBlock, UUID> moduleConstraints = new HashMap<FunctionBlock, UUID>();
private Map<FunctionBlock, String> placeConstraints = new HashMap<FunctionBlock, String>();
@Override
public void setFocus() {
}
@Override
public void init(IEditorSite site, IEditorInput input)
throws PartInitException {
LOGGER.entry(site, input);
setSite(site);
setInput(input);
activator = Activator.getDefault();
display = Display.getCurrent();
manager = activator.getModuleManager();
if (display == null) {
display = Display.getDefault();
LOGGER.trace(
"Display.getCurrent() returned null, using Display.getDefault(): {}",
display);
}
manager.addModuleManagerListener(this);
LOGGER.exit();
mapBlockToTarget = new HashMap<FunctionBlock, BlockTarget>();
}
@Override
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout();
layout.numColumns = 4;
parent.setLayout(layout);
functionBlocks = new ArrayList<FunctionBlock>();
mapItemToBlock = new HashMap<TableItem, FunctionBlock>();
appName = new Label(parent, SWT.NONE);
appName.pack();
createServerButton(parent);
createBlockSpecsLabel(parent);
createDeploymentTable(parent);
createUpdateButton(parent);
createBlockLabel(parent);
createCreateButton(parent);
createModuleLabel(parent);
createmoduleCombo(parent);
createDeployButton(parent);
createPlaceLabel(parent);
createPlacesText(parent);
createConstraintsButton(parent);
loadBlocks(getEditorInput());
}
private void createServerButton(Composite parent) {
GridData data = new GridData();
data.horizontalAlignment = SWT.FILL;
serverButton = new Button(parent, SWT.NONE);
serverButton.setLayoutData(data);
if (activator.isRunning()) {
serverButton.setText("Stop server");
} else {
serverButton.setText("Start server");
}
serverButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
new Thread() {
@Override
public void run() {
if (ViewDeploy.this.activator.isRunning()) {
ViewDeploy.this.activator.shutdownServer();
} else {
ViewDeploy.this.activator.startServer();
}
}
}.run();
}
});
}
private void createDeploymentTable(Composite parent) {
GridData data = new GridData();
data.verticalSpan = 4;
data.horizontalAlignment = SWT.FILL;
data.verticalAlignment = SWT.FILL;
data.grabExcessVerticalSpace = true;
data.grabExcessHorizontalSpace = true;
deployment = new Table(parent, SWT.NONE);
deployment.setLinesVisible(true);
deployment.setHeaderVisible(true);
deployment.setLayoutData(data);
TableColumn column1 = new TableColumn(deployment, SWT.None);
column1.setText("Function Block");
TableColumn column2 = new TableColumn(deployment, SWT.NONE);
column2.setText("Module");
column2.setToolTipText("Deploy Block on this Module, if possible. No module selected means no constraint for deployment");
TableColumn column3 = new TableColumn(deployment, SWT.NONE);
column3.setText("place");
column3.setToolTipText("Deploy Block at this place, if possible. No place selected means no constraint for deployment");
TableColumn column4 = new TableColumn(deployment, SWT.NONE);
column4.setText("Deployed on:");
column4.setToolTipText("Module assigned to the Block by the deployment algorithm");
TableColumn column5 = new TableColumn(deployment, SWT.NONE);
column5.setText("Deployed at:");
column5.setToolTipText("Place the Block will be deployed to");
deployment.getColumn(0).pack();
deployment.getColumn(1).pack();
deployment.getColumn(2).pack();
deployment.getColumn(3).pack();
deployment.getColumn(4).pack();
deployment.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ViewDeploy.this.blockSelected();
}
});
}
private void createUpdateButton(Composite parent) {
GridData data = new GridData();
data.horizontalAlignment = SWT.FILL;
updateButton = new Button(parent, SWT.NONE);
updateButton.setLayoutData(data);
updateButton.setText("Update");
updateButton.setToolTipText("Updates information on moduleCombo");
updateButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ViewDeploy.this.update();
}
});
updateButton.pack();
}
private void createBlockSpecsLabel(Composite parent) {
GridData data = new GridData();
data.horizontalSpan = 2;
blockSpecifications = new Label(parent, SWT.NONE);
blockSpecifications.setText("Block Specifications:");
blockSpecifications.setLayoutData(data);
blockSpecifications.pack();
}
private void createCreateButton(Composite parent) {
GridData data = new GridData();
data.horizontalAlignment = SWT.FILL;
createButton = new Button(parent, SWT.NONE);
createButton.setLayoutData(data);
createButton.setText("Create Deployment");
createButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ViewDeploy.this.create();
}
});
}
private void createBlockLabel(Composite parent) {
GridData data = new GridData();
data.horizontalSpan = 2;
blockLabel = new Label(parent, SWT.NONE);
blockLabel.setText("(select block on the left)");
blockLabel.setLayoutData(data);
blockLabel.pack();
}
private void createDeployButton(Composite parent) {
GridData data = new GridData();
data.verticalSpan = 3;
data.horizontalAlignment = SWT.FILL;
data.verticalAlignment = SWT.BEGINNING;
deployButton = new Button(parent, SWT.NONE);
deployButton.setText("Deploy");
deployButton
.setToolTipText("Submit the created deployment to deploy your application");
deployButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ViewDeploy.this.deploy();
}
});
deployButton.setLayoutData(data);
}
private void createModuleLabel(Composite parent) {
module = new Label(parent, SWT.NONE);
module.setText("Module:");
module.setToolTipText("Select a Module for this function block");
module.pack();
}
private void createmoduleCombo(Composite parent) {
GridData data = new GridData();
data.verticalAlignment = SWT.BEGINNING;
data.horizontalAlignment = SWT.FILL;
moduleCombo = new Combo(parent, SWT.NONE);
moduleCombo.setLayoutData(data);
moduleCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ViewDeploy.this.moduleSelected();
}
});
moduleCombo.setEnabled(false);
}
private void createPlaceLabel(Composite parent) {
GridData data = new GridData();
data.verticalAlignment = SWT.BEGINNING;
data.verticalSpan = 2;
place = new Label(parent, SWT.NONE);
place.setLayoutData(data);
place.setText("Place:");
place.setToolTipText("Select a place for this function block");
place.pack();
}
private void createPlacesText(Composite parent) {
GridData data = new GridData();
data.verticalAlignment = SWT.BEGINNING;
data.horizontalAlignment = SWT.FILL;
places = new Text(parent, SWT.NONE);
places.setToolTipText("Enter location for selected Function Block");
places.setLayoutData(data);
places.setEnabled(false);
}
private void createConstraintsButton(Composite parent) {
GridData data = new GridData();
data.horizontalAlignment = SWT.FILL;
data.verticalAlignment = SWT.BEGINNING;
constraintsButton = new Button(parent, SWT.NONE);
constraintsButton.setLayoutData(data);
constraintsButton.setText("Save constraints");
constraintsButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ViewDeploy.this.saveConstraints();
}
});
constraintsButton.setEnabled(false);
constraintsButton.pack();
}
/**
* Invoked whenever the Update Button is pressed.
*/
private void update() {
if (Activator.getDefault().isRunning()) {
warn("Not implemented yet. \n Later: Will update information on moduleCombo");
} else {
warn("Server not running");
}
}
/**
* Invoked whenever the Create Button is pressed.
*/
private void create() {
Collection<Module> moduleCollection = getModuleCollection();
if (functionBlocks.isEmpty()) {
warn("No blocks to distribute");
return;
}
if (moduleCollection.isEmpty()) {
warn("No modules to deploy on");
return;
}
Collection<Constraint> constraints = new ArrayList<Constraint>();
constraints
.add(new UserConstraints(moduleConstraints, placeConstraints));
DistributionGenerator generator = new DistributionGenerator(
new MinimalModuleCountEvaluator(), constraints);
Distribution dist = generator.getDistribution(functionBlocks,
moduleCollection);
if (dist.getMapping() == null) {
warn("No valid deployment exists");
} else {
mapBlockToTarget = dist.getMapping();
for (FunctionBlock block : mapBlockToTarget.keySet()) {
TableItem item = getItem(block); // TODO: Effizienter! dauert.
item.setText(1, mapBlockToTarget.get(block).getModule()
.getName());
item.setText(2, mapBlockToTarget.get(block).getModule()
.getLocation());
}
}
}
/**
* Invoked whenever the Deploy Button is pressed.
*/
private void deploy() {
if (mapBlockToTarget.isEmpty()) {
warn("No deployment created yet");
return;
}
// TODO: deploy map.
}
/**
* Invoked whenever a Function Block from the deploymentTable is selected.
*/
private void blockSelected() {
moduleCombo.setEnabled(true);
places.setEnabled(true);
constraintsButton.setEnabled(true);
TableItem[] items = deployment.getSelection();
if (items.length == 1) {
selectedItem = items[0];
selectedBlock = mapItemToBlock.get(items[0]);
blockLabel.setText(selectedBlock.getType());
if (placeConstraints.containsKey(selectedBlock)) {
places.setText(placeConstraints.get(selectedBlock));
} else {
places.setText("");
}
}
selectedIndex = -1;
selectedID = null;
}
/**
* Invoked whenever a Module from moduleCombo is selected.
*/
private void moduleSelected() {
selectedIndex = moduleCombo.getSelectionIndex();
selectedID = idList.get(selectedIndex);
}
private void saveConstraints() {
String text = places.getText();
if (text.isEmpty()) {
placeConstraints.remove(selectedBlock);
} else {
placeConstraints.put(selectedBlock, text);
}
selectedItem.setText(2, text);
if (selectedID != null && selectedIndex > -1) {
moduleConstraints.put(selectedBlock, selectedID);
String module = moduleCombo.getItem(selectedIndex);
selectedItem.setText(1, module);
} else {
selectedItem.setText(1, "(no module assigned)");
moduleConstraints.remove(selectedBlock);
}
}
/**
* Adds a Module ID to the moduleCombo.
*
* @param id
* the ID to add
*/
private synchronized void addID(final UUID id) {
LOGGER.entry(id);
if (!idList.contains(id)) {
LOGGER.trace("id {} is new, adding", id);
moduleCombo.add(id.toString());
idList.add(id);
} else {
LOGGER.debug("trying to add existing id {}", id);
}
LOGGER.exit();
}
/**
* Removes a Module ID from the moduleCombo.
*
* @param id
* the ID to remove
*/
private synchronized void removeID(final UUID id) {
LOGGER.entry(id);
int index = idList.indexOf(id);
if (index >= 0) {
moduleCombo.remove(index);
idList.remove(index);
LOGGER.trace("found combo entry for id {}", id);
} else {
LOGGER.debug("trying to remove nonexistant id {}", id);
}
LOGGER.exit();
}
/**
* Tries to load function blocks from input.
*
* @param input
* the input of the editor
*/
private void loadBlocks(IEditorInput input) {
if (input instanceof FileEditorInput) {
try {
functionBlocks = loadInput((FileEditorInput) input);
} catch (IOException e) {
LOGGER.catching(e);
} catch (InvalidFunctionBlockException e) {
LOGGER.catching(e);
}
} else {
LOGGER.error("Input is not a FileEditorInput {}", input);
}
for (FunctionBlock block : functionBlocks) {
TableItem item = new TableItem(deployment, SWT.NONE);
if (block.getBlockName() != null){
item.setText(0, block.getBlockName());
}
item.setText(1, "(no module assigned yet)");
item.setText(3, "(not deployed yet)");
mapItemToBlock.put(item, block);
}
}
/**
* Loads the given data flow graph. The file given in the editor input must
* be a valid graph. It is loaded and converted into actual FunctionBlocks.
*
* @param input
* the input of the editor
* @return a collection of FunctionBlocks that were defined in the model
* @throws IOException
* if reading fails
* @throws InvalidFunctionBlockException
* if converting the model into actual FunctionBlocks fails
*/
private Collection<FunctionBlock> loadInput(final FileEditorInput input)
throws IOException, InvalidFunctionBlockException {
LOGGER.entry(input);
Collection<FunctionBlock> blockList = new ArrayList<FunctionBlock>();
appName.setText(input.getFile().getName().replaceAll("\\.diagram", ""));
Set<IPath> paths = EclipseUtil.getAbsoluteBinPaths(input.getFile()
.getProject());
LOGGER.debug("using paths {}", paths);
URL[] urls = new URL[paths.size()];
String[] classpath = new String[paths.size()];
int i = 0;
for (IPath path : paths) {
urls[i] = path.toFile().toURI().toURL();
classpath[i] = path.toFile().getPath();
i++;
}
URLClassLoader classLoader = new URLClassLoader(urls, getClass()
.getClassLoader());
URI uri = URI.createURI(input.getURI().toASCIIString());
Resource resource = new XMIResourceImpl(uri);
resource.load(null);
for (EObject object : resource.getContents()) {
if (object instanceof FunctionBlockModel) {
LOGGER.trace("found FunctionBlock {}", object);
blockList.add(((FunctionBlockModel) object)
.createBlock(classLoader));
}
}
return blockList;
}
/**
* Opens a warning window with the given message.
*
* @param message
* Warning message
*/
private void warn(String message) {
Display display = Display.getCurrent();
Shell shell = new Shell(display);
MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
dialog.setText("Warning");
dialog.setMessage(message);
dialog.open();
}
/**
* Returns a Collection of currently running modules that are already
* resolved. Does not contain modules that haven't been resolved from their
* UUID yet.
*
* @return collection of currently running modules to deploy on.
*/
private Collection<Module> getModuleCollection() {
Collection<Module> collection = new ArrayList<Module>();
Map<UUID, Module> map = manager.getMap();
for (UUID id : map.keySet()) {
Module m = map.get(id);
if (m != null) {
collection.add(m);
}
}
return collection;
}
/**
* Returns table item representing a given function block.
*
* @param block
* The block to find in the table
* @return item holding the block
*/
private TableItem getItem(FunctionBlock block) {
UUID id = block.getID();
for (TableItem i : mapItemToBlock.keySet()) {
if (mapItemToBlock.get(i).getID() == id) {
return i;
}
}
return null;
}
@Override
public void doSave(IProgressMonitor monitor) {
// TODO Auto-generated method stub
}
@Override
public void doSaveAs() {
// TODO Auto-generated method stub
}
@Override
public boolean isDirty() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isSaveAsAllowed() {
// TODO Auto-generated method stub
return false;
}
@Override
public void dispose() {
manager.removeModuleManagerListener(this);
}
@Override
public void moduleOnline(final UUID id) {
LOGGER.entry(id);
display.asyncExec(new Runnable() {
@Override
public void run() {
addID(id);
}
});
LOGGER.exit();
}
// TODO: Was tun, wenn auf modul deployt werden soll, das offline ist?
@Override
public void moduleOffline(final UUID id) {
LOGGER.entry(id);
display.asyncExec(new Runnable() {
@Override
public void run() {
removeID(id);
}
});
LOGGER.exit();
}
@Override
public void moduleResolved(final UUID id, final Module module) {
display.asyncExec(new Runnable() {
@Override
public void run() {
int index = idList.indexOf(id);
if (index < 0) {
addID(id);
} else {
String text = id.toString();
text.concat(" : ");
if (module.getName() != null) {
text.concat(module.getName());
}
moduleCombo.setItem(index, text);
// Falls das Modul schon einem FB zugeteilt wurde
if (moduleConstraints.containsValue(id)) {
// Überprüfe alle FB (können auch mehrere sein)
for (FunctionBlock block : moduleConstraints.keySet()) {
// Setze Text neu.
getItem(block).setText(1, text);
}
}
}
}
});
}
@Override
public void serverOnline(final Map<UUID, Module> modules) {
display.asyncExec(new Runnable() {
@Override
public void run() {
if (serverButton != null) {
serverButton.setText("Stop Server");
}
updateButton.setEnabled(true);
createButton.setEnabled(true);
deployButton.setEnabled(true);
synchronized (ViewDeploy.this) {
while (!idList.isEmpty()) {
removeID(idList.get(0)); // TODO: Unschön, aber geht
// hoffentlich?
}
for (UUID moduleID : modules.keySet()) {
addID(moduleID);
}
}
}
});
}
@Override
public void serverOffline() {
display.asyncExec(new Runnable() {
@Override
public void run() {
if (serverButton != null) {
serverButton.setText("Start Server");
}
updateButton.setEnabled(false);
createButton.setEnabled(false);
deployButton.setEnabled(false);
synchronized (ViewDeploy.this) {
while (!idList.isEmpty()) {
removeID(idList.get(0)); // TODO: Unschön, aber geht
// hoffentlich?
}
}
}
});
}
}
| Name of the Function Block can now be changed in the deploy view.
Plus, the user will be warned when trying to specify both place and module for a function block to run on.
| DND/src/edu/teco/dnd/eclipse/ViewDeploy.java | Name of the Function Block can now be changed in the deploy view. Plus, the user will be warned when trying to specify both place and module for a function block to run on. |
|
Java | apache-2.0 | 15e5fd84a05a9ebd8f26096bcbe2bc9e36fb8345 | 0 | chunlinyao/fop,apache/fop,apache/fop,chunlinyao/fop,chunlinyao/fop,chunlinyao/fop,apache/fop,chunlinyao/fop,apache/fop,apache/fop | /*
* $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
package org.apache.fop.image;
// Java
import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.net.URL;
import java.net.MalformedURLException;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.WeakHashMap;
import java.util.Map;
import java.util.HashSet;
import java.util.Set;
import java.util.Collections;
import java.util.Iterator;
// FOP
import org.apache.fop.image.analyser.ImageReaderFactory;
import org.apache.fop.image.analyser.ImageReader;
import org.apache.fop.fo.FOUserAgent;
// Avalon
import org.apache.avalon.framework.logger.Logger;
/*
handle context: base dir, logger, caching
*/
/**
* create FopImage objects (with a configuration file - not yet implemented).
* @author Eric SCHAEFFER
*/
public class ImageFactory {
private static ImageFactory factory = new ImageFactory();
ImageCache cache = new ContextImageCache(true);
private ImageFactory() {}
public static ImageFactory getInstance() {
return factory;
}
public static String getURL(String href) {
/*
* According to section 5.11 a <uri-specification> is:
* "url(" + URI + ")"
* according to 7.28.7 a <uri-specification> is:
* URI
* So handle both.
*/
// Get the absolute URL
URL absoluteURL = null;
InputStream imgIS = null;
href = href.trim();
if (href.startsWith("url(") && (href.indexOf(")") != -1)) {
href = href.substring(4, href.indexOf(")")).trim();
if (href.startsWith("'") && href.endsWith("'")) {
href = href.substring(1, href.length() - 1);
} else if (href.startsWith("\"") && href.endsWith("\"")) {
href = href.substring(1, href.length() - 1);
}
} else {
// warn
}
return href;
}
/**
* Get the image from the cache or load.
* If this returns null then the image could not be loaded
* due to an error. Messages should be logged.
* Before calling this the getURL(url) must be used.
*/
public FopImage getImage(String url, FOUserAgent context) {
return cache.getImage(url, context);
}
/**
* Release an image from the cache.
* This can be used if the renderer has its own cache of
* the image.
* The image should then be put into the weak cache.
*/
public void releaseImage(String url, FOUserAgent context) {
cache.releaseImage(url, context);
}
/**
* create an FopImage objects.
* @param href image URL as a String
* @return a new FopImage object
*/
protected static FopImage loadImage(String href, String baseURL,
FOUserAgent ua) {
Logger log = ua.getLogger();
// Get the absolute URL
URL absoluteURL = null;
InputStream imgIS = null;
try {
// try url as complete first, this can cause
// a problem with relative uri's if there is an
// image relative to where fop is run and relative
// to the base dir of the document
try {
absoluteURL = new URL(href);
} catch (MalformedURLException mue) {
// if the href contains only a path then file is assumed
absoluteURL = new URL("file:" + href);
}
imgIS = absoluteURL.openStream();
} catch (MalformedURLException e_context) {
log.error("Error with image URL: " + e_context.getMessage(), e_context);
return null;
}
catch (Exception e) {
// maybe relative
URL context_url = null;
if (baseURL == null) {
log.error("Error with image URL: " + e.getMessage() + " and no base directory is specified", e);
return null;
}
try {
absoluteURL = new URL(baseURL + absoluteURL.getFile());
} catch (MalformedURLException e_context) {
// pb context url
log.error( "Invalid Image URL - error on relative URL : " +
e_context.getMessage(), e_context);
return null;
}
}
// If not, check image type
FopImage.ImageInfo imgInfo = null;
try {
if (imgIS == null) {
imgIS = absoluteURL.openStream();
}
imgInfo = ImageReaderFactory.make(
absoluteURL.toExternalForm(), imgIS, ua);
} catch (Exception e) {
log.error("Error while recovering Image Informations (" +
absoluteURL.toString() + ") : " + e.getMessage(), e);
return null;
}
finally { if (imgIS != null) {
try {
imgIS.close();
} catch (IOException e) {}
}
} if (imgInfo == null) {
log.error("No ImageReader for this type of image (" +
absoluteURL.toString() + ")");
return null;
}
// Associate mime-type to FopImage class
String imgMimeType = imgInfo.mimeType;
String imgClassName = null;
if ("image/gif".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.GifImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/jpeg".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JpegImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/bmp".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.BmpImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/eps".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.EPSImage";
} else if ("image/png".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/tga".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/tiff".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/svg+xml".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.XMLImage";
} else if ("text/xml".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.XMLImage";
}
if (imgClassName == null) {
log.error("Unsupported image type (" +
absoluteURL.toString() + ") : " + imgMimeType);
return null;
}
// load the right image class
// return new <FopImage implementing class>
Object imageInstance = null;
Class imageClass = null;
try {
imageClass = Class.forName(imgClassName);
Class[] imageConstructorParameters = new Class[2];
imageConstructorParameters[0] = java.net.URL.class;
imageConstructorParameters[1] = org.apache.fop.image.FopImage.ImageInfo.class;
Constructor imageConstructor =
imageClass.getDeclaredConstructor(
imageConstructorParameters);
Object[] initArgs = new Object[2];
initArgs[0] = absoluteURL;
initArgs[1] = imgInfo;
imageInstance = imageConstructor.newInstance(initArgs);
} catch (java.lang.reflect.InvocationTargetException ex) {
Throwable t = ex.getTargetException();
String msg;
if (t != null) {
msg = t.getMessage();
} else {
msg = ex.getMessage();
}
log.error("Error creating FopImage object (" +
absoluteURL.toString() + ") : " + msg, (t == null) ? ex:t);
return null;
}
catch (Exception ex) {
log.error("Error creating FopImage object (" +
absoluteURL.toString() + ") : " + ex.getMessage(), ex);
return null;
}
if (!(imageInstance instanceof org.apache.fop.image.FopImage)) {
log.error("Error creating FopImage object (" +
absoluteURL.toString() + ") : " + "class " +
imageClass.getName() + " doesn't implement org.apache.fop.image.FopImage interface");
return null;
}
return (FopImage) imageInstance;
}
}
class BasicImageCache implements ImageCache {
Set invalid = Collections.synchronizedSet(new HashSet());
Map contextStore = Collections.synchronizedMap(new HashMap());
public FopImage getImage(String url, FOUserAgent context) {
if (invalid.contains(url)) {
return null;
}
return null;
}
public void releaseImage(String url, FOUserAgent context) {
// do nothing
}
public void invalidateImage(String url, FOUserAgent context) {
// cap size of invalid list
if (invalid.size() > 100) {
invalid.clear();
}
invalid.add(url);
}
public void removeContext(FOUserAgent context) {
// do nothing
}
}
/**
* This is the context image cache.
* This caches images on the basis of the given context.
* Common images in different contexts are currently not handled.
* There are two possiblities, each context handles its own images
* and renderers can cache information or images are shared and
* all information is retained.
* Once a context is removed then all images are placed into a
* weak hashmap so they may be garbage collected.
*/
class ContextImageCache implements ImageCache {
// if this cache is collective then images can be shared
// among contexts, this implies that the base directory
// is either the same or does not effect the images being
// loaded
boolean collective;
Map contextStore = Collections.synchronizedMap(new HashMap());
Set invalid = null;
Map weakStore = null;
public ContextImageCache(boolean col) {
collective = col;
if(collective) {
weakStore = Collections.synchronizedMap(new WeakHashMap());
invalid = Collections.synchronizedSet(new HashSet());
}
}
// sync around lookups and puts
// another sync around load for a particular image
public FopImage getImage(String url, FOUserAgent context) {
ImageLoader im = null;
// this protects the finding or creating of a new
// ImageLoader for multi threads
synchronized (this) {
if (collective && invalid.contains(url)) {
return null;
}
Context con = (Context) contextStore.get(context);
if (con == null) {
con = new Context(context, collective);
contextStore.put(context, con);
} else {
if(con.invalid(url)) {
return null;
}
im = con.getImage(url);
}
if(im == null && collective) {
for(Iterator iter = contextStore.values().iterator(); iter.hasNext(); ) {
Context c = (Context)iter.next();
if(c != con) {
im = c.getImage(url);
if(im != null) {
break;
}
}
}
if(im == null) {
im = (ImageLoader) weakStore.get(url);
}
}
if (im != null) {
con.putImage(url, im);
} else {
im = con.getImage(url, this);
}
}
// the ImageLoader is synchronized so images with the
// same url will not be loaded at the same time
if (im != null) {
return im.loadImage();
}
return null;
}
public void releaseImage(String url, FOUserAgent context) {
Context con = (Context) contextStore.get(context);
if (con != null) {
if(collective) {
ImageLoader im = con.getImage(url);
weakStore.put(url, im);
}
con.releaseImage(url);
}
}
public void invalidateImage(String url, FOUserAgent context) {
if(collective) {
// cap size of invalid list
if (invalid.size() > 100) {
invalid.clear();
}
invalid.add(url);
}
Context con = (Context) contextStore.get(context);
if (con != null) {
con.invalidateImage(url);
}
}
public void removeContext(FOUserAgent context) {
Context con = (Context) contextStore.get(context);
if (con != null) {
if(collective) {
Map images = con.getImages();
weakStore.putAll(images);
}
contextStore.remove(context);
}
}
class Context {
Map images = Collections.synchronizedMap(new HashMap());
Set invalid = null;
FOUserAgent userAgent;
public Context(FOUserAgent ua, boolean inv) {
userAgent = ua;
if(inv) {
invalid = Collections.synchronizedSet(new HashSet());
}
}
public ImageLoader getImage(String url, ImageCache c) {
if (images.containsKey(url)) {
return (ImageLoader) images.get(url);
}
ImageLoader loader = new ImageLoader(url, c, userAgent);
images.put(url, loader);
return loader;
}
public void putImage(String url, ImageLoader image) {
images.put(url, image);
}
public ImageLoader getImage(String url) {
return (ImageLoader) images.get(url);
}
public void releaseImage(String url) {
images.remove(url);
}
public Map getImages() {
return images;
}
public void invalidateImage(String url) {
invalid.add(url);
}
public boolean invalid(String url) {
return invalid.contains(url);
}
}
}
| src/org/apache/fop/image/ImageFactory.java | /*
* $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
package org.apache.fop.image;
// Java
import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.net.URL;
import java.net.MalformedURLException;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.WeakHashMap;
import java.util.Map;
import java.util.HashSet;
import java.util.Set;
import java.util.Collections;
import java.util.Iterator;
// FOP
import org.apache.fop.image.analyser.ImageReaderFactory;
import org.apache.fop.image.analyser.ImageReader;
import org.apache.fop.fo.FOUserAgent;
// Avalon
import org.apache.avalon.framework.logger.Logger;
/*
handle context: base dir, logger, caching
*/
/**
* create FopImage objects (with a configuration file - not yet implemented).
* @author Eric SCHAEFFER
*/
public class ImageFactory {
private static ImageFactory factory = new ImageFactory();
ImageCache cache = new ContextImageCache(true);
private ImageFactory() {}
public static ImageFactory getInstance() {
return factory;
}
public static String getURL(String href) {
/*
* According to section 5.11 a <uri-specification> is:
* "url(" + URI + ")"
* according to 7.28.7 a <uri-specification> is:
* URI
* So handle both.
*/
// Get the absolute URL
URL absoluteURL = null;
InputStream imgIS = null;
href = href.trim();
if (href.startsWith("url(") && (href.indexOf(")") != -1)) {
href = href.substring(4, href.indexOf(")")).trim();
if (href.startsWith("'") && href.endsWith("'")) {
href = href.substring(1, href.length() - 1);
} else if (href.startsWith("\"") && href.endsWith("\"")) {
href = href.substring(1, href.length() - 1);
}
} else {
// warn
}
return href;
}
/**
* Get the image from the cache or load.
* If this returns null then the image could not be loaded
* due to an error. Messages should be logged.
* Before calling this the getURL(url) must be used.
*/
public FopImage getImage(String url, FOUserAgent context) {
return cache.getImage(url, context);
}
/**
* Release an image from the cache.
* This can be used if the renderer has its own cache of
* the image.
* The image should then be put into the weak cache.
*/
public void releaseImage(String url, FOUserAgent context) {
cache.releaseImage(url, context);
}
/**
* create an FopImage objects.
* @param href image URL as a String
* @return a new FopImage object
*/
protected static FopImage loadImage(String href, String baseURL,
FOUserAgent ua) {
Logger log = ua.getLogger();
// Get the absolute URL
URL absoluteURL = null;
InputStream imgIS = null;
try {
// try url as complete first, this can cause
// a problem with relative uri's if there is an
// image relative to where fop is run and relative
// to the base dir of the document
try {
absoluteURL = new URL(href);
} catch (MalformedURLException mue) {
// if the href contains only a path then file is assumed
absoluteURL = new URL("file:" + href);
}
imgIS = absoluteURL.openStream();
} catch (MalformedURLException e_context) {
log.error("Error with image URL: " + e_context.getMessage(), e_context);
return null;
}
catch (Exception e) {
// maybe relative
URL context_url = null;
if (baseURL == null) {
log.error("Error with image URL: " + e.getMessage() + " and no base directory is specified", e);
return null;
}
try {
absoluteURL = new URL(baseURL + absoluteURL.getFile());
} catch (MalformedURLException e_context) {
// pb context url
log.error( "Invalid Image URL - error on relative URL : " +
e_context.getMessage(), e_context);
return null;
}
}
// If not, check image type
FopImage.ImageInfo imgInfo = null;
try {
if (imgIS == null) {
imgIS = absoluteURL.openStream();
}
imgInfo = ImageReaderFactory.make(
absoluteURL.toExternalForm(), imgIS, ua);
} catch (Exception e) {
log.error("Error while recovering Image Informations (" +
absoluteURL.toString() + ") : " + e.getMessage(), e);
return null;
}
finally { if (imgIS != null) {
try {
imgIS.close();
} catch (IOException e) {}
}
} if (imgInfo == null) {
log.error("No ImageReader for this type of image (" +
absoluteURL.toString() + ")");
return null;
}
// Associate mime-type to FopImage class
String imgMimeType = imgInfo.mimeType;
String imgClassName = null;
if ("image/gif".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.GifImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/jpeg".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JpegImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/bmp".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.BmpImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/eps".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.EPSImage";
} else if ("image/png".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/tga".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/tiff".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/svg+xml".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.XMLImage";
} else if ("text/xml".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.XMLImage";
}
if (imgClassName == null) {
log.error("Unsupported image type (" +
absoluteURL.toString() + ") : " + imgMimeType);
return null;
}
// load the right image class
// return new <FopImage implementing class>
Object imageInstance = null;
Class imageClass = null;
try {
imageClass = Class.forName(imgClassName);
Class[] imageConstructorParameters = new Class[2];
imageConstructorParameters[0] = java.net.URL.class;
imageConstructorParameters[1] = org.apache.fop.image.FopImage.ImageInfo.class;
Constructor imageConstructor =
imageClass.getDeclaredConstructor(
imageConstructorParameters);
Object[] initArgs = new Object[2];
initArgs[0] = absoluteURL;
initArgs[1] = imgInfo;
imageInstance = imageConstructor.newInstance(initArgs);
} catch (java.lang.reflect.InvocationTargetException ex) {
Throwable t = ex.getTargetException();
String msg;
if (t != null) {
msg = t.getMessage();
} else {
msg = ex.getMessage();
}
log.error("Error creating FopImage object (" +
absoluteURL.toString() + ") : " + msg, (t == null) ? ex:t);
return null;
}
catch (Exception ex) {
log.error("Error creating FopImage object (" +
"Error creating FopImage object (" +
absoluteURL.toString() + ") : " + ex.getMessage(), ex);
return null;
}
if (!(imageInstance instanceof org.apache.fop.image.FopImage)) {
log.error("Error creating FopImage object (" +
absoluteURL.toString() + ") : " + "class " +
imageClass.getName() + " doesn't implement org.apache.fop.image.FopImage interface");
return null;
}
return (FopImage) imageInstance;
}
}
class BasicImageCache implements ImageCache {
Set invalid = Collections.synchronizedSet(new HashSet());
Map contextStore = Collections.synchronizedMap(new HashMap());
public FopImage getImage(String url, FOUserAgent context) {
if (invalid.contains(url)) {
return null;
}
return null;
}
public void releaseImage(String url, FOUserAgent context) {
// do nothing
}
public void invalidateImage(String url, FOUserAgent context) {
// cap size of invalid list
if (invalid.size() > 100) {
invalid.clear();
}
invalid.add(url);
}
public void removeContext(FOUserAgent context) {
// do nothing
}
}
/**
* This is the context image cache.
* This caches images on the basis of the given context.
* Common images in different contexts are currently not handled.
* There are two possiblities, each context handles its own images
* and renderers can cache information or images are shared and
* all information is retained.
* Once a context is removed then all images are placed into a
* weak hashmap so they may be garbage collected.
*/
class ContextImageCache implements ImageCache {
// if this cache is collective then images can be shared
// among contexts, this implies that the base directory
// is either the same or does not effect the images being
// loaded
boolean collective;
Map contextStore = Collections.synchronizedMap(new HashMap());
Set invalid = null;
Map weakStore = null;
public ContextImageCache(boolean col) {
collective = col;
if(collective) {
weakStore = Collections.synchronizedMap(new WeakHashMap());
invalid = Collections.synchronizedSet(new HashSet());
}
}
// sync around lookups and puts
// another sync around load for a particular image
public FopImage getImage(String url, FOUserAgent context) {
ImageLoader im = null;
// this protects the finding or creating of a new
// ImageLoader for multi threads
synchronized (this) {
if (collective && invalid.contains(url)) {
return null;
}
Context con = (Context) contextStore.get(context);
if (con == null) {
con = new Context(context, collective);
contextStore.put(context, con);
} else {
if(con.invalid(url)) {
return null;
}
im = con.getImage(url);
}
if(im == null && collective) {
for(Iterator iter = contextStore.values().iterator(); iter.hasNext(); ) {
Context c = (Context)iter.next();
if(c != con) {
im = c.getImage(url);
if(im != null) {
break;
}
}
}
if(im == null) {
im = (ImageLoader) weakStore.get(url);
}
}
if (im != null) {
con.putImage(url, im);
} else {
im = con.getImage(url, this);
}
}
// the ImageLoader is synchronized so images with the
// same url will not be loaded at the same time
if (im != null) {
return im.loadImage();
}
return null;
}
public void releaseImage(String url, FOUserAgent context) {
Context con = (Context) contextStore.get(context);
if (con != null) {
if(collective) {
ImageLoader im = con.getImage(url);
weakStore.put(url, im);
}
con.releaseImage(url);
}
}
public void invalidateImage(String url, FOUserAgent context) {
if(collective) {
// cap size of invalid list
if (invalid.size() > 100) {
invalid.clear();
}
invalid.add(url);
}
Context con = (Context) contextStore.get(context);
if (con != null) {
con.invalidateImage(url);
}
}
public void removeContext(FOUserAgent context) {
Context con = (Context) contextStore.get(context);
if (con != null) {
if(collective) {
Map images = con.getImages();
weakStore.putAll(images);
}
contextStore.remove(context);
}
}
class Context {
Map images = Collections.synchronizedMap(new HashMap());
Set invalid = null;
FOUserAgent userAgent;
public Context(FOUserAgent ua, boolean inv) {
userAgent = ua;
if(inv) {
invalid = Collections.synchronizedSet(new HashSet());
}
}
public ImageLoader getImage(String url, ImageCache c) {
if (images.containsKey(url)) {
return (ImageLoader) images.get(url);
}
ImageLoader loader = new ImageLoader(url, c, userAgent);
images.put(url, loader);
return loader;
}
public void putImage(String url, ImageLoader image) {
images.put(url, image);
}
public ImageLoader getImage(String url) {
return (ImageLoader) images.get(url);
}
public void releaseImage(String url) {
images.remove(url);
}
public Map getImages() {
return images;
}
public void invalidateImage(String url) {
invalid.add(url);
}
public boolean invalid(String url) {
return invalid.contains(url);
}
}
}
| removed repeated string
git-svn-id: 102839466c3b40dd9c7e25c0a1a6d26afc40150a@194959 13f79535-47bb-0310-9956-ffa450edef68
| src/org/apache/fop/image/ImageFactory.java | removed repeated string |
|
Java | apache-2.0 | 61881bb6988aa0320b4bacfabbc0ee6f05f287cb | 0 | srowen/spark,ueshin/apache-spark,milliman/spark,chuckchen/spark,JoshRosen/spark,holdenk/spark,hvanhovell/spark,witgo/spark,jiangxb1987/spark,witgo/spark,cloud-fan/spark,wangyum/spark,wangmiao1981/spark,gengliangwang/spark,apache/spark,vinodkc/spark,witgo/spark,nchammas/spark,gengliangwang/spark,holdenk/spark,wangyum/spark,cloud-fan/spark,holdenk/spark,taroplus/spark,WeichenXu123/spark,nchammas/spark,mahak/spark,hvanhovell/spark,nchammas/spark,srowen/spark,rednaxelafx/apache-spark,shaneknapp/spark,cloud-fan/spark,holdenk/spark,wangyum/spark,taroplus/spark,apache/spark,gengliangwang/spark,hvanhovell/spark,apache/spark,vinodkc/spark,maropu/spark,holdenk/spark,apache/spark,zzcclp/spark,wangmiao1981/spark,HyukjinKwon/spark,jiangxb1987/spark,rednaxelafx/apache-spark,gengliangwang/spark,xuanyuanking/spark,mahak/spark,cloud-fan/spark,jiangxb1987/spark,wangmiao1981/spark,zzcclp/spark,chuckchen/spark,BryanCutler/spark,vinodkc/spark,dongjoon-hyun/spark,jiangxb1987/spark,zero323/spark,shaneknapp/spark,milliman/spark,BryanCutler/spark,witgo/spark,jiangxb1987/spark,xuanyuanking/spark,xuanyuanking/spark,dongjoon-hyun/spark,wangmiao1981/spark,ueshin/apache-spark,shaneknapp/spark,BryanCutler/spark,milliman/spark,zero323/spark,srowen/spark,taroplus/spark,srowen/spark,chuckchen/spark,zero323/spark,taroplus/spark,nchammas/spark,milliman/spark,holdenk/spark,shaneknapp/spark,shaneknapp/spark,HyukjinKwon/spark,cloud-fan/spark,wangyum/spark,HyukjinKwon/spark,cloud-fan/spark,ueshin/apache-spark,jiangxb1987/spark,WeichenXu123/spark,HyukjinKwon/spark,rednaxelafx/apache-spark,wangyum/spark,wangyum/spark,zzcclp/spark,chuckchen/spark,rednaxelafx/apache-spark,zero323/spark,srowen/spark,milliman/spark,xuanyuanking/spark,BryanCutler/spark,WeichenXu123/spark,nchammas/spark,HyukjinKwon/spark,chuckchen/spark,milliman/spark,wangmiao1981/spark,zzcclp/spark,zzcclp/spark,dongjoon-hyun/spark,wangyum/spark,taroplus/spark,rednaxelafx/apache-spark,wangmiao1981/spark,mahak/spark,maropu/spark,witgo/spark,cloud-fan/spark,JoshRosen/spark,ueshin/apache-spark,gengliangwang/spark,mahak/spark,rednaxelafx/apache-spark,hvanhovell/spark,JoshRosen/spark,zero323/spark,taroplus/spark,nchammas/spark,srowen/spark,apache/spark,hvanhovell/spark,HyukjinKwon/spark,WeichenXu123/spark,maropu/spark,zero323/spark,zzcclp/spark,BryanCutler/spark,witgo/spark,apache/spark,JoshRosen/spark,maropu/spark,vinodkc/spark,xuanyuanking/spark,rednaxelafx/apache-spark,WeichenXu123/spark,witgo/spark,xuanyuanking/spark,gengliangwang/spark,dongjoon-hyun/spark,shaneknapp/spark,mahak/spark,WeichenXu123/spark,taroplus/spark,vinodkc/spark,ueshin/apache-spark,zero323/spark,hvanhovell/spark,JoshRosen/spark,zzcclp/spark,milliman/spark,gengliangwang/spark,holdenk/spark,maropu/spark,chuckchen/spark,vinodkc/spark,maropu/spark,hvanhovell/spark,srowen/spark,BryanCutler/spark,ueshin/apache-spark,wangmiao1981/spark,maropu/spark,mahak/spark,chuckchen/spark,jiangxb1987/spark,WeichenXu123/spark,mahak/spark,apache/spark,HyukjinKwon/spark,vinodkc/spark,BryanCutler/spark,JoshRosen/spark,xuanyuanking/spark,ueshin/apache-spark,shaneknapp/spark,JoshRosen/spark,dongjoon-hyun/spark,nchammas/spark,dongjoon-hyun/spark,dongjoon-hyun/spark | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.launcher;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;
import static org.apache.spark.launcher.CommandBuilderUtils.*;
/**
* Abstract Spark command builder that defines common functionality.
*/
abstract class AbstractCommandBuilder {
boolean verbose;
String appName;
String appResource;
String deployMode;
String javaHome;
String mainClass;
String master;
protected String propertiesFile;
final List<String> appArgs;
final List<String> jars;
final List<String> files;
final List<String> pyFiles;
final Map<String, String> childEnv;
final Map<String, String> conf;
// The merged configuration for the application. Cached to avoid having to read / parse
// properties files multiple times.
private Map<String, String> effectiveConfig;
AbstractCommandBuilder() {
this.appArgs = new ArrayList<>();
this.childEnv = new HashMap<>();
this.conf = new HashMap<>();
this.files = new ArrayList<>();
this.jars = new ArrayList<>();
this.pyFiles = new ArrayList<>();
}
/**
* Builds the command to execute.
*
* @param env A map containing environment variables for the child process. It may already contain
* entries defined by the user (such as SPARK_HOME, or those defined by the
* SparkLauncher constructor that takes an environment), and may be modified to
* include other variables needed by the process to be executed.
*/
abstract List<String> buildCommand(Map<String, String> env)
throws IOException, IllegalArgumentException;
/**
* Builds a list of arguments to run java.
*
* This method finds the java executable to use and appends JVM-specific options for running a
* class with Spark in the classpath. It also loads options from the "java-opts" file in the
* configuration directory being used.
*
* Callers should still add at least the class to run, as well as any arguments to pass to the
* class.
*/
List<String> buildJavaCommand(String extraClassPath) throws IOException {
List<String> cmd = new ArrayList<>();
String firstJavaHome = firstNonEmpty(javaHome,
childEnv.get("JAVA_HOME"),
System.getenv("JAVA_HOME"),
System.getProperty("java.home"));
if (firstJavaHome != null) {
cmd.add(join(File.separator, firstJavaHome, "bin", "java"));
}
// Load extra JAVA_OPTS from conf/java-opts, if it exists.
File javaOpts = new File(join(File.separator, getConfDir(), "java-opts"));
if (javaOpts.isFile()) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(javaOpts), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
addOptionString(cmd, line);
}
}
}
cmd.add("-cp");
cmd.add(join(File.pathSeparator, buildClassPath(extraClassPath)));
return cmd;
}
void addOptionString(List<String> cmd, String options) {
if (!isEmpty(options)) {
for (String opt : parseOptionString(options)) {
cmd.add(opt);
}
}
}
/**
* Builds the classpath for the application. Returns a list with one classpath entry per element;
* each entry is formatted in the way expected by <i>java.net.URLClassLoader</i> (more
* specifically, with trailing slashes for directories).
*/
List<String> buildClassPath(String appClassPath) throws IOException {
String sparkHome = getSparkHome();
Set<String> cp = new LinkedHashSet<>();
addToClassPath(cp, appClassPath);
addToClassPath(cp, getConfDir());
boolean prependClasses = !isEmpty(getenv("SPARK_PREPEND_CLASSES"));
boolean isTesting = "1".equals(getenv("SPARK_TESTING"));
if (prependClasses || isTesting) {
String scala = getScalaVersion();
List<String> projects = Arrays.asList(
"common/kvstore",
"common/network-common",
"common/network-shuffle",
"common/network-yarn",
"common/sketch",
"common/tags",
"common/unsafe",
"core",
"examples",
"graphx",
"launcher",
"mllib",
"repl",
"resource-managers/mesos",
"resource-managers/yarn",
"sql/catalyst",
"sql/core",
"sql/hive",
"sql/hive-thriftserver",
"streaming"
);
if (prependClasses) {
if (!isTesting) {
System.err.println(
"NOTE: SPARK_PREPEND_CLASSES is set, placing locally compiled Spark classes ahead of " +
"assembly.");
}
for (String project : projects) {
addToClassPath(cp, String.format("%s/%s/target/scala-%s/classes", sparkHome, project,
scala));
}
}
if (isTesting) {
for (String project : projects) {
addToClassPath(cp, String.format("%s/%s/target/scala-%s/test-classes", sparkHome,
project, scala));
}
}
// Add this path to include jars that are shaded in the final deliverable created during
// the maven build. These jars are copied to this directory during the build.
addToClassPath(cp, String.format("%s/core/target/jars/*", sparkHome));
addToClassPath(cp, String.format("%s/mllib/target/jars/*", sparkHome));
}
// Add Spark jars to the classpath. For the testing case, we rely on the test code to set and
// propagate the test classpath appropriately. For normal invocation, look for the jars
// directory under SPARK_HOME.
boolean isTestingSql = "1".equals(getenv("SPARK_SQL_TESTING"));
String jarsDir = findJarsDir(getSparkHome(), getScalaVersion(), !isTesting && !isTestingSql);
if (jarsDir != null) {
addToClassPath(cp, join(File.separator, jarsDir, "*"));
}
addToClassPath(cp, getenv("HADOOP_CONF_DIR"));
addToClassPath(cp, getenv("YARN_CONF_DIR"));
addToClassPath(cp, getenv("SPARK_DIST_CLASSPATH"));
return new ArrayList<>(cp);
}
/**
* Adds entries to the classpath.
*
* @param cp List to which the new entries are appended.
* @param entries New classpath entries (separated by File.pathSeparator).
*/
private void addToClassPath(Set<String> cp, String entries) {
if (isEmpty(entries)) {
return;
}
String[] split = entries.split(Pattern.quote(File.pathSeparator));
for (String entry : split) {
if (!isEmpty(entry)) {
if (new File(entry).isDirectory() && !entry.endsWith(File.separator)) {
entry += File.separator;
}
cp.add(entry);
}
}
}
String getScalaVersion() {
String scala = getenv("SPARK_SCALA_VERSION");
if (scala != null) {
return scala;
}
String sparkHome = getSparkHome();
File scala212 = new File(sparkHome, "launcher/target/scala-2.12");
File scala213 = new File(sparkHome, "launcher/target/scala-2.13");
checkState(!scala212.isDirectory() || !scala213.isDirectory(),
"Presence of build for multiple Scala versions detected.\n" +
"Either clean one of them or set SPARK_SCALA_VERSION in your environment.");
if (scala213.isDirectory()) {
return "2.13";
} else {
checkState(scala212.isDirectory(), "Cannot find any build directories.");
return "2.12";
}
}
String getSparkHome() {
String path = getenv(ENV_SPARK_HOME);
if (path == null && "1".equals(getenv("SPARK_TESTING"))) {
path = System.getProperty("spark.test.home");
}
checkState(path != null,
"Spark home not found; set it explicitly or use the SPARK_HOME environment variable.");
return path;
}
String getenv(String key) {
return firstNonEmpty(childEnv.get(key), System.getenv(key));
}
void setPropertiesFile(String path) {
effectiveConfig = null;
this.propertiesFile = path;
}
Map<String, String> getEffectiveConfig() throws IOException {
if (effectiveConfig == null) {
effectiveConfig = new HashMap<>(conf);
Properties p = loadPropertiesFile();
for (String key : p.stringPropertyNames()) {
if (!effectiveConfig.containsKey(key)) {
effectiveConfig.put(key, p.getProperty(key));
}
}
}
return effectiveConfig;
}
/**
* Loads the configuration file for the application, if it exists. This is either the
* user-specified properties file, or the spark-defaults.conf file under the Spark configuration
* directory.
*/
private Properties loadPropertiesFile() throws IOException {
Properties props = new Properties();
File propsFile;
if (propertiesFile != null) {
propsFile = new File(propertiesFile);
checkArgument(propsFile.isFile(), "Invalid properties file '%s'.", propertiesFile);
} else {
propsFile = new File(getConfDir(), DEFAULT_PROPERTIES_FILE);
}
if (propsFile.isFile()) {
try (InputStreamReader isr = new InputStreamReader(
new FileInputStream(propsFile), StandardCharsets.UTF_8)) {
props.load(isr);
for (Map.Entry<Object, Object> e : props.entrySet()) {
e.setValue(e.getValue().toString().trim());
}
}
}
return props;
}
private String getConfDir() {
String confDir = getenv("SPARK_CONF_DIR");
return confDir != null ? confDir : join(File.separator, getSparkHome(), "conf");
}
}
| launcher/src/main/java/org/apache/spark/launcher/AbstractCommandBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.launcher;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;
import static org.apache.spark.launcher.CommandBuilderUtils.*;
/**
* Abstract Spark command builder that defines common functionality.
*/
abstract class AbstractCommandBuilder {
boolean verbose;
String appName;
String appResource;
String deployMode;
String javaHome;
String mainClass;
String master;
protected String propertiesFile;
final List<String> appArgs;
final List<String> jars;
final List<String> files;
final List<String> pyFiles;
final Map<String, String> childEnv;
final Map<String, String> conf;
// The merged configuration for the application. Cached to avoid having to read / parse
// properties files multiple times.
private Map<String, String> effectiveConfig;
AbstractCommandBuilder() {
this.appArgs = new ArrayList<>();
this.childEnv = new HashMap<>();
this.conf = new HashMap<>();
this.files = new ArrayList<>();
this.jars = new ArrayList<>();
this.pyFiles = new ArrayList<>();
}
/**
* Builds the command to execute.
*
* @param env A map containing environment variables for the child process. It may already contain
* entries defined by the user (such as SPARK_HOME, or those defined by the
* SparkLauncher constructor that takes an environment), and may be modified to
* include other variables needed by the process to be executed.
*/
abstract List<String> buildCommand(Map<String, String> env)
throws IOException, IllegalArgumentException;
/**
* Builds a list of arguments to run java.
*
* This method finds the java executable to use and appends JVM-specific options for running a
* class with Spark in the classpath. It also loads options from the "java-opts" file in the
* configuration directory being used.
*
* Callers should still add at least the class to run, as well as any arguments to pass to the
* class.
*/
List<String> buildJavaCommand(String extraClassPath) throws IOException {
List<String> cmd = new ArrayList<>();
String[] candidateJavaHomes = new String[] {
javaHome,
childEnv.get("JAVA_HOME"),
System.getenv("JAVA_HOME"),
System.getProperty("java.home")
};
for (String javaHome : candidateJavaHomes) {
if (javaHome != null) {
cmd.add(join(File.separator, javaHome, "bin", "java"));
break;
}
}
// Load extra JAVA_OPTS from conf/java-opts, if it exists.
File javaOpts = new File(join(File.separator, getConfDir(), "java-opts"));
if (javaOpts.isFile()) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(javaOpts), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
addOptionString(cmd, line);
}
}
}
cmd.add("-cp");
cmd.add(join(File.pathSeparator, buildClassPath(extraClassPath)));
return cmd;
}
void addOptionString(List<String> cmd, String options) {
if (!isEmpty(options)) {
for (String opt : parseOptionString(options)) {
cmd.add(opt);
}
}
}
/**
* Builds the classpath for the application. Returns a list with one classpath entry per element;
* each entry is formatted in the way expected by <i>java.net.URLClassLoader</i> (more
* specifically, with trailing slashes for directories).
*/
List<String> buildClassPath(String appClassPath) throws IOException {
String sparkHome = getSparkHome();
Set<String> cp = new LinkedHashSet<>();
addToClassPath(cp, appClassPath);
addToClassPath(cp, getConfDir());
boolean prependClasses = !isEmpty(getenv("SPARK_PREPEND_CLASSES"));
boolean isTesting = "1".equals(getenv("SPARK_TESTING"));
if (prependClasses || isTesting) {
String scala = getScalaVersion();
List<String> projects = Arrays.asList(
"common/kvstore",
"common/network-common",
"common/network-shuffle",
"common/network-yarn",
"common/sketch",
"common/tags",
"common/unsafe",
"core",
"examples",
"graphx",
"launcher",
"mllib",
"repl",
"resource-managers/mesos",
"resource-managers/yarn",
"sql/catalyst",
"sql/core",
"sql/hive",
"sql/hive-thriftserver",
"streaming"
);
if (prependClasses) {
if (!isTesting) {
System.err.println(
"NOTE: SPARK_PREPEND_CLASSES is set, placing locally compiled Spark classes ahead of " +
"assembly.");
}
for (String project : projects) {
addToClassPath(cp, String.format("%s/%s/target/scala-%s/classes", sparkHome, project,
scala));
}
}
if (isTesting) {
for (String project : projects) {
addToClassPath(cp, String.format("%s/%s/target/scala-%s/test-classes", sparkHome,
project, scala));
}
}
// Add this path to include jars that are shaded in the final deliverable created during
// the maven build. These jars are copied to this directory during the build.
addToClassPath(cp, String.format("%s/core/target/jars/*", sparkHome));
addToClassPath(cp, String.format("%s/mllib/target/jars/*", sparkHome));
}
// Add Spark jars to the classpath. For the testing case, we rely on the test code to set and
// propagate the test classpath appropriately. For normal invocation, look for the jars
// directory under SPARK_HOME.
boolean isTestingSql = "1".equals(getenv("SPARK_SQL_TESTING"));
String jarsDir = findJarsDir(getSparkHome(), getScalaVersion(), !isTesting && !isTestingSql);
if (jarsDir != null) {
addToClassPath(cp, join(File.separator, jarsDir, "*"));
}
addToClassPath(cp, getenv("HADOOP_CONF_DIR"));
addToClassPath(cp, getenv("YARN_CONF_DIR"));
addToClassPath(cp, getenv("SPARK_DIST_CLASSPATH"));
return new ArrayList<>(cp);
}
/**
* Adds entries to the classpath.
*
* @param cp List to which the new entries are appended.
* @param entries New classpath entries (separated by File.pathSeparator).
*/
private void addToClassPath(Set<String> cp, String entries) {
if (isEmpty(entries)) {
return;
}
String[] split = entries.split(Pattern.quote(File.pathSeparator));
for (String entry : split) {
if (!isEmpty(entry)) {
if (new File(entry).isDirectory() && !entry.endsWith(File.separator)) {
entry += File.separator;
}
cp.add(entry);
}
}
}
String getScalaVersion() {
String scala = getenv("SPARK_SCALA_VERSION");
if (scala != null) {
return scala;
}
String sparkHome = getSparkHome();
File scala212 = new File(sparkHome, "launcher/target/scala-2.12");
File scala213 = new File(sparkHome, "launcher/target/scala-2.13");
checkState(!scala212.isDirectory() || !scala213.isDirectory(),
"Presence of build for multiple Scala versions detected.\n" +
"Either clean one of them or set SPARK_SCALA_VERSION in your environment.");
if (scala213.isDirectory()) {
return "2.13";
} else {
checkState(scala212.isDirectory(), "Cannot find any build directories.");
return "2.12";
}
}
String getSparkHome() {
String path = getenv(ENV_SPARK_HOME);
if (path == null && "1".equals(getenv("SPARK_TESTING"))) {
path = System.getProperty("spark.test.home");
}
checkState(path != null,
"Spark home not found; set it explicitly or use the SPARK_HOME environment variable.");
return path;
}
String getenv(String key) {
return firstNonEmpty(childEnv.get(key), System.getenv(key));
}
void setPropertiesFile(String path) {
effectiveConfig = null;
this.propertiesFile = path;
}
Map<String, String> getEffectiveConfig() throws IOException {
if (effectiveConfig == null) {
effectiveConfig = new HashMap<>(conf);
Properties p = loadPropertiesFile();
for (String key : p.stringPropertyNames()) {
if (!effectiveConfig.containsKey(key)) {
effectiveConfig.put(key, p.getProperty(key));
}
}
}
return effectiveConfig;
}
/**
* Loads the configuration file for the application, if it exists. This is either the
* user-specified properties file, or the spark-defaults.conf file under the Spark configuration
* directory.
*/
private Properties loadPropertiesFile() throws IOException {
Properties props = new Properties();
File propsFile;
if (propertiesFile != null) {
propsFile = new File(propertiesFile);
checkArgument(propsFile.isFile(), "Invalid properties file '%s'.", propertiesFile);
} else {
propsFile = new File(getConfDir(), DEFAULT_PROPERTIES_FILE);
}
if (propsFile.isFile()) {
try (InputStreamReader isr = new InputStreamReader(
new FileInputStream(propsFile), StandardCharsets.UTF_8)) {
props.load(isr);
for (Map.Entry<Object, Object> e : props.entrySet()) {
e.setValue(e.getValue().toString().trim());
}
}
}
return props;
}
private String getConfDir() {
String confDir = getenv("SPARK_CONF_DIR");
return confDir != null ? confDir : join(File.separator, getSparkHome(), "conf");
}
}
| [SPARK-33835][CORE] Refector AbstractCommandBuilder.buildJavaCommand: use firstNonEmpty
### What changes were proposed in this pull request?
refector AbstractCommandBuilder.buildJavaCommand: use firstNonEmpty
### Why are the changes needed?
For better code understanding, and firstNonEmpty can detect javaHome = " ", an empty string.
### Does this PR introduce _any_ user-facing change?
No
### How was this patch tested?
End to End.
Closes #30831 from offthewall123/refector_AbstractCommandBuilder.
Authored-by: offthewall123 <[email protected]>
Signed-off-by: Sean Owen <[email protected]>
| launcher/src/main/java/org/apache/spark/launcher/AbstractCommandBuilder.java | [SPARK-33835][CORE] Refector AbstractCommandBuilder.buildJavaCommand: use firstNonEmpty |
|
Java | bsd-3-clause | 50dc04ba9610a966c6ced71f5868cda884a68727 | 0 | sebastiangraf/treetank,sebastiangraf/treetank,sebastiangraf/treetank | /*
* Copyright (c) 2007, Marc Kramis
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* $Id$
*/
package org.treetank.xmllayer;
import java.util.ArrayList;
import org.treetank.api.IReadTransaction;
import org.treetank.api.IWriteTransaction;
import org.treetank.utils.FastStack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* <h1>SAXHandler</h1>
*
* <p>
* SAX handler shredding a complete XML document into an TreeTank storage.
* </p>
*/
public class SAXHandler extends DefaultHandler {
/** TreeTank write transaction. */
private final IWriteTransaction mWTX;
/** Stack containing left sibling nodeKey of each level. */
private final FastStack<Long> mLeftSiblingKeyStack;
/** Aggregated pending text node. */
private final StringBuilder mCharacters;
/** List of prefixes bound to last element node. */
private final ArrayList<String> mPrefixList;
/** List of URIs bound to last element node. */
private final ArrayList<String> mURIList;
/**
* Constructor.
*
* @param target File to write to.
*/
public SAXHandler(final IWriteTransaction target) {
mWTX = target;
mLeftSiblingKeyStack = new FastStack<Long>();
mCharacters = new StringBuilder();
mPrefixList = new ArrayList<String>();
mURIList = new ArrayList<String>();
}
/**
* {@inheritDoc}
*/
@Override
public void startDocument() throws SAXException {
mLeftSiblingKeyStack.push(IReadTransaction.NULL_NODE_KEY);
}
/**
* {@inheritDoc}
*/
@Override
public void startElement(
final String uri,
final String localName,
final String qName,
final Attributes attr) throws SAXException {
// Insert text node.
insertPendingText();
// Insert element node and maintain stack.
long key;
if (mLeftSiblingKeyStack.peek() == IReadTransaction.NULL_NODE_KEY) {
key =
mWTX.insertElementAsFirstChild(localName, uri, qNameToPrefix(qName));
} else {
key =
mWTX
.insertElementAsRightSibling(localName, uri, qNameToPrefix(qName));
}
mLeftSiblingKeyStack.pop();
mLeftSiblingKeyStack.push(key);
mLeftSiblingKeyStack.push(IReadTransaction.NULL_NODE_KEY);
// Insert uriKey nodes.
for (int i = 0, n = mPrefixList.size(); i < n; i++) {
//insert(IConstants.NAMESPACE, "", uriList.get(i), prefixList.get(i), "");
}
mPrefixList.clear();
mURIList.clear();
// Insert attribute nodes.
for (int i = 0, l = attr.getLength(); i < l; i++) {
mWTX.insertAttribute(
attr.getLocalName(i),
attr.getURI(i),
qNameToPrefix(attr.getQName(i)),
attr.getValue(i));
}
}
/**
* {@inheritDoc}
*/
@Override
public void endElement(
final String uri,
final String localName,
final String qName) throws SAXException {
insertPendingText();
mLeftSiblingKeyStack.pop();
mWTX.moveTo(mLeftSiblingKeyStack.peek());
}
/**
* {@inheritDoc}
*/
@Override
public void characters(final char[] ch, final int start, final int length)
throws SAXException {
mCharacters.append(ch, start, length);
}
/**
* {@inheritDoc}
*/
@Override
public void processingInstruction(final String target, final String data)
throws SAXException {
}
/**
* {@inheritDoc}
*/
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
mPrefixList.add(prefix);
mURIList.add(uri);
}
/**
* Insert aggregated pending text node.
*
* @throws Exception of any kind.
*/
private final void insertPendingText() {
final String text = mCharacters.toString().trim();
mCharacters.setLength(0);
if (text.length() > 0) {
// Insert text node and maintain stacks.
long key;
if (mLeftSiblingKeyStack.peek() == IReadTransaction.NULL_NODE_KEY) {
key = mWTX.insertTextAsFirstChild(text);
} else {
key = mWTX.insertTextAsRightSibling(text);
}
mLeftSiblingKeyStack.pop();
mLeftSiblingKeyStack.push(key);
}
}
/**
* Extract prefixKey out of qName if there is any.
*
* @param qName Fully qualified name.
* @return Prefix or empty string.
*/
private final String qNameToPrefix(final String qName) {
final int delimiter = qName.indexOf(":");
if (delimiter > -1) {
return qName.substring(0, delimiter);
} else {
return "";
}
}
}
| src/org/treetank/xmllayer/SAXHandler.java | /*
* Copyright (c) 2007, Marc Kramis
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* $Id$
*/
package org.treetank.xmllayer;
import java.util.ArrayList;
import org.treetank.api.IReadTransaction;
import org.treetank.api.IWriteTransaction;
import org.treetank.utils.FastStack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.DefaultHandler;
/**
* <h1>SAXHandler</h1>
*
* <p>
* SAX handler shredding a complete XML document into an TreeTank storage.
* </p>
*/
public class SAXHandler extends DefaultHandler implements LexicalHandler {
/** TreeTank write transaction. */
protected IWriteTransaction mWTX;
/** Stack containing left sibling nodeKey of each level. */
protected FastStack<Long> mLeftSiblingKeyStack;
/** Aggregated pending text node. */
private final StringBuilder mCharacters;
/** List of prefixes bound to last element node. */
private final ArrayList<String> mPrefixList;
/** List of URIs bound to last element node. */
private final ArrayList<String> mURIList;
/**
* Constructor.
*
* @param target File to write to.
*/
public SAXHandler(final IWriteTransaction target) {
mWTX = target;
mLeftSiblingKeyStack = new FastStack<Long>();
mCharacters = new StringBuilder();
mPrefixList = new ArrayList<String>();
mURIList = new ArrayList<String>();
}
/**
* {@inheritDoc}
*/
@Override
public void startDocument() throws SAXException {
try {
mLeftSiblingKeyStack.push(IReadTransaction.NULL_NODE_KEY);
} catch (Exception e) {
throw new SAXException(e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void startElement(
final String uri,
final String localName,
final String qName,
final Attributes attr) throws SAXException {
try {
// Insert text node.
insertPendingText();
// Insert element node and maintain stack.
long key;
if (mLeftSiblingKeyStack.peek() == IReadTransaction.NULL_NODE_KEY) {
key =
mWTX
.insertElementAsFirstChild(localName, uri, qNameToPrefix(qName));
} else {
key =
mWTX.insertElementAsRightSibling(
localName,
uri,
qNameToPrefix(qName));
}
mLeftSiblingKeyStack.pop();
mLeftSiblingKeyStack.push(key);
mLeftSiblingKeyStack.push(IReadTransaction.NULL_NODE_KEY);
// Insert uriKey nodes.
for (int i = 0, n = mPrefixList.size(); i < n; i++) {
//insert(IConstants.NAMESPACE, "", uriList.get(i), prefixList.get(i), "");
}
mPrefixList.clear();
mURIList.clear();
// Insert attribute nodes.
for (int i = 0, l = attr.getLength(); i < l; i++) {
mWTX.insertAttribute(
attr.getLocalName(i),
attr.getURI(i),
qNameToPrefix(attr.getQName(i)),
attr.getValue(i));
}
} catch (Exception e) {
throw new SAXException(e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void endElement(
final String uri,
final String localName,
final String qName) throws SAXException {
try {
insertPendingText();
mLeftSiblingKeyStack.pop();
mWTX.moveTo(mLeftSiblingKeyStack.peek());
} catch (Exception e) {
throw new SAXException(e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void characters(final char[] ch, final int start, final int length)
throws SAXException {
mCharacters.append(ch, start, length);
}
@Override
public void processingInstruction(final String target, final String data)
throws SAXException {
// Ignore it for now. If activated, some axis iterators must be adapted!
// try {
// insert(IConstants.PROCESSING_INSTRUCTION, target, "", "", data);
//
// } catch (Exception e) {
// throw new SAXException(e);
// }
}
/**
* {@inheritDoc}
*/
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
mPrefixList.add(prefix);
mURIList.add(uri);
}
/**
* Insert aggregated pending text node.
*
* @throws Exception of any kind.
*/
private final void insertPendingText() throws Exception {
String text = mCharacters.toString().trim();
mCharacters.setLength(0);
if (text.length() > 0) {
// Insert text node and maintain stacks.
long key;
if (mLeftSiblingKeyStack.peek() == IReadTransaction.NULL_NODE_KEY) {
key = mWTX.insertTextAsFirstChild(text);
} else {
key = mWTX.insertTextAsRightSibling(text);
}
mLeftSiblingKeyStack.pop();
mLeftSiblingKeyStack.push(key);
}
}
/**
* Extract prefixKey out of qName if there is any.
*
* @param qName Fully qualified name.
* @return Prefix or empty string.
*/
private final String qNameToPrefix(final String qName) {
int delimiter = qName.indexOf(":");
if (delimiter > -1) {
return qName.substring(0, delimiter);
} else {
return "";
}
}
public final void comment(final char[] ch, final int start, final int length)
throws SAXException {
// TODO Auto-generated method stub
}
public final void endCDATA() throws SAXException {
// TODO Auto-generated method stub
}
public final void endDTD() throws SAXException {
// TODO Auto-generated method stub
}
public final void endEntity(final String name) throws SAXException {
// TODO Auto-generated method stub
}
public final void startCDATA() throws SAXException {
// TODO Auto-generated method stub
}
public final void startDTD(
final String name,
final String publicId,
final String systemId) throws SAXException {
// System.out.print(name + "; ");
// System.out.print(publicId + "; ");
// System.out.println(systemId);
}
public final void startEntity(String name) throws SAXException {
// System.out.println(name);
}
}
| Refactored SAXHandler.
git-svn-id: a5379eb5ca3beb2b6e029be3b1b7f6aa53f2352b@3608 e3ddb328-5bfe-0310-b762-aafcbcbd2528
| src/org/treetank/xmllayer/SAXHandler.java | Refactored SAXHandler. |
|
Java | bsd-3-clause | 80fc66705f8c157a65194151130ba181a5e0a8a5 | 0 | MatthiasMann/TWLThemeEditor,MatthiasMann/TWLThemeEditor | /*
* Copyright (ch) 2008-2011, Matthias Mann
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Matthias Mann nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package de.matthiasmann.twlthemeeditor.fontgen;
import com.sun.jna.Platform;
import de.matthiasmann.javafreetype.FreeTypeCodePointIterator;
import de.matthiasmann.javafreetype.FreeTypeFont;
import de.matthiasmann.javafreetype.FreeTypeFont.LoadTarget;
import de.matthiasmann.javafreetype.FreeTypeGlyphInfo;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphMetrics;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Comparator;
import java.util.Iterator;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
/**
*
* @author Matthias Mann
*/
public class FontGenerator {
public enum ExportFormat {
XML,
TEXT
};
public static final int BIT_AA = 0;
public static final int FLAG_AA = 1 << BIT_AA;
public enum GeneratorMethod {
AWT_VECTOR(true, FLAG_AA),
AWT_DRAWSTRING(true, FLAG_AA),
FREETYPE2(isFreeTypeAvailable(), FLAG_AA);
public final boolean isAvailable;
public final int supportedFlags;
private GeneratorMethod(boolean isAvailable, int supportedFlags) {
this.isAvailable = isAvailable;
this.supportedFlags = supportedFlags;
}
}
private final FontData fontData;
private final GeneratorMethod generatorMethod;
private Padding padding;
private BufferedImage image;
private GlyphRect[] rects;
private int[][] kernings;
private int ascent;
private int descent;
private int lineHeight;
private int usedTextureHeight;
public FontGenerator(FontData fontData, GeneratorMethod generatorMethod) {
this.fontData = fontData;
this.generatorMethod = generatorMethod;
}
public void generate(int width, int height, CharSet set, Padding padding, Effect.Renderer[] effects, int flags) throws IOException {
if(generatorMethod == GeneratorMethod.FREETYPE2) {
generateFT2(width, height, set, padding, (Effect.FT2Renderer[])effects, flags);
} else {
generateAWT(width, height, set, padding, (Effect.AWTRenderer[])effects, flags, generatorMethod == GeneratorMethod.AWT_DRAWSTRING);
}
}
static class FT2Glyph implements Comparable<FT2Glyph> {
final FreeTypeGlyphInfo info;
final int glyphIndex;
int x;
int y;
public FT2Glyph(FreeTypeGlyphInfo info, int glyphIndex) {
this.info = info;
this.glyphIndex = glyphIndex;
}
public int compareTo(FT2Glyph o) {
int diff = o.info.getHeight() - info.getHeight();
if(diff == 0) {
diff = o.info.getWidth() - info.getWidth();
}
return diff;
}
}
private void generateFT2(int width, int height, CharSet set, Padding padding, Effect.FT2Renderer[] effects, int flags) throws IOException {
boolean useAA = (flags & FLAG_AA) == FLAG_AA;
LoadTarget loadTarget = useAA
? FreeTypeFont.LoadTarget.NORMAL
: FreeTypeFont.LoadTarget.MONO;
this.padding = padding;
this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int paddingHorz = padding.left + padding.right;
int paddingVert = padding.top + padding.bottom;
FreeTypeFont font = FreeTypeFont.create(fontData.getFontFile());
try {
font.setCharSize(0, fontData.getSize(), 72, 72);
ascent = font.getAscent();
descent = font.getDescent();
lineHeight = font.getLineHeight();
int maxHeight = ascent;
IntMap<FT2Glyph> glyphMap = new IntMap<FT2Glyph>();
BitSet usedGlyphCodes = new BitSet();
int numCodePoints = 0;
int numGlyphs = 0;
FreeTypeCodePointIterator iter = font.iterateCodePoints();
while(iter.nextCodePoint()) {
int codepoint = iter.getCodePoint();
int glyphIndex = iter.getGlyphIndex();
if (!set.isIncluded(codepoint)) {
continue;
}
FT2Glyph glyph = glyphMap.get(glyphIndex);
if(glyph == null) {
try {
glyph = new FT2Glyph(font.loadGlyph(glyphIndex), glyphIndex);
glyphMap.put(glyphIndex, glyph);
usedGlyphCodes.set(glyphIndex);
numGlyphs++;
maxHeight = Math.max(glyph.info.getHeight() + paddingVert, maxHeight);
} catch (IOException ex) {
// ignore
/*
Logger.getLogger(FontGenerator.class.getName()).log(Level.SEVERE,
"Can't retrieve glyph " + glyphIndex + " codepoint " + codepoint +
" (" + new String(Character.toChars(codepoint)) + ")", ex);
*/
}
}
if(glyph != null) {
numCodePoints++;
}
}
FT2Glyph[] glyphs = new FT2Glyph[numGlyphs];
Iterator<IntMap.Entry<FT2Glyph>> glyphIter = glyphMap.iterator();
for(int idx=0 ; glyphIter.hasNext() ; idx++) {
glyphs[idx] = glyphIter.next().value;
}
Arrays.sort(glyphs);
int xp = 0;
int dir = 1;
int[] usedY = new int[width];
usedTextureHeight = 0;
FontInfo fontInfo = new FontInfo(maxHeight, descent);
for(Effect.FT2Renderer effect : effects) {
effect.prePageRender(image, fontInfo);
}
for (int glyphNr=0 ; glyphNr<numGlyphs ; glyphNr++) {
final FT2Glyph glyph = glyphs[glyphNr];
final int glyphWidth = glyph.info.getWidth() + paddingHorz;
final int glyphHeight = glyph.info.getHeight() + paddingVert;
if (dir > 0) {
if (xp + glyphWidth > width) {
xp = width - glyphWidth;
dir = -1;
}
} else {
xp -= glyphWidth;
if (xp < 0) {
xp = 0;
dir = 1;
}
}
int yp = 0;
for(int x=0 ; x<glyphWidth ; x++) {
yp = Math.max(yp, usedY[xp + x]);
}
glyph.x = xp;
glyph.y = yp;
//System.out.println("xp="+xp+" yp="+yp+" w="+rect.width+" h="+rect.height+" adv="+rect.advance);
if(glyphWidth > 0) {
font.loadGlyph(glyph.glyphIndex, loadTarget);
if(effects.length > 0) {
int w = glyphWidth + 2;
int h = glyphHeight + 2;
byte[] tmp = new byte[w*h];
font.copyGlyphToByteArray(tmp, w*2+2, w);
for(Effect.FT2Renderer renderer : effects) {
renderer.render(image, fontInfo, xp, yp, w, h, tmp);
}
} else {
font.copyGlpyhToBufferedImage(image, xp, yp, Color.WHITE);
}
}
yp += glyphHeight + 1;
for(int x=0 ; x<glyphWidth ; x++) {
usedY[xp + x] = yp;
}
if(yp > usedTextureHeight) {
usedTextureHeight = yp;
}
if(dir > 0) {
xp += glyphWidth + 1;
} else {
xp -= 1;
}
}
for(Effect.FT2Renderer effect : effects) {
effect.postPageRender(image, fontInfo);
}
rects = new GlyphRect[numCodePoints];
iter = font.iterateCodePoints();
for(int rectNr=0 ; iter.nextCodePoint() ;) {
int codepoint = iter.getCodePoint();
int glyphIndex = iter.getGlyphIndex();
if (!set.isIncluded(codepoint)) {
continue;
}
FT2Glyph glyph = glyphMap.get(glyphIndex);
if(glyph != null) {
GlyphRect rect = new GlyphRect((char)codepoint,
glyph.info.getWidth()+paddingHorz,
glyph.info.getHeight()+paddingVert,
glyph.info.getAdvanceX()+this.padding.advance,
-glyph.info.getOffsetY(),
-glyph.info.getOffsetX(), 0, null);
rect.x = glyph.x;
rect.y = glyph.y;
rects[rectNr++] = rect;
}
}
if(font.hasKerning()) {
ArrayList<int[]> kerns = new ArrayList<int[]>();
for(IntMap.Entry<IntMap<Integer>> from : fontData.getRawKerning()) {
if(usedGlyphCodes.get(from.key)) {
for(IntMap.Entry<Integer> to : from.value) {
if(usedGlyphCodes.get(to.key)) {
int value = font.getKerning(from.key, to.key).x;
if(value != 0) {
fontData.expandKerning(kerns, from.key, to.key, value, set);
}
}
}
}
}
this.kernings = kerns.toArray(new int[kerns.size()][]);
} else {
this.kernings = new int[0][];
}
} finally {
font.close();
}
}
private void generateAWT(int width, int height, CharSet set, Padding padding, Effect.AWTRenderer[] effects, int flags, boolean useDrawString) {
boolean useAA = (flags & FLAG_AA) == FLAG_AA;
this.padding = padding;
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, useAA ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, useAA ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
Font font = fontData.getJavaFont();
g.setFont(font);
FontRenderContext fontRenderContext = g.getFontRenderContext();
kernings = fontData.getKernings(set);
ascent = g.getFontMetrics().getMaxAscent();
descent = g.getFontMetrics().getMaxDescent();
lineHeight = g.getFontMetrics().getLeading() + ascent + descent;
int maxHeight = ascent;
//data = new DataSet(font.getName(), (int) font.getSize(), lineHeight, width, height, set.getName(), "font.png");
ArrayList<GlyphRect> rectList = new ArrayList<GlyphRect>();
char[] chBuffer = new char[1];
int codepoint = -1;
while((codepoint=fontData.getNextCodepoint(codepoint)) >= 0) {
if (!set.isIncluded(codepoint)) {
continue;
}
chBuffer[0] = (char)codepoint;
final GlyphVector vector = font.layoutGlyphVector(fontRenderContext, chBuffer, 0, 1, Font.LAYOUT_LEFT_TO_RIGHT);
final GlyphMetrics metrics = vector.getGlyphMetrics(0);
final Rectangle bounds = metrics.getBounds2D().getBounds();
int advance = Math.round(metrics.getAdvanceX());
int glyphWidth = bounds.width + 1 + padding.left + padding.right;
int glyphHeight = bounds.height + 1 + padding.top + padding.bottom;
int xoffset = 1 - bounds.x;
int yoffset = bounds.y - 1;
GlyphRect rect = new GlyphRect(chBuffer[0],
Math.min(glyphWidth, width), glyphHeight,
advance + padding.advance, yoffset,
xoffset + padding.left, padding.top,
vector.getGlyphOutline(0));
maxHeight = Math.max(glyphHeight, maxHeight);
rectList.add(rect);
}
FontInfo fontInfo = new FontInfo(maxHeight, descent);
// sorting of arrays is more efficient then sorting of collections
final int numGlyphs = rectList.size();
rects = rectList.toArray(new GlyphRect[numGlyphs]);
Arrays.sort(rects, new Comparator<GlyphRect>() {
public int compare(GlyphRect a, GlyphRect b) {
int diff = b.height - a.height;
if(diff == 0) {
diff = b.width - a.width;
}
return diff;
}
});
for(Effect.AWTRenderer effect : effects) {
effect.prePageRender(g, fontInfo);
}
g.setColor(Color.white);
int xp = 0;
int dir = 1;
int[] usedY = new int[width];
usedTextureHeight = 0;
for (int i=0 ; i < numGlyphs ; i++) {
final GlyphRect rect = rects[i];
if (dir > 0) {
if (xp + rect.width > width) {
xp = width - rect.width;
dir = -1;
}
} else {
xp -= rect.width;
if (xp < 0) {
xp = 0;
dir = 1;
}
}
int yp = 0;
for(int x=0 ; x<rect.width ; x++) {
yp = Math.max(yp, usedY[xp + x]);
}
rect.x = xp;
rect.y = yp;
//System.out.println("xp="+xp+" yp="+yp+" w="+rect.width+" h="+rect.height+" adv="+rect.advance);
Graphics2D gGlyph = (Graphics2D) g.create(xp, yp, rect.width, rect.height);
try {
for(Effect.AWTRenderer effect : effects) {
effect.preGlyphRender(gGlyph, fontInfo, rect);
}
rect.drawGlyph(gGlyph, useDrawString);
for(Effect.AWTRenderer effect : effects) {
effect.postGlyphRender(gGlyph, fontInfo, rect);
}
} finally {
gGlyph.dispose();
}
yp += rect.height + 1;
for(int x=0 ; x<rect.width ; x++) {
usedY[xp + x] = yp;
}
if(yp > usedTextureHeight) {
usedTextureHeight = yp;
}
if(dir > 0) {
xp += rect.width + 1;
} else {
xp -= 1;
}
}
for(Effect.AWTRenderer effect : effects) {
effect.postPageRender(g, fontInfo);
}
Arrays.sort(rects, new Comparator<GlyphRect>() {
public int compare(GlyphRect a, GlyphRect b) {
return a.ch - b.ch;
}
});
}
public int getImageWidth() {
return image.getWidth();
}
public int getUsedTextureHeight() {
return usedTextureHeight;
}
public int getAscent() {
return ascent;
}
public int getDescent() {
return descent;
}
public int getLineHeight() {
return lineHeight;
}
public int getImageType() {
if(image != null) {
return image.getType();
}
return -1;
}
public boolean getTextureData(IntBuffer ib) {
if(image != null) {
ib.put(((DataBufferInt)image.getRaster().getDataBuffer()).getData());
return true;
}
return false;
}
public boolean getTextureData(ByteBuffer bb) {
if(image != null) {
bb.put(((DataBufferByte)image.getRaster().getDataBuffer()).getData());
return true;
}
return false;
}
public void write(File file, ExportFormat format, boolean fullImageSize) throws IOException {
File dir = file.getParentFile();
String baseName = getBaseName(file);
int height = image.getHeight();
if(!fullImageSize && usedTextureHeight < height) {
height = usedTextureHeight;
}
PNGWriter.write(new File(dir, baseName.concat("_00.png")), image, height);
OutputStream os = new FileOutputStream(file);
try {
switch(format) {
case XML:
writeXML(os, baseName);
break;
case TEXT:
writeText(os, baseName);
break;
default:
throw new AssertionError();
}
} finally {
os.close();
}
}
public File[] getFilesCreatedForName(File file) {
File dir = file.getParentFile();
String baseName = getBaseName(file);
return new File[] {
file,
new File(dir, baseName.concat("_00.png"))
};
}
private void writeXML(OutputStream os, String basename) throws IOException {
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlSerializer xs = factory.newSerializer();
xs.setOutput(os, "UTF8");
xs.startDocument("UTF8", true);
xs.text("\n");
xs.comment("Created by TWL Theme Editor");
xs.text("\n");
xs.startTag(null, "font");
xs.text("\n ");
xs.startTag(null, "info");
xs.attribute(null, "face", fontData.getName());
xs.attribute(null, "size", Integer.toString((int)fontData.getSize()));
xs.attribute(null, "bold", fontData.getJavaFont().isBold() ? "1" : "0");
xs.attribute(null, "italic", fontData.getJavaFont().isItalic() ? "1" : "0");
xs.attribute(null, "charset", "");
xs.attribute(null, "unicode", "1");
xs.attribute(null, "stretchH", "100");
xs.attribute(null, "smooth", "0");
xs.attribute(null, "aa", "1");
xs.attribute(null, "padding", padding.top+","+padding.left+","+padding.bottom+","+padding.right); // order?
xs.attribute(null, "spacing", "1,1");
xs.endTag(null, "info");
xs.text("\n ");
xs.startTag(null, "common");
xs.attribute(null, "lineHeight", Integer.toString(lineHeight + padding.top + padding.bottom));
xs.attribute(null, "base", Integer.toString(ascent));
xs.attribute(null, "scaleW", Integer.toString(image.getWidth()));
xs.attribute(null, "scaleH", Integer.toString(image.getHeight()));
xs.attribute(null, "pages", "1");
xs.attribute(null, "packed", "0");
xs.endTag(null, "common");
xs.text("\n ");
xs.startTag(null, "pages");
xs.text("\n ");
xs.startTag(null, "page");
xs.attribute(null, "id", "0");
xs.attribute(null, "file", basename.concat("_00.png"));
xs.endTag(null, "page");
xs.text("\n ");
xs.endTag(null, "pages");
xs.text("\n ");
xs.startTag(null, "chars");
xs.attribute(null, "count", Integer.toString(rects.length));
for(GlyphRect rect : rects) {
xs.text("\n ");
xs.startTag(null, "char");
xs.attribute(null, "id", Integer.toString(rect.ch));
xs.attribute(null, "x", Integer.toString(rect.x));
xs.attribute(null, "y", Integer.toString(rect.y));
xs.attribute(null, "width", Integer.toString(rect.width));
xs.attribute(null, "height", Integer.toString(rect.height));
xs.attribute(null, "xoffset", Integer.toString(-rect.xDrawOffset));
xs.attribute(null, "yoffset", Integer.toString(ascent + rect.yoffset));
xs.attribute(null, "xadvance", Integer.toString(rect.advance));
xs.attribute(null, "page", "0");
xs.attribute(null, "chnl", "0");
xs.endTag(null, "char");
}
xs.text("\n ");
xs.endTag(null, "chars");
xs.text("\n ");
xs.startTag(null, "kernings");
xs.attribute(null, "count", Integer.toString(kernings.length));
for(int[] kerning : kernings) {
xs.text("\n ");
xs.startTag(null, "kerning");
xs.attribute(null, "first", Integer.toString(kerning[0]));
xs.attribute(null, "second", Integer.toString(kerning[1]));
xs.attribute(null, "amount", Integer.toString(kerning[2]));
xs.endTag(null, "kerning");
xs.comment(" '" + ch2str(kerning[0]) + "' to '" + ch2str(kerning[1]) + "' ");
}
xs.text("\n ");
xs.endTag(null, "kernings");
xs.text("\n");
xs.endTag(null, "font");
xs.endDocument();
} catch (XmlPullParserException ex) {
throw (IOException)(new IOException().initCause(ex));
}
}
public void writeText(OutputStream os, String basename) {
PrintWriter pw = new PrintWriter(os);
pw.printf("info face=%s size=%d bold=%d italic=%d charset=\"\" unicode=1 stretchH=100 smooth=0 aa=1 padding=%d,%d,%d,%d spacing=1,1\n",
fontData.getName(), (int)fontData.getSize(),
fontData.getJavaFont().isBold() ? 1 : 0,
fontData.getJavaFont().isItalic() ? 1 : 0,
padding.top, padding.left, padding.bottom, padding.right);
pw.printf("common lineHeight=%d base=%s scaleW=%s scaleH=%d pages=1 packed=0\n",
lineHeight + padding.bottom + padding.top, ascent, image.getWidth(), image.getHeight());
pw.printf("page id=0 file=%s_00.png\n", basename);
pw.printf("chars count=%d\n", rects.length);
for(GlyphRect rect : rects) {
pw.printf("char id=%d x=%d y=%d width=%d height=%d xoffset=%d yoffset=%d xadvance=%d page=0 chnl=0\n",
(int)rect.ch, rect.x, rect.y, rect.width, rect.height,
-rect.xDrawOffset, ascent+rect.yoffset, rect.advance);
}
pw.printf("kernings count=%d\n", kernings.length);
for(int[] kerning : kernings){
pw.printf("kerning first=%d second=%d amount=%d\n",
kerning[0], kerning[1], kerning[2]);
}
pw.close();
}
private String ch2str(int ch) {
if(Character.isISOControl(ch)) {
return String.format("\\u%04X", ch);
} else {
return Character.toString((char)ch);
}
}
private String getBaseName(File file) {
String baseName = file.getName();
int idx = baseName.lastIndexOf('.');
if(idx > 0) {
baseName = baseName.substring(0, idx);
}
return baseName;
}
static boolean isFreeTypeAvailable() {
if(Platform.isWindows()) {
FreeTypeFont.setNativeLibraryName(Platform.is64Bit()
? "freetype6_amd64" : "freetype6_x86");
}
return FreeTypeFont.isAvailable();
}
}
| src/de/matthiasmann/twlthemeeditor/fontgen/FontGenerator.java | /*
* Copyright (ch) 2008-2011, Matthias Mann
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Matthias Mann nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package de.matthiasmann.twlthemeeditor.fontgen;
import com.sun.jna.Platform;
import de.matthiasmann.javafreetype.FreeTypeCodePointIterator;
import de.matthiasmann.javafreetype.FreeTypeFont;
import de.matthiasmann.javafreetype.FreeTypeGlyphInfo;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphMetrics;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Comparator;
import java.util.Iterator;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
/**
*
* @author Matthias Mann
*/
public class FontGenerator {
public enum ExportFormat {
XML,
TEXT
};
public static final int BIT_AA = 0;
public static final int FLAG_AA = 1 << BIT_AA;
public enum GeneratorMethod {
AWT_VECTOR(true, FLAG_AA),
AWT_DRAWSTRING(true, FLAG_AA),
FREETYPE2(isFreeTypeAvailable(), 0);
public final boolean isAvailable;
public final int supportedFlags;
private GeneratorMethod(boolean isAvailable, int supportedFlags) {
this.isAvailable = isAvailable;
this.supportedFlags = supportedFlags;
}
}
private final FontData fontData;
private final GeneratorMethod generatorMethod;
private Padding padding;
private BufferedImage image;
private GlyphRect[] rects;
private int[][] kernings;
private int ascent;
private int descent;
private int lineHeight;
private int usedTextureHeight;
public FontGenerator(FontData fontData, GeneratorMethod generatorMethod) {
this.fontData = fontData;
this.generatorMethod = generatorMethod;
}
public void generate(int width, int height, CharSet set, Padding padding, Effect.Renderer[] effects, int flags) throws IOException {
if(generatorMethod == GeneratorMethod.FREETYPE2) {
generateFT2(width, height, set, padding, (Effect.FT2Renderer[])effects, flags);
} else {
generateAWT(width, height, set, padding, (Effect.AWTRenderer[])effects, flags, generatorMethod == GeneratorMethod.AWT_DRAWSTRING);
}
}
static class FT2Glyph implements Comparable<FT2Glyph> {
final FreeTypeGlyphInfo info;
final int glyphIndex;
int x;
int y;
public FT2Glyph(FreeTypeGlyphInfo info, int glyphIndex) {
this.info = info;
this.glyphIndex = glyphIndex;
}
public int compareTo(FT2Glyph o) {
int diff = o.info.getHeight() - info.getHeight();
if(diff == 0) {
diff = o.info.getWidth() - info.getWidth();
}
return diff;
}
}
private void generateFT2(int width, int height, CharSet set, Padding padding, Effect.FT2Renderer[] effects, int flags) throws IOException {
this.padding = padding;
this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int paddingHorz = padding.left + padding.right;
int paddingVert = padding.top + padding.bottom;
FreeTypeFont font = FreeTypeFont.create(fontData.getFontFile());
try {
font.setCharSize(0, fontData.getSize(), 72, 72);
ascent = font.getAscent();
descent = font.getDescent();
lineHeight = font.getLineHeight();
int maxHeight = ascent;
IntMap<FT2Glyph> glyphMap = new IntMap<FT2Glyph>();
BitSet usedGlyphCodes = new BitSet();
int numCodePoints = 0;
int numGlyphs = 0;
FreeTypeCodePointIterator iter = font.iterateCodePoints();
while(iter.nextCodePoint()) {
int codepoint = iter.getCodePoint();
int glyphIndex = iter.getGlyphIndex();
if (!set.isIncluded(codepoint)) {
continue;
}
FT2Glyph glyph = glyphMap.get(glyphIndex);
if(glyph == null) {
try {
glyph = new FT2Glyph(font.loadGlyph(glyphIndex), glyphIndex);
glyphMap.put(glyphIndex, glyph);
usedGlyphCodes.set(glyphIndex);
numGlyphs++;
maxHeight = Math.max(glyph.info.getHeight() + paddingVert, maxHeight);
} catch (IOException ex) {
// ignore
/*
Logger.getLogger(FontGenerator.class.getName()).log(Level.SEVERE,
"Can't retrieve glyph " + glyphIndex + " codepoint " + codepoint +
" (" + new String(Character.toChars(codepoint)) + ")", ex);
*/
}
}
if(glyph != null) {
numCodePoints++;
}
}
FT2Glyph[] glyphs = new FT2Glyph[numGlyphs];
Iterator<IntMap.Entry<FT2Glyph>> glyphIter = glyphMap.iterator();
for(int idx=0 ; glyphIter.hasNext() ; idx++) {
glyphs[idx] = glyphIter.next().value;
}
Arrays.sort(glyphs);
int xp = 0;
int dir = 1;
int[] usedY = new int[width];
usedTextureHeight = 0;
FontInfo fontInfo = new FontInfo(maxHeight, descent);
for(Effect.FT2Renderer effect : effects) {
effect.prePageRender(image, fontInfo);
}
for (int glyphNr=0 ; glyphNr<numGlyphs ; glyphNr++) {
final FT2Glyph glyph = glyphs[glyphNr];
final int glyphWidth = glyph.info.getWidth() + paddingHorz;
final int glyphHeight = glyph.info.getHeight() + paddingVert;
if (dir > 0) {
if (xp + glyphWidth > width) {
xp = width - glyphWidth;
dir = -1;
}
} else {
xp -= glyphWidth;
if (xp < 0) {
xp = 0;
dir = 1;
}
}
int yp = 0;
for(int x=0 ; x<glyphWidth ; x++) {
yp = Math.max(yp, usedY[xp + x]);
}
glyph.x = xp;
glyph.y = yp;
//System.out.println("xp="+xp+" yp="+yp+" w="+rect.width+" h="+rect.height+" adv="+rect.advance);
if(glyphWidth > 0) {
font.loadGlyph(glyph.glyphIndex);
if(effects.length > 0) {
int w = glyphWidth + 2;
int h = glyphHeight + 2;
byte[] tmp = new byte[w*h];
font.copyGlyphToByteArray(tmp, w*2+2, w);
for(Effect.FT2Renderer renderer : effects) {
renderer.render(image, fontInfo, xp, yp, w, h, tmp);
}
} else {
font.copyGlpyhToBufferedImage(image, xp, yp, Color.WHITE);
}
}
yp += glyphHeight + 1;
for(int x=0 ; x<glyphWidth ; x++) {
usedY[xp + x] = yp;
}
if(yp > usedTextureHeight) {
usedTextureHeight = yp;
}
if(dir > 0) {
xp += glyphWidth + 1;
} else {
xp -= 1;
}
}
for(Effect.FT2Renderer effect : effects) {
effect.postPageRender(image, fontInfo);
}
rects = new GlyphRect[numCodePoints];
iter = font.iterateCodePoints();
for(int rectNr=0 ; iter.nextCodePoint() ;) {
int codepoint = iter.getCodePoint();
int glyphIndex = iter.getGlyphIndex();
if (!set.isIncluded(codepoint)) {
continue;
}
FT2Glyph glyph = glyphMap.get(glyphIndex);
if(glyph != null) {
GlyphRect rect = new GlyphRect((char)codepoint,
glyph.info.getWidth()+paddingHorz,
glyph.info.getHeight()+paddingVert,
glyph.info.getAdvanceX()+this.padding.advance,
-glyph.info.getOffsetY(),
-glyph.info.getOffsetX(), 0, null);
rect.x = glyph.x;
rect.y = glyph.y;
rects[rectNr++] = rect;
}
}
if(font.hasKerning()) {
ArrayList<int[]> kerns = new ArrayList<int[]>();
for(IntMap.Entry<IntMap<Integer>> from : fontData.getRawKerning()) {
if(usedGlyphCodes.get(from.key)) {
for(IntMap.Entry<Integer> to : from.value) {
if(usedGlyphCodes.get(to.key)) {
int value = font.getKerning(from.key, to.key).x;
if(value != 0) {
fontData.expandKerning(kerns, from.key, to.key, value, set);
}
}
}
}
}
this.kernings = kerns.toArray(new int[kerns.size()][]);
} else {
this.kernings = new int[0][];
}
} finally {
font.close();
}
}
private void generateAWT(int width, int height, CharSet set, Padding padding, Effect.AWTRenderer[] effects, int flags, boolean useDrawString) {
boolean useAA = (flags & FLAG_AA) == FLAG_AA;
this.padding = padding;
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, useAA ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, useAA ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
Font font = fontData.getJavaFont();
g.setFont(font);
FontRenderContext fontRenderContext = g.getFontRenderContext();
kernings = fontData.getKernings(set);
ascent = g.getFontMetrics().getMaxAscent();
descent = g.getFontMetrics().getMaxDescent();
lineHeight = g.getFontMetrics().getLeading() + ascent + descent;
int maxHeight = ascent;
//data = new DataSet(font.getName(), (int) font.getSize(), lineHeight, width, height, set.getName(), "font.png");
ArrayList<GlyphRect> rectList = new ArrayList<GlyphRect>();
char[] chBuffer = new char[1];
int codepoint = -1;
while((codepoint=fontData.getNextCodepoint(codepoint)) >= 0) {
if (!set.isIncluded(codepoint)) {
continue;
}
chBuffer[0] = (char)codepoint;
final GlyphVector vector = font.layoutGlyphVector(fontRenderContext, chBuffer, 0, 1, Font.LAYOUT_LEFT_TO_RIGHT);
final GlyphMetrics metrics = vector.getGlyphMetrics(0);
final Rectangle bounds = metrics.getBounds2D().getBounds();
int advance = Math.round(metrics.getAdvanceX());
int glyphWidth = bounds.width + 1 + padding.left + padding.right;
int glyphHeight = bounds.height + 1 + padding.top + padding.bottom;
int xoffset = 1 - bounds.x;
int yoffset = bounds.y - 1;
GlyphRect rect = new GlyphRect(chBuffer[0],
Math.min(glyphWidth, width), glyphHeight,
advance + padding.advance, yoffset,
xoffset + padding.left, padding.top,
vector.getGlyphOutline(0));
maxHeight = Math.max(glyphHeight, maxHeight);
rectList.add(rect);
}
FontInfo fontInfo = new FontInfo(maxHeight, descent);
// sorting of arrays is more efficient then sorting of collections
final int numGlyphs = rectList.size();
rects = rectList.toArray(new GlyphRect[numGlyphs]);
Arrays.sort(rects, new Comparator<GlyphRect>() {
public int compare(GlyphRect a, GlyphRect b) {
int diff = b.height - a.height;
if(diff == 0) {
diff = b.width - a.width;
}
return diff;
}
});
for(Effect.AWTRenderer effect : effects) {
effect.prePageRender(g, fontInfo);
}
g.setColor(Color.white);
int xp = 0;
int dir = 1;
int[] usedY = new int[width];
usedTextureHeight = 0;
for (int i=0 ; i < numGlyphs ; i++) {
final GlyphRect rect = rects[i];
if (dir > 0) {
if (xp + rect.width > width) {
xp = width - rect.width;
dir = -1;
}
} else {
xp -= rect.width;
if (xp < 0) {
xp = 0;
dir = 1;
}
}
int yp = 0;
for(int x=0 ; x<rect.width ; x++) {
yp = Math.max(yp, usedY[xp + x]);
}
rect.x = xp;
rect.y = yp;
//System.out.println("xp="+xp+" yp="+yp+" w="+rect.width+" h="+rect.height+" adv="+rect.advance);
Graphics2D gGlyph = (Graphics2D) g.create(xp, yp, rect.width, rect.height);
try {
for(Effect.AWTRenderer effect : effects) {
effect.preGlyphRender(gGlyph, fontInfo, rect);
}
rect.drawGlyph(gGlyph, useDrawString);
for(Effect.AWTRenderer effect : effects) {
effect.postGlyphRender(gGlyph, fontInfo, rect);
}
} finally {
gGlyph.dispose();
}
yp += rect.height + 1;
for(int x=0 ; x<rect.width ; x++) {
usedY[xp + x] = yp;
}
if(yp > usedTextureHeight) {
usedTextureHeight = yp;
}
if(dir > 0) {
xp += rect.width + 1;
} else {
xp -= 1;
}
}
for(Effect.AWTRenderer effect : effects) {
effect.postPageRender(g, fontInfo);
}
Arrays.sort(rects, new Comparator<GlyphRect>() {
public int compare(GlyphRect a, GlyphRect b) {
return a.ch - b.ch;
}
});
}
public int getImageWidth() {
return image.getWidth();
}
public int getUsedTextureHeight() {
return usedTextureHeight;
}
public int getAscent() {
return ascent;
}
public int getDescent() {
return descent;
}
public int getLineHeight() {
return lineHeight;
}
public int getImageType() {
if(image != null) {
return image.getType();
}
return -1;
}
public boolean getTextureData(IntBuffer ib) {
if(image != null) {
ib.put(((DataBufferInt)image.getRaster().getDataBuffer()).getData());
return true;
}
return false;
}
public boolean getTextureData(ByteBuffer bb) {
if(image != null) {
bb.put(((DataBufferByte)image.getRaster().getDataBuffer()).getData());
return true;
}
return false;
}
public void write(File file, ExportFormat format, boolean fullImageSize) throws IOException {
File dir = file.getParentFile();
String baseName = getBaseName(file);
int height = image.getHeight();
if(!fullImageSize && usedTextureHeight < height) {
height = usedTextureHeight;
}
PNGWriter.write(new File(dir, baseName.concat("_00.png")), image, height);
OutputStream os = new FileOutputStream(file);
try {
switch(format) {
case XML:
writeXML(os, baseName);
break;
case TEXT:
writeText(os, baseName);
break;
default:
throw new AssertionError();
}
} finally {
os.close();
}
}
public File[] getFilesCreatedForName(File file) {
File dir = file.getParentFile();
String baseName = getBaseName(file);
return new File[] {
file,
new File(dir, baseName.concat("_00.png"))
};
}
private void writeXML(OutputStream os, String basename) throws IOException {
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlSerializer xs = factory.newSerializer();
xs.setOutput(os, "UTF8");
xs.startDocument("UTF8", true);
xs.text("\n");
xs.comment("Created by TWL Theme Editor");
xs.text("\n");
xs.startTag(null, "font");
xs.text("\n ");
xs.startTag(null, "info");
xs.attribute(null, "face", fontData.getName());
xs.attribute(null, "size", Integer.toString((int)fontData.getSize()));
xs.attribute(null, "bold", fontData.getJavaFont().isBold() ? "1" : "0");
xs.attribute(null, "italic", fontData.getJavaFont().isItalic() ? "1" : "0");
xs.attribute(null, "charset", "");
xs.attribute(null, "unicode", "1");
xs.attribute(null, "stretchH", "100");
xs.attribute(null, "smooth", "0");
xs.attribute(null, "aa", "1");
xs.attribute(null, "padding", padding.top+","+padding.left+","+padding.bottom+","+padding.right); // order?
xs.attribute(null, "spacing", "1,1");
xs.endTag(null, "info");
xs.text("\n ");
xs.startTag(null, "common");
xs.attribute(null, "lineHeight", Integer.toString(lineHeight + padding.top + padding.bottom));
xs.attribute(null, "base", Integer.toString(ascent));
xs.attribute(null, "scaleW", Integer.toString(image.getWidth()));
xs.attribute(null, "scaleH", Integer.toString(image.getHeight()));
xs.attribute(null, "pages", "1");
xs.attribute(null, "packed", "0");
xs.endTag(null, "common");
xs.text("\n ");
xs.startTag(null, "pages");
xs.text("\n ");
xs.startTag(null, "page");
xs.attribute(null, "id", "0");
xs.attribute(null, "file", basename.concat("_00.png"));
xs.endTag(null, "page");
xs.text("\n ");
xs.endTag(null, "pages");
xs.text("\n ");
xs.startTag(null, "chars");
xs.attribute(null, "count", Integer.toString(rects.length));
for(GlyphRect rect : rects) {
xs.text("\n ");
xs.startTag(null, "char");
xs.attribute(null, "id", Integer.toString(rect.ch));
xs.attribute(null, "x", Integer.toString(rect.x));
xs.attribute(null, "y", Integer.toString(rect.y));
xs.attribute(null, "width", Integer.toString(rect.width));
xs.attribute(null, "height", Integer.toString(rect.height));
xs.attribute(null, "xoffset", Integer.toString(-rect.xDrawOffset));
xs.attribute(null, "yoffset", Integer.toString(ascent + rect.yoffset));
xs.attribute(null, "xadvance", Integer.toString(rect.advance));
xs.attribute(null, "page", "0");
xs.attribute(null, "chnl", "0");
xs.endTag(null, "char");
}
xs.text("\n ");
xs.endTag(null, "chars");
xs.text("\n ");
xs.startTag(null, "kernings");
xs.attribute(null, "count", Integer.toString(kernings.length));
for(int[] kerning : kernings) {
xs.text("\n ");
xs.startTag(null, "kerning");
xs.attribute(null, "first", Integer.toString(kerning[0]));
xs.attribute(null, "second", Integer.toString(kerning[1]));
xs.attribute(null, "amount", Integer.toString(kerning[2]));
xs.endTag(null, "kerning");
xs.comment(" '" + ch2str(kerning[0]) + "' to '" + ch2str(kerning[1]) + "' ");
}
xs.text("\n ");
xs.endTag(null, "kernings");
xs.text("\n");
xs.endTag(null, "font");
xs.endDocument();
} catch (XmlPullParserException ex) {
throw (IOException)(new IOException().initCause(ex));
}
}
public void writeText(OutputStream os, String basename) {
PrintWriter pw = new PrintWriter(os);
pw.printf("info face=%s size=%d bold=%d italic=%d charset=\"\" unicode=1 stretchH=100 smooth=0 aa=1 padding=%d,%d,%d,%d spacing=1,1\n",
fontData.getName(), (int)fontData.getSize(),
fontData.getJavaFont().isBold() ? 1 : 0,
fontData.getJavaFont().isItalic() ? 1 : 0,
padding.top, padding.left, padding.bottom, padding.right);
pw.printf("common lineHeight=%d base=%s scaleW=%s scaleH=%d pages=1 packed=0\n",
lineHeight + padding.bottom + padding.top, ascent, image.getWidth(), image.getHeight());
pw.printf("page id=0 file=%s_00.png\n", basename);
pw.printf("chars count=%d\n", rects.length);
for(GlyphRect rect : rects) {
pw.printf("char id=%d x=%d y=%d width=%d height=%d xoffset=%d yoffset=%d xadvance=%d page=0 chnl=0\n",
(int)rect.ch, rect.x, rect.y, rect.width, rect.height,
-rect.xDrawOffset, ascent+rect.yoffset, rect.advance);
}
pw.printf("kernings count=%d\n", kernings.length);
for(int[] kerning : kernings){
pw.printf("kerning first=%d second=%d amount=%d\n",
kerning[0], kerning[1], kerning[2]);
}
pw.close();
}
private String ch2str(int ch) {
if(Character.isISOControl(ch)) {
return String.format("\\u%04X", ch);
} else {
return Character.toString((char)ch);
}
}
private String getBaseName(File file) {
String baseName = file.getName();
int idx = baseName.lastIndexOf('.');
if(idx > 0) {
baseName = baseName.substring(0, idx);
}
return baseName;
}
static boolean isFreeTypeAvailable() {
if(Platform.isWindows()) {
FreeTypeFont.setNativeLibraryName(Platform.is64Bit()
? "freetype6_amd64" : "freetype6_x86");
}
return FreeTypeFont.isAvailable();
}
}
| add AA option also for FREETYPE2
| src/de/matthiasmann/twlthemeeditor/fontgen/FontGenerator.java | add AA option also for FREETYPE2 |
|
Java | bsd-3-clause | 2404f0c08d37382b082ae13c56aca35c2adeb696 | 0 | mikebrock/jline,cosmin/jline2,DALDEI/jline2,tkruse/jline2,hns/jline,pcl/jline,gnodet/jline,kaulkie/jline2,ctubbsii/jline2,mikebrock/jline,mikiobraun/jline-fork,mikiobraun/jline-fork,mikiobraun/jline-fork,gnodet/test,hns/jline,fantasy86/jline2,msaxena2/jline2,pcl/jline,scala/scala-jline,renew-tgi/jline2,scala/scala-jline,gnodet/jline | /*
* Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*/
package jline;
import java.io.*;
import java.util.*;
/**
* <p>
* Terminal that is used for unix platforms. Terminal initialization
* is handled by issuing the <em>stty</em> command against the
* <em>/dev/tty</em> file to disable character echoing and enable
* character input. All known unix systems (including
* Linux and Macintosh OS X) support the <em>stty</em>), so this
* implementation should work for an reasonable POSIX system.
* </p>
*
* @author <a href="mailto:[email protected]">Marc Prud'hommeaux</a>
* @author Updates <a href="mailto:[email protected]">Dale Kemp</a> 2005-12-03
*/
public class UnixTerminal extends Terminal {
public static final short ARROW_START = 27;
public static final short ARROW_PREFIX = 91;
public static final short ARROW_LEFT = 68;
public static final short ARROW_RIGHT = 67;
public static final short ARROW_UP = 65;
public static final short ARROW_DOWN = 66;
public static final short O_PREFIX = 79;
public static final short HOME_CODE = 72;
public static final short END_CODE = 70;
private Map terminfo;
private boolean echoEnabled;
private String ttyConfig;
private static String sttyCommand =
System.getProperty("jline.sttyCommand", "stty");
/**
* Remove line-buffered input by invoking "stty -icanon min 1"
* against the current terminal.
*/
public void initializeTerminal() throws IOException, InterruptedException {
// save the initial tty configuration
ttyConfig = stty("-g");
// sanity check
if ((ttyConfig.length() == 0)
|| ((ttyConfig.indexOf("=") == -1)
&& (ttyConfig.indexOf(":") == -1))) {
throw new IOException("Unrecognized stty code: " + ttyConfig);
}
// set the console to be character-buffered instead of line-buffered
stty("-icanon min 1");
// disable character echoing
stty("-echo");
echoEnabled = false;
// at exit, restore the original tty configuration (for JDK 1.3+)
try {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void start() {
try {
restoreTerminal();
} catch (Exception e) {
consumeException(e);
}
}
});
} catch (AbstractMethodError ame) {
// JDK 1.3+ only method. Bummer.
consumeException(ame);
}
}
/**
* Restore the original terminal configuration, which can be used when
* shutting down the console reader. The ConsoleReader cannot be
* used after calling this method.
*/
public void restoreTerminal() throws IOException {
if (ttyConfig != null) {
stty(ttyConfig);
ttyConfig = null;
}
resetTerminal();
}
public int readVirtualKey(InputStream in) throws IOException {
int c = readCharacter(in);
// in Unix terminals, arrow keys are represented by
// a sequence of 3 characters. E.g., the up arrow
// key yields 27, 91, 68
if (c == ARROW_START) {
c = readCharacter(in);
if (c == ARROW_PREFIX || c == O_PREFIX) {
c = readCharacter(in);
if (c == ARROW_UP) {
return CTRL_P;
} else if (c == ARROW_DOWN) {
return CTRL_N;
} else if (c == ARROW_LEFT) {
return CTRL_B;
} else if (c == ARROW_RIGHT) {
return CTRL_F;
} else if (c == HOME_CODE) {
return CTRL_A;
} else if (c == END_CODE) {
return CTRL_E;
}
}
}
// handle unicode characters, thanks for a patch from [email protected]
if (c > 128)
// handle unicode characters longer than 2 bytes,
// thanks to [email protected]
c = new InputStreamReader(new ReplayPrefixOneCharInputStream(c, in),
"UTF-8").read();
return c;
}
/**
* No-op for exceptions we want to silently consume.
*/
private void consumeException(Throwable e) {
}
public boolean isSupported() {
return true;
}
public boolean getEcho() {
return false;
}
/**
* Returns the value of "stty size" width param.
*
* <strong>Note</strong>: this method caches the value from the
* first time it is called in order to increase speed, which means
* that changing to size of the terminal will not be reflected
* in the console.
*/
public int getTerminalWidth() {
int val = -1;
try {
val = getTerminalProperty("columns");
} catch (Exception e) {
}
if (val == -1) {
val = 80;
}
return val;
}
/**
* Returns the value of "stty size" height param.
*
* <strong>Note</strong>: this method caches the value from the
* first time it is called in order to increase speed, which means
* that changing to size of the terminal will not be reflected
* in the console.
*/
public int getTerminalHeight() {
int val = -1;
try {
val = getTerminalProperty("rows");
} catch (Exception e) {
}
if (val == -1) {
val = 24;
}
return val;
}
private static int getTerminalProperty(String prop)
throws IOException, InterruptedException {
// need to be able handle both output formats:
// speed 9600 baud; 24 rows; 140 columns;
// and:
// speed 38400 baud; rows = 49; columns = 111; ypixels = 0; xpixels = 0;
String props = stty("-a");
for (StringTokenizer tok = new StringTokenizer(props, ";\n");
tok.hasMoreTokens();) {
String str = tok.nextToken().trim();
if (str.startsWith(prop)) {
int index = str.lastIndexOf(" ");
return Integer.parseInt(str.substring(index).trim());
} else if (str.endsWith(prop)) {
int index = str.indexOf(" ");
return Integer.parseInt(str.substring(0, index).trim());
}
}
return -1;
}
/**
* Execute the stty command with the specified arguments
* against the current active terminal.
*/
private static String stty(final String args)
throws IOException, InterruptedException {
return exec("stty " + args + " < /dev/tty").trim();
}
/**
* Execute the specified command and return the output
* (both stdout and stderr).
*/
private static String exec(final String cmd)
throws IOException, InterruptedException {
return exec(new String[] {
"sh",
"-c",
cmd
});
}
/**
* Execute the specified command and return the output
* (both stdout and stderr).
*/
private static String exec(final String[] cmd)
throws IOException, InterruptedException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
Process p = Runtime.getRuntime().exec(cmd);
int c;
InputStream in;
in = p.getInputStream();
while ((c = in.read()) != -1) {
bout.write(c);
}
in = p.getErrorStream();
while ((c = in.read()) != -1) {
bout.write(c);
}
p.waitFor();
String result = new String(bout.toByteArray());
return result;
}
/**
* The command to use to set the terminal options. Defaults
* to "stty", or the value of the system property "jline.sttyCommand".
*/
public static void setSttyCommand(String cmd) {
sttyCommand = cmd;
}
/**
* The command to use to set the terminal options. Defaults
* to "stty", or the value of the system property "jline.sttyCommand".
*/
public static String getSttyCommand() {
return sttyCommand;
}
public synchronized boolean isEchoEnabled() {
return echoEnabled;
}
public synchronized void enableEcho() {
try {
stty("echo");
echoEnabled = true;
} catch (Exception e) {
consumeException(e);
}
}
public synchronized void disableEcho() {
try {
stty("-echo");
echoEnabled = false;
} catch (Exception e) {
consumeException(e);
}
}
/**
* This is awkward and inefficient, but probably the minimal way to add
* UTF-8 support to JLine
*
* @author <a href="mailto:[email protected]">Marc Herbert</a>
*/
static class ReplayPrefixOneCharInputStream extends InputStream {
final byte firstByte;
final int byteLength;
final InputStream wrappedStream;
int byteRead;
public ReplayPrefixOneCharInputStream(int recorded, InputStream wrapped)
throws IOException {
this.wrappedStream = wrapped;
this.byteRead = 0;
this.firstByte = (byte) recorded;
// 110yyyyy 10zzzzzz
if ((firstByte & (byte) 0xE0) == (byte) 0xC0)
this.byteLength = 2;
// 1110xxxx 10yyyyyy 10zzzzzz
else if ((firstByte & (byte) 0xF0) == (byte) 0xE0)
this.byteLength = 3;
// 11110www 10xxxxxx 10yyyyyy 10zzzzzz
else if ((firstByte & (byte) 0xF8) == (byte) 0xF0)
this.byteLength = 4;
else
throw new IOException("invalid UTF-8 first byte: " + firstByte);
}
public int read() throws IOException {
if (available() == 0)
return -1;
byteRead++;
if (byteRead == 1)
return firstByte;
return wrappedStream.read();
}
/**
* InputStreamReader is greedy and will try to read bytes in advance. We
* do NOT want this to happen since we use a temporary/"losing bytes"
* InputStreamReader above, that's why we hide the real
* wrappedStream.available() here.
*/
public int available() {
return byteLength - byteRead;
}
}
}
| src/main/java/jline/UnixTerminal.java | /*
* Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*/
package jline;
import java.io.*;
import java.util.*;
/**
* <p>
* Terminal that is used for unix platforms. Terminal initialization
* is handled by issuing the <em>stty</em> command against the
* <em>/dev/tty</em> file to disable character echoing and enable
* character input. All known unix systems (including
* Linux and Macintosh OS X) support the <em>stty</em>), so this
* implementation should work for an reasonable POSIX system.
* </p>
*
* @author <a href="mailto:[email protected]">Marc Prud'hommeaux</a>
* @author Updates <a href="mailto:[email protected]">Dale Kemp</a> 2005-12-03
*/
public class UnixTerminal extends Terminal {
public static final short ARROW_START = 27;
public static final short ARROW_PREFIX = 91;
public static final short ARROW_LEFT = 68;
public static final short ARROW_RIGHT = 67;
public static final short ARROW_UP = 65;
public static final short ARROW_DOWN = 66;
public static final short O_PREFIX = 79;
public static final short HOME_CODE = 72;
public static final short END_CODE = 70;
private Map terminfo;
private boolean echoEnabled;
private String ttyConfig;
private static String sttyCommand =
System.getProperty("jline.sttyCommand", "stty");
/**
* Remove line-buffered input by invoking "stty -icanon min 1"
* against the current terminal.
*/
public void initializeTerminal() throws IOException, InterruptedException {
// save the initial tty configuration
ttyConfig = stty("-g");
// sanity check
if ((ttyConfig.length() == 0)
|| ((ttyConfig.indexOf("=") == -1)
&& (ttyConfig.indexOf(":") == -1))) {
throw new IOException("Unrecognized stty code: " + ttyConfig);
}
// set the console to be character-buffered instead of line-buffered
stty("-icanon min 1");
// disable character echoing
stty("-echo");
echoEnabled = false;
// at exit, restore the original tty configuration (for JDK 1.3+)
try {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void start() {
try {
restoreTerminal();
} catch (Exception e) {
consumeException(e);
}
}
});
} catch (AbstractMethodError ame) {
// JDK 1.3+ only method. Bummer.
consumeException(ame);
}
}
/**
* Restore the original terminal configuration, which can be used when
* shutting down the console reader. The ConsoleReader cannot be
* used after calling this method.
*/
public void restoreTerminal() {
if (ttyConfig != null) {
stty(ttyConfig);
ttyConfig = null;
}
resetTerminal();
}
public int readVirtualKey(InputStream in) throws IOException {
int c = readCharacter(in);
// in Unix terminals, arrow keys are represented by
// a sequence of 3 characters. E.g., the up arrow
// key yields 27, 91, 68
if (c == ARROW_START) {
c = readCharacter(in);
if (c == ARROW_PREFIX || c == O_PREFIX) {
c = readCharacter(in);
if (c == ARROW_UP) {
return CTRL_P;
} else if (c == ARROW_DOWN) {
return CTRL_N;
} else if (c == ARROW_LEFT) {
return CTRL_B;
} else if (c == ARROW_RIGHT) {
return CTRL_F;
} else if (c == HOME_CODE) {
return CTRL_A;
} else if (c == END_CODE) {
return CTRL_E;
}
}
}
// handle unicode characters, thanks for a patch from [email protected]
if (c > 128)
// handle unicode characters longer than 2 bytes,
// thanks to [email protected]
c = new InputStreamReader(new ReplayPrefixOneCharInputStream(c, in),
"UTF-8").read();
return c;
}
/**
* No-op for exceptions we want to silently consume.
*/
private void consumeException(Throwable e) {
}
public boolean isSupported() {
return true;
}
public boolean getEcho() {
return false;
}
/**
* Returns the value of "stty size" width param.
*
* <strong>Note</strong>: this method caches the value from the
* first time it is called in order to increase speed, which means
* that changing to size of the terminal will not be reflected
* in the console.
*/
public int getTerminalWidth() {
int val = -1;
try {
val = getTerminalProperty("columns");
} catch (Exception e) {
}
if (val == -1) {
val = 80;
}
return val;
}
/**
* Returns the value of "stty size" height param.
*
* <strong>Note</strong>: this method caches the value from the
* first time it is called in order to increase speed, which means
* that changing to size of the terminal will not be reflected
* in the console.
*/
public int getTerminalHeight() {
int val = -1;
try {
val = getTerminalProperty("rows");
} catch (Exception e) {
}
if (val == -1) {
val = 24;
}
return val;
}
private static int getTerminalProperty(String prop)
throws IOException, InterruptedException {
// need to be able handle both output formats:
// speed 9600 baud; 24 rows; 140 columns;
// and:
// speed 38400 baud; rows = 49; columns = 111; ypixels = 0; xpixels = 0;
String props = stty("-a");
for (StringTokenizer tok = new StringTokenizer(props, ";\n");
tok.hasMoreTokens();) {
String str = tok.nextToken().trim();
if (str.startsWith(prop)) {
int index = str.lastIndexOf(" ");
return Integer.parseInt(str.substring(index).trim());
} else if (str.endsWith(prop)) {
int index = str.indexOf(" ");
return Integer.parseInt(str.substring(0, index).trim());
}
}
return -1;
}
/**
* Execute the stty command with the specified arguments
* against the current active terminal.
*/
private static String stty(final String args)
throws IOException, InterruptedException {
return exec("stty " + args + " < /dev/tty").trim();
}
/**
* Execute the specified command and return the output
* (both stdout and stderr).
*/
private static String exec(final String cmd)
throws IOException, InterruptedException {
return exec(new String[] {
"sh",
"-c",
cmd
});
}
/**
* Execute the specified command and return the output
* (both stdout and stderr).
*/
private static String exec(final String[] cmd)
throws IOException, InterruptedException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
Process p = Runtime.getRuntime().exec(cmd);
int c;
InputStream in;
in = p.getInputStream();
while ((c = in.read()) != -1) {
bout.write(c);
}
in = p.getErrorStream();
while ((c = in.read()) != -1) {
bout.write(c);
}
p.waitFor();
String result = new String(bout.toByteArray());
return result;
}
/**
* The command to use to set the terminal options. Defaults
* to "stty", or the value of the system property "jline.sttyCommand".
*/
public static void setSttyCommand(String cmd) {
sttyCommand = cmd;
}
/**
* The command to use to set the terminal options. Defaults
* to "stty", or the value of the system property "jline.sttyCommand".
*/
public static String getSttyCommand() {
return sttyCommand;
}
public synchronized boolean isEchoEnabled() {
return echoEnabled;
}
public synchronized void enableEcho() {
try {
stty("echo");
echoEnabled = true;
} catch (Exception e) {
consumeException(e);
}
}
public synchronized void disableEcho() {
try {
stty("-echo");
echoEnabled = false;
} catch (Exception e) {
consumeException(e);
}
}
/**
* This is awkward and inefficient, but probably the minimal way to add
* UTF-8 support to JLine
*
* @author <a href="mailto:[email protected]">Marc Herbert</a>
*/
static class ReplayPrefixOneCharInputStream extends InputStream {
final byte firstByte;
final int byteLength;
final InputStream wrappedStream;
int byteRead;
public ReplayPrefixOneCharInputStream(int recorded, InputStream wrapped)
throws IOException {
this.wrappedStream = wrapped;
this.byteRead = 0;
this.firstByte = (byte) recorded;
// 110yyyyy 10zzzzzz
if ((firstByte & (byte) 0xE0) == (byte) 0xC0)
this.byteLength = 2;
// 1110xxxx 10yyyyyy 10zzzzzz
else if ((firstByte & (byte) 0xF0) == (byte) 0xE0)
this.byteLength = 3;
// 11110www 10xxxxxx 10yyyyyy 10zzzzzz
else if ((firstByte & (byte) 0xF8) == (byte) 0xF0)
this.byteLength = 4;
else
throw new IOException("invalid UTF-8 first byte: " + firstByte);
}
public int read() throws IOException {
if (available() == 0)
return -1;
byteRead++;
if (byteRead == 1)
return firstByte;
return wrappedStream.read();
}
/**
* InputStreamReader is greedy and will try to read bytes in advance. We
* do NOT want this to happen since we use a temporary/"losing bytes"
* InputStreamReader above, that's why we hide the real
* wrappedStream.available() here.
*/
public int available() {
return byteLength - byteRead;
}
}
}
| Added restoreTerminal invocation that will allow people to use System.in after a ConsoleReader has been created (issue #1604273).
| src/main/java/jline/UnixTerminal.java | Added restoreTerminal invocation that will allow people to use System.in after a ConsoleReader has been created (issue #1604273). |
|
Java | mit | b3313b9aa5c5d1b3fb4c095504c1224c8027db96 | 0 | trywildcard/pair-java,trywildcard/pair-java | package com.wildcard.pair.model.product;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wildcard.pair.model.product.Offer;
import com.wildcard.pair.model.product.OfferBuilder;
import com.wildcard.pair.model.product.ProductCard;
import com.wildcard.pair.model.product.ProductCardBuilder;
import com.wildcard.pair.util.DummyOffer;
import com.wildcard.pair.util.DummyProduct;
import com.wildcard.pair.util.TestUtil;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* Test using the productCardBuilder to build a product card from values in code stubs.
*/
public class ProductCardBuilderTest {
ObjectMapper mapper = TestUtil.getObjectMapper();
private static DummyOffer dummyOffer;
private static DummyProduct dummyProduct;
@BeforeClass
public static void prepare() throws MalformedURLException, ParseException {
dummyOffer = new DummyOffer();
dummyProduct = new DummyProduct();
}
private void testMinimalCardAttributes(ProductCard card){
Assert.assertEquals("Name should match", dummyProduct.name, card.getName());
Assert.assertEquals("Web url should match", dummyProduct.webUrl, card.getWebUrl());
Assert.assertEquals("Price should match", dummyOffer.price.getPrice(), card.getOffers().get(0).getPrice().getPrice());
}
private ProductCard buildMinimalProductCard(){
List<Offer> offers = new ArrayList<Offer>();
Offer offer = new OfferBuilder(dummyOffer.price).build();
offers.add(offer);
ProductCardBuilder cardBuilder = new ProductCardBuilder(dummyProduct.name, offers, dummyProduct.webUrl);
return cardBuilder.build();
}
@Test
public void testMinimalProductCard() throws MalformedURLException, JsonProcessingException{
ProductCard card = buildMinimalProductCard();
testMinimalCardAttributes(card);
}
@Test
public void testMinimalProductWithMinimalConstructor(){
ProductCard card = new ProductCardBuilder(dummyProduct.name, dummyOffer.price.getPrice(), dummyProduct.webUrl).build();
testMinimalCardAttributes(card);
}
private void testExtensiveCardAttributes(ProductCard card){
testMinimalCardAttributes(card);
Assert.assertEquals("Image url should match", dummyProduct.imgUrl, card.getImages().get(0));
Assert.assertEquals("Description should match", dummyProduct.description, card.getDescription());
Assert.assertEquals("Brand name should match", dummyProduct.brand, card.getBrand());
Assert.assertEquals("Merchant should match", dummyProduct.merchant, card.getMerchant());
Assert.assertEquals("Colors should match", dummyProduct.colors, card.getColors());
List<URL> combinedImages = new ArrayList<URL>();
combinedImages.add(dummyProduct.imgUrl);
for (URL img : dummyProduct.images){
combinedImages.add(img);
}
Assert.assertEquals("Images should match", combinedImages, card.getImages());
Assert.assertEquals("Rating should match", dummyProduct.rating, card.getRating(), TestUtil.FLOAT_EXACT_COMPARISON_EPSILON);
Assert.assertEquals("Rating scale should match", dummyProduct.ratingScale, card.getRatingScale(), TestUtil.FLOAT_EXACT_COMPARISON_EPSILON);
Assert.assertEquals("Rating count should match", dummyProduct.ratingCount, card.getRatingCount());
Assert.assertEquals("Related Items should match", dummyProduct.relatedItems, card.getRelatedItems());
Assert.assertEquals("Sizes should match", dummyProduct.sizes, card.getSizes());
Assert.assertEquals("Options should match", dummyProduct.options, card.getOptions());
Assert.assertEquals("Model should match", dummyProduct.model, card.getModel());
Assert.assertEquals("App link ios should match", dummyProduct.appLinkIos, card.getAppLinkIos());
Assert.assertEquals("App link Android should match", dummyProduct.appLinkAndroid, card.getAppLinkAndroid());
}
private Offer buildExtensiveOffer(){
OfferBuilder builder = new OfferBuilder(dummyOffer.price);
builder.originalPrice(dummyOffer.originalPrice);
builder.description(dummyOffer.description);
builder.availability(dummyOffer.availability);
builder.shippingCost(dummyOffer.shippingCost);
builder.quantity(dummyOffer.quantity);
builder.saleStartDate(dummyOffer.saleStartDate);
builder.saleEndDate(dummyOffer.saleEndDate);
builder.expirationDate(dummyOffer.expirationDate);
builder.geographicAvailability(dummyOffer.geographicAvailability);
builder.gender(dummyOffer.gender);
builder.weight(dummyOffer.weight);
builder.weightUnits(dummyOffer.weightUnits);
builder.offerId(dummyOffer.offerId);
return builder.build();
}
private ProductCard buildExtensiveProductCard(){
List<Offer> offers = new ArrayList<Offer>();
Offer offer = buildExtensiveOffer();
offers.add(offer);
ProductCardBuilder builder = new ProductCardBuilder(dummyProduct.name, offers, dummyProduct.webUrl);
builder.productId(dummyProduct.productId);
builder.description(dummyProduct.description);
builder.image(dummyProduct.imgUrl);
builder.brand(dummyProduct.brand);
builder.merchant(dummyProduct.merchant);
builder.colors(dummyProduct.colors);
builder.images(dummyProduct.images);
builder.rating(dummyProduct.rating);
builder.ratingScale(dummyProduct.ratingScale);
builder.ratingCount(dummyProduct.ratingCount);
builder.relatedItems(dummyProduct.relatedItems);
builder.referencedItems(dummyProduct.referencedItems);
builder.sizes(dummyProduct.sizes);
builder.options(dummyProduct.options);
builder.model(dummyProduct.model);
builder.appLinkIos(dummyProduct.appLinkIos);
builder.appLinkAndroid(dummyProduct.appLinkAndroid);
return builder.build();
}
@Test
public void testExtensiveProductCard() throws IOException, URISyntaxException{
ProductCard card = buildExtensiveProductCard();
testExtensiveCardAttributes(card);
}
@Test
public void testExtensiveWriteAsJsonMethod() throws JsonParseException, JsonMappingException, IOException{
String inputString = TestUtil.readResourceAsString("example_product_card.json");
ProductCard fixtureCard = mapper.readValue(inputString, ProductCard.class);
ProductCard generatedCard = buildExtensiveProductCard();
Assert.assertEquals(mapper.writeValueAsString(fixtureCard), generatedCard.writeAsJsonString());
}
@Test
public void testMinimalWriteAsJsonMethod() throws JsonParseException, JsonMappingException, IOException{
String inputString = TestUtil.readResourceAsString("example_minimal_product_card.json");
ProductCard fixtureCard = mapper.readValue(inputString, ProductCard.class);
ProductCard generatedCard = buildMinimalProductCard();
Assert.assertEquals(mapper.writeValueAsString(fixtureCard), generatedCard.writeAsJsonString());
}
// TODO: test validation
}
| src/test/java/com/wildcard/pair/model/product/ProductCardBuilderTest.java | package com.wildcard.pair.model.product;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wildcard.pair.model.product.Offer;
import com.wildcard.pair.model.product.OfferBuilder;
import com.wildcard.pair.model.product.ProductCard;
import com.wildcard.pair.model.product.ProductCardBuilder;
import com.wildcard.pair.util.DummyOffer;
import com.wildcard.pair.util.DummyProduct;
import com.wildcard.pair.util.TestUtil;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* Test using the productCardBuilder to build a product card from values in code stubs.
*/
public class ProductCardBuilderTest {
ObjectMapper mapper = TestUtil.getObjectMapper();
private static DummyOffer dummyOffer;
private static DummyProduct dummyProduct;
@BeforeClass
public static void prepare() throws MalformedURLException, ParseException {
dummyOffer = new DummyOffer();
dummyProduct = new DummyProduct();
}
private void testMinimalCardAttributes(ProductCard card){
Assert.assertEquals("Name should match", dummyProduct.name, card.getName());
Assert.assertEquals("Web url should match", dummyProduct.webUrl, card.getWebUrl());
Assert.assertEquals("Price should match", dummyOffer.price.getPrice(), card.getOffers().get(0).getPrice().getPrice());
}
private ProductCard buildMinimalProductCard(){
List<Offer> offers = new ArrayList<Offer>();
Offer offer = new OfferBuilder(dummyOffer.price).build();
offers.add(offer);
ProductCardBuilder cardBuilder = new ProductCardBuilder(dummyProduct.name, offers, dummyProduct.webUrl);
return cardBuilder.build();
}
@Test
public void testMinimalProductCard() throws MalformedURLException, JsonProcessingException{
ProductCard card = buildMinimalProductCard();
testMinimalCardAttributes(card);
assertEquals(1,getClass().getPackage());
}
@Test
public void testMinimalProductWithMinimalConstructor(){
ProductCard card = new ProductCardBuilder(dummyProduct.name, dummyOffer.price.getPrice(), dummyProduct.webUrl).build();
testMinimalCardAttributes(card);
}
private void testExtensiveCardAttributes(ProductCard card){
testMinimalCardAttributes(card);
Assert.assertEquals("Image url should match", dummyProduct.imgUrl, card.getImages().get(0));
Assert.assertEquals("Description should match", dummyProduct.description, card.getDescription());
Assert.assertEquals("Brand name should match", dummyProduct.brand, card.getBrand());
Assert.assertEquals("Merchant should match", dummyProduct.merchant, card.getMerchant());
Assert.assertEquals("Colors should match", dummyProduct.colors, card.getColors());
List<URL> combinedImages = new ArrayList<URL>();
combinedImages.add(dummyProduct.imgUrl);
for (URL img : dummyProduct.images){
combinedImages.add(img);
}
Assert.assertEquals("Images should match", combinedImages, card.getImages());
Assert.assertEquals("Rating should match", dummyProduct.rating, card.getRating(), TestUtil.FLOAT_EXACT_COMPARISON_EPSILON);
Assert.assertEquals("Rating scale should match", dummyProduct.ratingScale, card.getRatingScale(), TestUtil.FLOAT_EXACT_COMPARISON_EPSILON);
Assert.assertEquals("Rating count should match", dummyProduct.ratingCount, card.getRatingCount());
Assert.assertEquals("Related Items should match", dummyProduct.relatedItems, card.getRelatedItems());
Assert.assertEquals("Sizes should match", dummyProduct.sizes, card.getSizes());
Assert.assertEquals("Options should match", dummyProduct.options, card.getOptions());
Assert.assertEquals("Model should match", dummyProduct.model, card.getModel());
Assert.assertEquals("App link ios should match", dummyProduct.appLinkIos, card.getAppLinkIos());
Assert.assertEquals("App link Android should match", dummyProduct.appLinkAndroid, card.getAppLinkAndroid());
}
private Offer buildExtensiveOffer(){
OfferBuilder builder = new OfferBuilder(dummyOffer.price);
builder.originalPrice(dummyOffer.originalPrice);
builder.description(dummyOffer.description);
builder.availability(dummyOffer.availability);
builder.shippingCost(dummyOffer.shippingCost);
builder.quantity(dummyOffer.quantity);
builder.saleStartDate(dummyOffer.saleStartDate);
builder.saleEndDate(dummyOffer.saleEndDate);
builder.expirationDate(dummyOffer.expirationDate);
builder.geographicAvailability(dummyOffer.geographicAvailability);
builder.gender(dummyOffer.gender);
builder.weight(dummyOffer.weight);
builder.weightUnits(dummyOffer.weightUnits);
builder.offerId(dummyOffer.offerId);
return builder.build();
}
private ProductCard buildExtensiveProductCard(){
List<Offer> offers = new ArrayList<Offer>();
Offer offer = buildExtensiveOffer();
offers.add(offer);
ProductCardBuilder builder = new ProductCardBuilder(dummyProduct.name, offers, dummyProduct.webUrl);
builder.productId(dummyProduct.productId);
builder.description(dummyProduct.description);
builder.image(dummyProduct.imgUrl);
builder.brand(dummyProduct.brand);
builder.merchant(dummyProduct.merchant);
builder.colors(dummyProduct.colors);
builder.images(dummyProduct.images);
builder.rating(dummyProduct.rating);
builder.ratingScale(dummyProduct.ratingScale);
builder.ratingCount(dummyProduct.ratingCount);
builder.relatedItems(dummyProduct.relatedItems);
builder.referencedItems(dummyProduct.referencedItems);
builder.sizes(dummyProduct.sizes);
builder.options(dummyProduct.options);
builder.model(dummyProduct.model);
builder.appLinkIos(dummyProduct.appLinkIos);
builder.appLinkAndroid(dummyProduct.appLinkAndroid);
return builder.build();
}
@Test
public void testExtensiveProductCard() throws IOException, URISyntaxException{
ProductCard card = buildExtensiveProductCard();
testExtensiveCardAttributes(card);
}
@Test
public void testExtensiveWriteAsJsonMethod() throws JsonParseException, JsonMappingException, IOException{
String inputString = TestUtil.readResourceAsString("example_product_card.json");
ProductCard fixtureCard = mapper.readValue(inputString, ProductCard.class);
ProductCard generatedCard = buildExtensiveProductCard();
Assert.assertEquals(mapper.writeValueAsString(fixtureCard), generatedCard.writeAsJsonString());
}
@Test
public void testMinimalWriteAsJsonMethod() throws JsonParseException, JsonMappingException, IOException{
String inputString = TestUtil.readResourceAsString("example_minimal_product_card.json");
ProductCard fixtureCard = mapper.readValue(inputString, ProductCard.class);
ProductCard generatedCard = buildMinimalProductCard();
Assert.assertEquals(mapper.writeValueAsString(fixtureCard), generatedCard.writeAsJsonString());
}
// TODO: test validation
}
| Revert "remove mondoid from card_preview class"
This reverts commit 84008f11ad8f33d4ed491b79ddd1f42e67f5a8bd.
| src/test/java/com/wildcard/pair/model/product/ProductCardBuilderTest.java | Revert "remove mondoid from card_preview class" |
|
Java | mit | bac47b94c51437e6430d0131e934792c798ad792 | 0 | sonork/spongycastle,savichris/spongycastle,isghe/bc-java,bcgit/bc-java,Skywalker-11/spongycastle,open-keychain/spongycastle,Skywalker-11/spongycastle,isghe/bc-java,bcgit/bc-java,sonork/spongycastle,sergeypayu/bc-java,sonork/spongycastle,savichris/spongycastle,FAU-Inf2/spongycastle,sergeypayu/bc-java,sergeypayu/bc-java,FAU-Inf2/spongycastle,savichris/spongycastle,onessimofalconi/bc-java,lesstif/spongycastle,FAU-Inf2/spongycastle,onessimofalconi/bc-java,lesstif/spongycastle,lesstif/spongycastle,open-keychain/spongycastle,open-keychain/spongycastle,onessimofalconi/bc-java,Skywalker-11/spongycastle,isghe/bc-java,bcgit/bc-java | package org.bouncycastle.crypto.kems;
import java.math.BigInteger;
import java.security.SecureRandom;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DerivationFunction;
import org.bouncycastle.crypto.KeyEncapsulation;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.KDFParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECMultiplier;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.math.ec.FixedPointCombMultiplier;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.BigIntegers;
/**
* The ECIES Key Encapsulation Mechanism (ECIES-KEM) from ISO 18033-2.
*/
public class ECIESKeyEncapsulation
implements KeyEncapsulation
{
private static final BigInteger ONE = BigInteger.valueOf(1);
private DerivationFunction kdf;
private SecureRandom rnd;
private ECKeyParameters key;
private boolean CofactorMode;
private boolean OldCofactorMode;
private boolean SingleHashMode;
/**
* Set up the ECIES-KEM.
*
* @param kdf the key derivation function to be used.
* @param rnd the random source for the session key.
*/
public ECIESKeyEncapsulation(
DerivationFunction kdf,
SecureRandom rnd)
{
this.kdf = kdf;
this.rnd = rnd;
this.CofactorMode = false;
this.OldCofactorMode = false;
this.SingleHashMode = false;
}
/**
* Set up the ECIES-KEM.
*
* @param kdf the key derivation function to be used.
* @param rnd the random source for the session key.
* @param cofactorMode true to use the new cofactor ECDH.
* @param oldCofactorMode true to use the old cofactor ECDH.
* @param singleHashMode true to use single hash mode.
*/
public ECIESKeyEncapsulation(
DerivationFunction kdf,
SecureRandom rnd,
boolean cofactorMode,
boolean oldCofactorMode,
boolean singleHashMode)
{
this.kdf = kdf;
this.rnd = rnd;
// If both cofactorMode and oldCofactorMode are set to true
// then the implementation will use the new cofactor ECDH
this.CofactorMode = cofactorMode;
this.OldCofactorMode = oldCofactorMode;
this.SingleHashMode = singleHashMode;
}
/**
* Initialise the ECIES-KEM.
*
* @param key the recipient's public (for encryption) or private (for decryption) key.
*/
public void init(CipherParameters key)
throws IllegalArgumentException
{
if (!(key instanceof ECKeyParameters))
{
throw new IllegalArgumentException("EC key required");
}
else
{
this.key = (ECKeyParameters)key;
}
}
/**
* Generate and encapsulate a random session key.
*
* @param out the output buffer for the encapsulated key.
* @param outOff the offset for the output buffer.
* @param keyLen the length of the session key.
* @return the random session key.
*/
public CipherParameters encrypt(byte[] out, int outOff, int keyLen)
throws IllegalArgumentException
{
if (!(key instanceof ECPublicKeyParameters))
{
throw new IllegalArgumentException("Public key required for encryption");
}
ECPublicKeyParameters ecPubKey = (ECPublicKeyParameters)key;
ECDomainParameters ecParams = ecPubKey.getParameters();
ECCurve curve = ecParams.getCurve();
BigInteger n = ecParams.getN();
BigInteger h = ecParams.getH();
// Generate the ephemeral key pair
BigInteger r = BigIntegers.createRandomInRange(ONE, n, rnd);
// Compute the static-ephemeral key agreement
BigInteger rPrime = CofactorMode ? r.multiply(h).mod(n) : r;
ECMultiplier basePointMultiplier = createBasePointMultiplier();
ECPoint[] ghTilde = new ECPoint[]{
basePointMultiplier.multiply(ecParams.getG(), r),
ecPubKey.getQ().multiply(rPrime)
};
// NOTE: More efficient than normalizing each individually
curve.normalizeAll(ghTilde);
ECPoint gTilde = ghTilde[0], hTilde = ghTilde[1];
// Encode the ephemeral public key
byte[] C = gTilde.getEncoded(false);
System.arraycopy(C, 0, out, outOff, C.length);
// Encode the shared secret value
byte[] PEH = hTilde.getAffineXCoord().getEncoded();
return deriveKey(keyLen, C, PEH);
}
/**
* Generate and encapsulate a random session key.
*
* @param out the output buffer for the encapsulated key.
* @param keyLen the length of the session key.
* @return the random session key.
*/
public CipherParameters encrypt(byte[] out, int keyLen)
{
return encrypt(out, 0, keyLen);
}
/**
* Decrypt an encapsulated session key.
*
* @param in the input buffer for the encapsulated key.
* @param inOff the offset for the input buffer.
* @param inLen the length of the encapsulated key.
* @param keyLen the length of the session key.
* @return the session key.
*/
public CipherParameters decrypt(byte[] in, int inOff, int inLen, int keyLen)
throws IllegalArgumentException
{
if (!(key instanceof ECPrivateKeyParameters))
{
throw new IllegalArgumentException("Private key required for encryption");
}
ECPrivateKeyParameters ecPrivKey = (ECPrivateKeyParameters)key;
ECDomainParameters ecParams = ecPrivKey.getParameters();
ECCurve curve = ecParams.getCurve();
BigInteger n = ecParams.getN();
BigInteger h = ecParams.getH();
// Decode the ephemeral public key
byte[] C = new byte[inLen];
System.arraycopy(in, inOff, C, 0, inLen);
// NOTE: Decoded points are already normalized (i.e in affine form)
ECPoint gTilde = curve.decodePoint(C);
// Compute the static-ephemeral key agreement
ECPoint gHat = gTilde;
if ((CofactorMode) || (OldCofactorMode))
{
gHat = gHat.multiply(h);
}
BigInteger xHat = ecPrivKey.getD();
if (CofactorMode)
{
xHat = xHat.multiply(h.modInverse(n)).mod(n);
}
ECPoint hTilde = gHat.multiply(xHat).normalize();
// Encode the shared secret value
byte[] PEH = hTilde.getAffineXCoord().getEncoded();
return deriveKey(keyLen, C, PEH);
}
/**
* Decrypt an encapsulated session key.
*
* @param in the input buffer for the encapsulated key.
* @param keyLen the length of the session key.
* @return the session key.
*/
public CipherParameters decrypt(byte[] in, int keyLen)
{
return decrypt(in, 0, in.length, keyLen);
}
protected ECMultiplier createBasePointMultiplier()
{
return new FixedPointCombMultiplier();
}
protected KeyParameter deriveKey(int keyLen, byte[] C, byte[] PEH)
{
byte[] kdfInput = PEH;
if (SingleHashMode)
{
kdfInput = Arrays.concatenate(C, PEH);
Arrays.fill(PEH, (byte)0);
}
try
{
// Initialise the KDF
kdf.init(new KDFParameters(kdfInput, null));
// Generate the secret key
byte[] K = new byte[keyLen];
kdf.generateBytes(K, 0, K.length);
// Return the ciphertext
return new KeyParameter(K);
}
finally
{
Arrays.fill(kdfInput, (byte)0);
}
}
}
| core/src/main/java/org/bouncycastle/crypto/kems/ECIESKeyEncapsulation.java | package org.bouncycastle.crypto.kems;
import java.math.BigInteger;
import java.security.SecureRandom;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DerivationFunction;
import org.bouncycastle.crypto.KeyEncapsulation;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.KDFParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECMultiplier;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.math.ec.FixedPointCombMultiplier;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.BigIntegers;
/**
* The ECIES Key Encapsulation Mechanism (ECIES-KEM) from ISO 18033-2.
*/
public class ECIESKeyEncapsulation
implements KeyEncapsulation
{
private static final BigInteger ONE = BigInteger.valueOf(1);
private DerivationFunction kdf;
private SecureRandom rnd;
private ECKeyParameters key;
private boolean CofactorMode;
private boolean OldCofactorMode;
private boolean SingleHashMode;
/**
* Set up the ECIES-KEM.
*
* @param kdf the key derivation function to be used.
* @param rnd the random source for the session key.
*/
public ECIESKeyEncapsulation(
DerivationFunction kdf,
SecureRandom rnd)
{
this.kdf = kdf;
this.rnd = rnd;
this.CofactorMode = false;
this.OldCofactorMode = false;
this.SingleHashMode = false;
}
/**
* Set up the ECIES-KEM.
*
* @param kdf the key derivation function to be used.
* @param rnd the random source for the session key.
* @param cofactorMode true to use the new cofactor ECDH.
* @param oldCofactorMode true to use the old cofactor ECDH.
* @param singleHashMode true to use single hash mode.
*/
public ECIESKeyEncapsulation(
DerivationFunction kdf,
SecureRandom rnd,
boolean cofactorMode,
boolean oldCofactorMode,
boolean singleHashMode)
{
this.kdf = kdf;
this.rnd = rnd;
// If both cofactorMode and oldCofactorMode are set to true
// then the implementation will use the new cofactor ECDH
this.CofactorMode = cofactorMode;
this.OldCofactorMode = oldCofactorMode;
this.SingleHashMode = singleHashMode;
}
/**
* Initialise the ECIES-KEM.
*
* @param key the recipient's public (for encryption) or private (for decryption) key.
*/
public void init(CipherParameters key)
throws IllegalArgumentException
{
if (!(key instanceof ECKeyParameters))
{
throw new IllegalArgumentException("EC key required");
}
else
{
this.key = (ECKeyParameters)key;
}
}
/**
* Generate and encapsulate a random session key.
*
* @param out the output buffer for the encapsulated key.
* @param outOff the offset for the output buffer.
* @param keyLen the length of the session key.
* @return the random session key.
*/
public CipherParameters encrypt(byte[] out, int outOff, int keyLen)
throws IllegalArgumentException
{
if (!(key instanceof ECPublicKeyParameters))
{
throw new IllegalArgumentException("Public key required for encryption");
}
ECPublicKeyParameters ecPubKey = (ECPublicKeyParameters)key;
ECDomainParameters ecParams = ecPubKey.getParameters();
ECCurve curve = ecParams.getCurve();
BigInteger n = ecParams.getN();
BigInteger h = ecParams.getH();
// Generate the ephemeral key pair
BigInteger r = BigIntegers.createRandomInRange(ONE, n, rnd);
// Compute the static-ephemeral key agreement
BigInteger rPrime = CofactorMode ? r.multiply(h).mod(n) : r;
ECMultiplier basePointMultiplier = createBasePointMultiplier();
ECPoint[] ghTilde = new ECPoint[]{
basePointMultiplier.multiply(ecParams.getG(), r),
ecPubKey.getQ().multiply(rPrime)
};
// NOTE: More efficient than normalizing each individually
curve.normalizeAll(ghTilde);
ECPoint gTilde = ghTilde[0], hTilde = ghTilde[1];
// Encode the ephemeral public key
byte[] C = gTilde.getEncoded();
System.arraycopy(C, 0, out, outOff, C.length);
// Encode the shared secret value
byte[] PEH = hTilde.getAffineXCoord().getEncoded();
// Initialise the KDF
byte[] kdfInput = SingleHashMode ? Arrays.concatenate(C, PEH) : PEH;
kdf.init(new KDFParameters(kdfInput, null));
// Generate the secret key
byte[] K = new byte[keyLen];
kdf.generateBytes(K, 0, K.length);
// Return the ciphertext
return new KeyParameter(K);
}
/**
* Generate and encapsulate a random session key.
*
* @param out the output buffer for the encapsulated key.
* @param keyLen the length of the session key.
* @return the random session key.
*/
public CipherParameters encrypt(byte[] out, int keyLen)
{
return encrypt(out, 0, keyLen);
}
/**
* Decrypt an encapsulated session key.
*
* @param in the input buffer for the encapsulated key.
* @param inOff the offset for the input buffer.
* @param inLen the length of the encapsulated key.
* @param keyLen the length of the session key.
* @return the session key.
*/
public CipherParameters decrypt(byte[] in, int inOff, int inLen, int keyLen)
throws IllegalArgumentException
{
if (!(key instanceof ECPrivateKeyParameters))
{
throw new IllegalArgumentException("Private key required for encryption");
}
ECPrivateKeyParameters ecPrivKey = (ECPrivateKeyParameters)key;
ECDomainParameters ecParams = ecPrivKey.getParameters();
ECCurve curve = ecParams.getCurve();
BigInteger n = ecParams.getN();
BigInteger h = ecParams.getH();
// Decode the ephemeral public key
byte[] C = new byte[inLen];
System.arraycopy(in, inOff, C, 0, inLen);
// NOTE: Decoded points are already normalized (i.e in affine form)
ECPoint gTilde = curve.decodePoint(C);
// Compute the static-ephemeral key agreement
ECPoint gHat = gTilde;
if ((CofactorMode) || (OldCofactorMode))
{
gHat = gHat.multiply(h);
}
BigInteger xHat = ecPrivKey.getD();
if (CofactorMode)
{
xHat = xHat.multiply(h.modInverse(n)).mod(n);
}
ECPoint hTilde = gHat.multiply(xHat).normalize();
// Encode the shared secret value
byte[] PEH = hTilde.getAffineXCoord().getEncoded();
// Initialise the KDF
byte[] kdfInput = SingleHashMode ? Arrays.concatenate(C, PEH) : PEH;
kdf.init(new KDFParameters(kdfInput, null));
// Generate the secret key
byte[] K = new byte[keyLen];
kdf.generateBytes(K, 0, K.length);
return new KeyParameter(K);
}
/**
* Decrypt an encapsulated session key.
*
* @param in the input buffer for the encapsulated key.
* @param keyLen the length of the session key.
* @return the session key.
*/
public CipherParameters decrypt(byte[] in, int keyLen)
{
return decrypt(in, 0, in.length, keyLen);
}
protected ECMultiplier createBasePointMultiplier()
{
return new FixedPointCombMultiplier();
}
}
| Clear the shared secret after use
Explicitly select uncmopressed point format | core/src/main/java/org/bouncycastle/crypto/kems/ECIESKeyEncapsulation.java | Clear the shared secret after use Explicitly select uncmopressed point format |
|
Java | mit | 8fbcd4f492d1577b330a2f9c0c4718e43bf2b01c | 0 | epam/NGB,epam/NGB,epam/NGB,epam/NGB | /*
* MIT License
*
* Copyright (c) 2016 EPAM Systems
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.epam.catgenome.manager.dataitem;
import static com.epam.catgenome.component.MessageHelper.getMessage;
import static com.epam.catgenome.constant.MessagesConstants.ERROR_BIO_ID_NOT_FOUND;
import static com.epam.catgenome.constant.MessagesConstants.ERROR_UNSUPPORTED_FILE_FORMAT;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.epam.catgenome.entity.BiologicalDataItemFormat;
import com.epam.catgenome.entity.BiologicalDataItemResourceType;
import com.epam.catgenome.manager.wig.FacadeWigManager;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import com.epam.catgenome.dao.BiologicalDataItemDao;
import com.epam.catgenome.entity.BiologicalDataItem;
import com.epam.catgenome.manager.bam.BamManager;
import com.epam.catgenome.manager.bed.BedManager;
import com.epam.catgenome.manager.gene.GffManager;
import com.epam.catgenome.manager.maf.MafManager;
import com.epam.catgenome.manager.seg.SegManager;
import com.epam.catgenome.manager.vcf.VcfManager;
/**
* {@code DataItemManager} represents a service class designed to encapsulate all business
* logic operations required to manage data common to all types of files registered on the server.
*/
@Service
public class DataItemManager {
@Autowired
private BiologicalDataItemDao biologicalDataItemDao;
@Autowired
private BamManager bamManager;
@Autowired
private BedManager bedManager;
@Autowired
private VcfManager vcfManager;
@Autowired
private FacadeWigManager facadeWigManager;
@Autowired
private SegManager segManager;
@Autowired
private MafManager mafManager;
@Autowired
private GffManager geneManager;
/**
* Method finds all files registered in the system by an input search query
* @param name to find
* @param strict if true a strict, case sensitive search is performed,
* otherwise a substring, case insensitive search is performed
* @return list of found files
*/
@Transactional(propagation = Propagation.SUPPORTS)
public List<BiologicalDataItem> findFilesByName(final String name, boolean strict) {
if (strict) {
return biologicalDataItemDao.loadFilesByNameStrict(name);
} else {
return biologicalDataItemDao.loadFilesByName(name);
}
}
/**
* Method fins a file registered in the system by BiologicalDataItem ID
* @param id to find
* @return loaded entity
*/
@Transactional(propagation = Propagation.REQUIRED)
public BiologicalDataItem findFileByBioItemId(Long id) {
List<BiologicalDataItem> items = biologicalDataItemDao.loadBiologicalDataItemsByIds(
Collections.singletonList(id));
Assert.notNull(items, getMessage(ERROR_BIO_ID_NOT_FOUND, id));
Assert.isTrue(!items.isEmpty(), getMessage(ERROR_BIO_ID_NOT_FOUND, id));
return items.get(0);
}
/**
* Method defines the format of a file, specified by biological data item ID, and uses the
* corresponding to the format manager to delete it. Reference file must be deleted using
* corresponding API and are not supported in this method.
* @param id biological data item ID
* @return deleted file
*/
@Transactional(propagation = Propagation.REQUIRED)
public BiologicalDataItem deleteFileByBioItemId(Long id) throws IOException {
List<BiologicalDataItem> items = biologicalDataItemDao.loadBiologicalDataItemsByIds(
Collections.singletonList(id));
Assert.notNull(items, getMessage(ERROR_BIO_ID_NOT_FOUND, id));
Assert.isTrue(!items.isEmpty(), getMessage(ERROR_BIO_ID_NOT_FOUND, id));
final BiologicalDataItem item = items.get(0);
final Long itemId = item.getId();
if (item.getId() == null || item.getId() == 0) {
biologicalDataItemDao.deleteBiologicalDataItem(id);
return item;
}
switch (item.getFormat()) {
case BAM:
bamManager.unregisterBamFile(itemId);
break;
case BED:
bedManager.unregisterBedFile(itemId);
break;
case GENE:
geneManager.unregisterGeneFile(itemId);
break;
case WIG:
facadeWigManager.unregisterWigFile(itemId);
break;
case SEG:
segManager.unregisterSegFile(itemId);
break;
case MAF:
mafManager.unregisterMafFile(itemId);
break;
case VCF:
vcfManager.unregisterVcfFile(itemId);
break;
default:
throw new IllegalArgumentException(getMessage(ERROR_UNSUPPORTED_FILE_FORMAT,
item.getFormat()));
}
return item;
}
public Map<String, BiologicalDataItemFormat> getFormats() {
return bedManager.getFormats().stream()
.map(e -> Pair.of(e, BiologicalDataItemFormat.BED))
.collect(Collectors.toMap(Pair::getKey, Pair::getValue));
}
public InputStream loadFileContent(final BiologicalDataItem biologicalDataItem) throws IOException {
final String dataItemPath = biologicalDataItem.getPath();
if (BiologicalDataItemResourceType.FILE.equals(biologicalDataItem.getType())) {
Assert.state(Files.exists(Paths.get(dataItemPath)),
getMessage(ERROR_BIO_ID_NOT_FOUND, biologicalDataItem.getId()));
return Files.newInputStream(Paths.get(dataItemPath));
}
throw new UnsupportedOperationException("Download available for local data only");
}
}
| server/catgenome/src/main/java/com/epam/catgenome/manager/dataitem/DataItemManager.java | /*
* MIT License
*
* Copyright (c) 2016 EPAM Systems
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.epam.catgenome.manager.dataitem;
import static com.epam.catgenome.component.MessageHelper.getMessage;
import static com.epam.catgenome.constant.MessagesConstants.ERROR_BIO_ID_NOT_FOUND;
import static com.epam.catgenome.constant.MessagesConstants.ERROR_UNSUPPORTED_FILE_FORMAT;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.epam.catgenome.entity.BiologicalDataItemFormat;
import com.epam.catgenome.entity.BiologicalDataItemResourceType;
import com.epam.catgenome.manager.wig.FacadeWigManager;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import com.epam.catgenome.dao.BiologicalDataItemDao;
import com.epam.catgenome.entity.BiologicalDataItem;
import com.epam.catgenome.manager.bam.BamManager;
import com.epam.catgenome.manager.bed.BedManager;
import com.epam.catgenome.manager.gene.GffManager;
import com.epam.catgenome.manager.maf.MafManager;
import com.epam.catgenome.manager.seg.SegManager;
import com.epam.catgenome.manager.vcf.VcfManager;
/**
* {@code DataItemManager} represents a service class designed to encapsulate all business
* logic operations required to manage data common to all types of files registered on the server.
*/
@Service
public class DataItemManager {
@Autowired
private BiologicalDataItemDao biologicalDataItemDao;
@Autowired
private BamManager bamManager;
@Autowired
private BedManager bedManager;
@Autowired
private VcfManager vcfManager;
@Autowired
private FacadeWigManager facadeWigManager;
@Autowired
private SegManager segManager;
@Autowired
private MafManager mafManager;
@Autowired
private GffManager geneManager;
/**
* Method finds all files registered in the system by an input search query
* @param name to find
* @param strict if true a strict, case sensitive search is performed,
* otherwise a substring, case insensitive search is performed
* @return list of found files
*/
@Transactional(propagation = Propagation.SUPPORTS)
public List<BiologicalDataItem> findFilesByName(final String name, boolean strict) {
if (strict) {
return biologicalDataItemDao.loadFilesByNameStrict(name);
} else {
return biologicalDataItemDao.loadFilesByName(name);
}
}
/**
* Method fins a file registered in the system by BiologicalDataItem ID
* @param id to find
* @return loaded entity
*/
@Transactional(propagation = Propagation.REQUIRED)
public BiologicalDataItem findFileByBioItemId(Long id) {
List<BiologicalDataItem> items = biologicalDataItemDao.loadBiologicalDataItemsByIds(
Collections.singletonList(id));
Assert.notNull(items, getMessage(ERROR_BIO_ID_NOT_FOUND, id));
Assert.isTrue(!items.isEmpty(), getMessage(ERROR_BIO_ID_NOT_FOUND, id));
return items.get(0);
}
/**
* Method defines the format of a file, specified by biological data item ID, and uses the
* corresponding to the format manager to delete it. Reference file must be deleted using
* corresponding API and are not supported in this method.
* @param id biological data item ID
* @return deleted file
*/
@Transactional(propagation = Propagation.REQUIRED)
public BiologicalDataItem deleteFileByBioItemId(Long id) throws IOException {
List<BiologicalDataItem> items = biologicalDataItemDao.loadBiologicalDataItemsByIds(
Collections.singletonList(id));
Assert.notNull(items, getMessage(ERROR_BIO_ID_NOT_FOUND, id));
Assert.isTrue(!items.isEmpty(), getMessage(ERROR_BIO_ID_NOT_FOUND, id));
final BiologicalDataItem item = items.get(0);
final Long itemId = item.getId();
if (item.getId() == null || item.getId() == 0) {
biologicalDataItemDao.deleteBiologicalDataItem(id);
return item;
}
switch (item.getFormat()) {
case BAM:
bamManager.unregisterBamFile(itemId);
break;
case BED:
bedManager.unregisterBedFile(itemId);
break;
case GENE:
geneManager.unregisterGeneFile(itemId);
break;
case WIG:
facadeWigManager.unregisterWigFile(itemId);
break;
case SEG:
segManager.unregisterSegFile(itemId);
break;
case MAF:
mafManager.unregisterMafFile(itemId);
break;
case VCF:
vcfManager.unregisterVcfFile(itemId);
break;
default:
throw new IllegalArgumentException(getMessage(ERROR_UNSUPPORTED_FILE_FORMAT,
item.getFormat()));
}
return item;
}
public Map<String, BiologicalDataItemFormat> getFormats() {
return bedManager.getFormats().stream()
.map(e -> Pair.of(e, BiologicalDataItemFormat.BED))
.collect(Collectors.toMap(Pair::getKey, Pair::getValue));
}
public InputStream loadFileContent(final BiologicalDataItem biologicalDataItem) throws IOException {
final String dataItemPath = biologicalDataItem.getPath();
if (BiologicalDataItemResourceType.FILE.equals(biologicalDataItem.getType())) {
return Files.newInputStream(Paths.get(dataItemPath));
}
throw new UnsupportedOperationException("Download available for local data only");
}
}
| Issue #439: Ability to download NGB files from the GUI - API part for local data (file existence check)
| server/catgenome/src/main/java/com/epam/catgenome/manager/dataitem/DataItemManager.java | Issue #439: Ability to download NGB files from the GUI - API part for local data (file existence check) |
|
Java | mit | e15560facb1e229ab189fba165c1f7360b832da8 | 0 | douggie/XChange | package org.knowm.xchange.kraken.service;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.*;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.dto.account.*;
import org.knowm.xchange.kraken.KrakenAdapters;
import org.knowm.xchange.kraken.dto.account.KrakenDepositAddress;
import org.knowm.xchange.kraken.dto.account.KrakenLedger;
import org.knowm.xchange.kraken.dto.account.KrakenTradeBalanceInfo;
import org.knowm.xchange.kraken.dto.account.LedgerType;
import org.knowm.xchange.service.account.AccountService;
import org.knowm.xchange.service.trade.params.DefaultTradeHistoryParamsTimeSpan;
import org.knowm.xchange.service.trade.params.DefaultWithdrawFundsParams;
import org.knowm.xchange.service.trade.params.HistoryParamsFundingType;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencies;
import org.knowm.xchange.service.trade.params.TradeHistoryParamOffset;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan;
import org.knowm.xchange.service.trade.params.WithdrawFundsParams;
public class KrakenAccountService extends KrakenAccountServiceRaw implements AccountService {
/**
* Constructor
*
* @param exchange
*/
public KrakenAccountService(Exchange exchange) {
super(exchange);
}
@Override
public AccountInfo getAccountInfo() throws IOException {
KrakenTradeBalanceInfo krakenTradeBalanceInfo = getKrakenTradeBalance();
Wallet tradingWallet = KrakenAdapters.adaptWallet(getKrakenBalance());
Wallet marginWallet =
Wallet.Builder.from(tradingWallet.getBalances().values())
.id("margin")
.features(EnumSet.of(Wallet.WalletFeature.FUNDING, Wallet.WalletFeature.MARGIN_TRADING))
.maxLeverage(BigDecimal.valueOf(5))
.currentLeverage(
(BigDecimal.ZERO.compareTo(krakenTradeBalanceInfo.getTradeBalance()) == 0)
? BigDecimal.ZERO
: krakenTradeBalanceInfo
.getCostBasis()
.divide(krakenTradeBalanceInfo.getTradeBalance(), MathContext.DECIMAL32))
.build();
return new AccountInfo(
exchange.getExchangeSpecification().getUserName(), tradingWallet, marginWallet);
}
@Override
public String withdrawFunds(Currency currency, BigDecimal amount, String address)
throws IOException {
return withdraw(null, currency.toString(), address, amount).getRefid();
}
@Override
public String withdrawFunds(WithdrawFundsParams params) throws IOException {
if (params instanceof DefaultWithdrawFundsParams) {
DefaultWithdrawFundsParams defaultParams = (DefaultWithdrawFundsParams) params;
return withdrawFunds(
defaultParams.getCurrency(), defaultParams.getAmount(), defaultParams.getAddress());
}
throw new IllegalStateException("Don't know how to withdraw: " + params);
}
@Override
public String requestDepositAddress(Currency currency, String... args) throws IOException {
KrakenDepositAddress[] depositAddresses;
if (Currency.BTC.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Bitcoin");
} else if (Currency.LTC.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Litecoin");
} else if (Currency.ETH.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Ether (Hex)");
} else if (Currency.ZEC.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Zcash (Transparent)");
} else if (Currency.ADA.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "ADA");
} else if (Currency.XMR.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Monero");
} else if (Currency.XRP.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Ripple XRP");
} else if (Currency.XLM.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Stellar XLM");
} else if (Currency.BCH.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Bitcoin Cash");
} else if (Currency.REP.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "REP");
} else if (Currency.USD.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "SynapsePay (US Wire)");
} else if (Currency.XDG.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Dogecoin");
} else if (Currency.MLN.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "MLN");
} else if (Currency.GNO.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "GNO");
} else if (Currency.QTUM.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "QTUM");
} else if (Currency.XTZ.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "XTZ");
} else if (Currency.ATOM.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Cosmos");
} else if (Currency.EOS.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "EOS");
} else if (Currency.DASH.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Dash");
} else {
throw new RuntimeException("Not implemented yet, Kraken works only for BTC and LTC");
}
return KrakenAdapters.adaptKrakenDepositAddress(depositAddresses);
}
@Override
public TradeHistoryParams createFundingHistoryParams() {
return new KrakenFundingHistoryParams(null, null, null, (Currency[]) null);
}
@Override
public List<FundingRecord> getFundingHistory(TradeHistoryParams params) throws IOException {
Date startTime = null;
Date endTime = null;
if (params instanceof TradeHistoryParamsTimeSpan) {
TradeHistoryParamsTimeSpan timeSpanParam = (TradeHistoryParamsTimeSpan) params;
startTime = timeSpanParam.getStartTime();
endTime = timeSpanParam.getEndTime();
}
Long offset = null;
if (params instanceof TradeHistoryParamOffset) {
offset = ((TradeHistoryParamOffset) params).getOffset();
}
Currency[] currencies = null;
if (params instanceof TradeHistoryParamCurrencies) {
final TradeHistoryParamCurrencies currenciesParam = (TradeHistoryParamCurrencies) params;
if (currenciesParam.getCurrencies() != null) {
currencies = currenciesParam.getCurrencies();
}
}
LedgerType ledgerType = null;
if (params instanceof HistoryParamsFundingType) {
final FundingRecord.Type type = ((HistoryParamsFundingType) params).getType();
ledgerType =
type == FundingRecord.Type.DEPOSIT
? LedgerType.DEPOSIT
: type == FundingRecord.Type.WITHDRAWAL ? LedgerType.WITHDRAWAL : null;
}
if (ledgerType == null) {
Map<String, KrakenLedger> ledgerEntries =
getKrakenLedgerInfo(LedgerType.DEPOSIT, startTime, endTime, offset, currencies);
ledgerEntries.putAll(
getKrakenLedgerInfo(LedgerType.WITHDRAWAL, startTime, endTime, offset, currencies));
return KrakenAdapters.adaptFundingHistory(ledgerEntries);
} else {
return KrakenAdapters.adaptFundingHistory(
getKrakenLedgerInfo(ledgerType, startTime, endTime, offset, currencies));
}
}
public static class KrakenFundingHistoryParams extends DefaultTradeHistoryParamsTimeSpan
implements TradeHistoryParamOffset, TradeHistoryParamCurrencies, HistoryParamsFundingType {
private Long offset;
private Currency[] currencies;
private FundingRecord.Type type;
public KrakenFundingHistoryParams(
final Date startTime, final Date endTime, final Long offset, final Currency... currencies) {
super(startTime, endTime);
this.offset = offset;
this.currencies = currencies;
}
@Override
public Long getOffset() {
return offset;
}
@Override
public void setOffset(final Long offset) {
this.offset = offset;
}
@Override
public Currency[] getCurrencies() {
return this.currencies;
}
@Override
public void setCurrencies(Currency[] currencies) {
this.currencies = currencies;
}
@Override
public FundingRecord.Type getType() {
return type;
}
@Override
public void setType(FundingRecord.Type type) {
this.type = type;
}
}
}
| xchange-kraken/src/main/java/org/knowm/xchange/kraken/service/KrakenAccountService.java | package org.knowm.xchange.kraken.service;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.*;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.dto.account.*;
import org.knowm.xchange.kraken.KrakenAdapters;
import org.knowm.xchange.kraken.dto.account.KrakenDepositAddress;
import org.knowm.xchange.kraken.dto.account.KrakenLedger;
import org.knowm.xchange.kraken.dto.account.KrakenTradeBalanceInfo;
import org.knowm.xchange.kraken.dto.account.LedgerType;
import org.knowm.xchange.service.account.AccountService;
import org.knowm.xchange.service.trade.params.DefaultTradeHistoryParamsTimeSpan;
import org.knowm.xchange.service.trade.params.DefaultWithdrawFundsParams;
import org.knowm.xchange.service.trade.params.HistoryParamsFundingType;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencies;
import org.knowm.xchange.service.trade.params.TradeHistoryParamOffset;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan;
import org.knowm.xchange.service.trade.params.WithdrawFundsParams;
public class KrakenAccountService extends KrakenAccountServiceRaw implements AccountService {
/**
* Constructor
*
* @param exchange
*/
public KrakenAccountService(Exchange exchange) {
super(exchange);
}
@Override
public AccountInfo getAccountInfo() throws IOException {
KrakenTradeBalanceInfo krakenTradeBalanceInfo = getKrakenTradeBalance();
Wallet tradingWallet = KrakenAdapters.adaptWallet(getKrakenBalance());
Wallet marginWallet =
Wallet.Builder.from(tradingWallet.getBalances().values())
.id("margin")
.features(EnumSet.of(Wallet.WalletFeature.FUNDING, Wallet.WalletFeature.MARGIN_TRADING))
.maxLeverage(BigDecimal.valueOf(5))
.currentLeverage(
(krakenTradeBalanceInfo.getTradeBalance().equals(BigDecimal.ZERO))
? BigDecimal.ZERO
: krakenTradeBalanceInfo
.getCostBasis()
.divide(krakenTradeBalanceInfo.getTradeBalance(), MathContext.DECIMAL32))
.build();
return new AccountInfo(
exchange.getExchangeSpecification().getUserName(), tradingWallet, marginWallet);
}
@Override
public String withdrawFunds(Currency currency, BigDecimal amount, String address)
throws IOException {
return withdraw(null, currency.toString(), address, amount).getRefid();
}
@Override
public String withdrawFunds(WithdrawFundsParams params) throws IOException {
if (params instanceof DefaultWithdrawFundsParams) {
DefaultWithdrawFundsParams defaultParams = (DefaultWithdrawFundsParams) params;
return withdrawFunds(
defaultParams.getCurrency(), defaultParams.getAmount(), defaultParams.getAddress());
}
throw new IllegalStateException("Don't know how to withdraw: " + params);
}
@Override
public String requestDepositAddress(Currency currency, String... args) throws IOException {
KrakenDepositAddress[] depositAddresses;
if (Currency.BTC.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Bitcoin");
} else if (Currency.LTC.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Litecoin");
} else if (Currency.ETH.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Ether (Hex)");
} else if (Currency.ZEC.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Zcash (Transparent)");
} else if (Currency.ADA.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "ADA");
} else if (Currency.XMR.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Monero");
} else if (Currency.XRP.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Ripple XRP");
} else if (Currency.XLM.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Stellar XLM");
} else if (Currency.BCH.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Bitcoin Cash");
} else if (Currency.REP.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "REP");
} else if (Currency.USD.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "SynapsePay (US Wire)");
} else if (Currency.XDG.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Dogecoin");
} else if (Currency.MLN.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "MLN");
} else if (Currency.GNO.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "GNO");
} else if (Currency.QTUM.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "QTUM");
} else if (Currency.XTZ.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "XTZ");
} else if (Currency.ATOM.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Cosmos");
} else if (Currency.EOS.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "EOS");
} else if (Currency.DASH.equals(currency)) {
depositAddresses = getDepositAddresses(currency.toString(), "Dash");
} else {
throw new RuntimeException("Not implemented yet, Kraken works only for BTC and LTC");
}
return KrakenAdapters.adaptKrakenDepositAddress(depositAddresses);
}
@Override
public TradeHistoryParams createFundingHistoryParams() {
return new KrakenFundingHistoryParams(null, null, null, (Currency[]) null);
}
@Override
public List<FundingRecord> getFundingHistory(TradeHistoryParams params) throws IOException {
Date startTime = null;
Date endTime = null;
if (params instanceof TradeHistoryParamsTimeSpan) {
TradeHistoryParamsTimeSpan timeSpanParam = (TradeHistoryParamsTimeSpan) params;
startTime = timeSpanParam.getStartTime();
endTime = timeSpanParam.getEndTime();
}
Long offset = null;
if (params instanceof TradeHistoryParamOffset) {
offset = ((TradeHistoryParamOffset) params).getOffset();
}
Currency[] currencies = null;
if (params instanceof TradeHistoryParamCurrencies) {
final TradeHistoryParamCurrencies currenciesParam = (TradeHistoryParamCurrencies) params;
if (currenciesParam.getCurrencies() != null) {
currencies = currenciesParam.getCurrencies();
}
}
LedgerType ledgerType = null;
if (params instanceof HistoryParamsFundingType) {
final FundingRecord.Type type = ((HistoryParamsFundingType) params).getType();
ledgerType =
type == FundingRecord.Type.DEPOSIT
? LedgerType.DEPOSIT
: type == FundingRecord.Type.WITHDRAWAL ? LedgerType.WITHDRAWAL : null;
}
if (ledgerType == null) {
Map<String, KrakenLedger> ledgerEntries =
getKrakenLedgerInfo(LedgerType.DEPOSIT, startTime, endTime, offset, currencies);
ledgerEntries.putAll(
getKrakenLedgerInfo(LedgerType.WITHDRAWAL, startTime, endTime, offset, currencies));
return KrakenAdapters.adaptFundingHistory(ledgerEntries);
} else {
return KrakenAdapters.adaptFundingHistory(
getKrakenLedgerInfo(ledgerType, startTime, endTime, offset, currencies));
}
}
public static class KrakenFundingHistoryParams extends DefaultTradeHistoryParamsTimeSpan
implements TradeHistoryParamOffset, TradeHistoryParamCurrencies, HistoryParamsFundingType {
private Long offset;
private Currency[] currencies;
private FundingRecord.Type type;
public KrakenFundingHistoryParams(
final Date startTime, final Date endTime, final Long offset, final Currency... currencies) {
super(startTime, endTime);
this.offset = offset;
this.currencies = currencies;
}
@Override
public Long getOffset() {
return offset;
}
@Override
public void setOffset(final Long offset) {
this.offset = offset;
}
@Override
public Currency[] getCurrencies() {
return this.currencies;
}
@Override
public void setCurrencies(Currency[] currencies) {
this.currencies = currencies;
}
@Override
public FundingRecord.Type getType() {
return type;
}
@Override
public void setType(FundingRecord.Type type) {
this.type = type;
}
}
}
| Replace equals() with compareTo()
BigDecimal::equals takes scale into consideration.
https://github.com/knowm/XChange/issues/3475 | xchange-kraken/src/main/java/org/knowm/xchange/kraken/service/KrakenAccountService.java | Replace equals() with compareTo() |
|
Java | mit | f410bda5678a242a563f7226d857e3660cc1385a | 0 | saintdan/spring-microservices-boilerplate | package com.saintdan.framework.config;
import com.saintdan.framework.config.client.CustomClientDetailsService;
import com.saintdan.framework.config.user.CustomUserDetailsService;
import com.saintdan.framework.constant.ResourceURL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
/**
* OAuth2 server configuration.
*
* @author <a href="http://github.com/saintdan">Liao Yifan</a>
* @date 6/30/15
* @since JDK1.8
*/
@Configuration
public class OAuth2ServerConfiguration {
private static final String RESOURCE_ID = "rest_api";
private static final String WELCOME_URL = "/welcome";
private static final String USER_URL = new String(new StringBuilder(ResourceURL.RESOURCES).append(ResourceURL.USERS));
private static final String ROLE_URL = new String(new StringBuilder(ResourceURL.RESOURCES).append(ResourceURL.ROLES));
private static final String GROUP_URL = new String(new StringBuilder(ResourceURL.RESOURCES).append(ResourceURL.GROUPS));
private static final String RESOURCE_URL = new String(new StringBuilder(ResourceURL.RESOURCES).append(ResourceURL.RESOURCES));
/**
* OAuth2 resource server configuration.
*/
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends
ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources
.resourceId(RESOURCE_ID);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.authorizeRequests()
// User resource
.antMatchers(HttpMethod.GET, USER_URL).hasAnyAuthority("root", "user")
.antMatchers(HttpMethod.POST, USER_URL).hasAnyAuthority("root", "user")
.antMatchers(HttpMethod.PUT, USER_URL).hasAnyAuthority("root", "user")
.antMatchers(HttpMethod.DELETE, USER_URL).hasAnyAuthority("root", "user")
// role resource
.antMatchers(HttpMethod.GET, ROLE_URL).hasAnyAuthority("root", "role")
.antMatchers(HttpMethod.POST, ROLE_URL).hasAnyAuthority("root", "role")
.antMatchers(HttpMethod.PUT, ROLE_URL).hasAnyAuthority("root", "role")
.antMatchers(HttpMethod.DELETE, ROLE_URL).hasAnyAuthority("root", "role")
// group resource
.antMatchers(HttpMethod.GET, GROUP_URL).hasAnyAuthority("root", "group")
.antMatchers(HttpMethod.POST, GROUP_URL).hasAnyAuthority("root", "group")
.antMatchers(HttpMethod.PUT, GROUP_URL).hasAnyAuthority("root", "group")
.antMatchers(HttpMethod.DELETE, GROUP_URL).hasAnyAuthority("root", "group")
// resource resource
.antMatchers(HttpMethod.GET, RESOURCE_URL).hasAnyAuthority("root", "resource")
.antMatchers(HttpMethod.POST, RESOURCE_URL).hasAnyAuthority("root", "resource")
.antMatchers(HttpMethod.PUT, RESOURCE_URL).hasAnyAuthority("root", "resource")
.antMatchers(HttpMethod.DELETE, RESOURCE_URL).hasAnyAuthority("root", "resource")
// welcome resource
.antMatchers(HttpMethod.GET, WELCOME_URL).access("#oauth2.hasScope('read')");
}
}
/**
* OAuth2 authorization server configuration.
*/
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends
AuthorizationServerConfigurerAdapter {
// Token store type.
private TokenStore tokenStore = new InMemoryTokenStore();
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
private CustomUserDetailsService userDetailsService;
// When you use memory client, you can comment the custom client details service.
@Autowired
private CustomClientDetailsService clientDetailsService;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints
.tokenStore(this.tokenStore)
.authenticationManager(this.authenticationManager)
.userDetailsService(userDetailsService);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// Use JDBC client.
// If you have many clients, you can use JDBC client.
clients.withClientDetails(clientDetailsService);
// // Use memory client.
// // Or you can config them here use memory client.
// clients
// .inMemory()
// .withClient("ios_app")
// .authorizedGrantTypes("password", "refresh_token")
// .authorities("USER")
// .scopes("read")
// .resourceIds(RESOURCE_ID)
// .secret("123456");
// // You can add other clients like:
// /*
// clients
// .inMemory()
// .withClient("android_app")
// .authorizedGrantTypes("password", "refresh_token")
// .authorities("USER")
// .scopes("read")
// .resourceIds(RESOURCE_ID)
// .secret("654321");
// */
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(this.tokenStore);
return tokenServices;
}
}
}
| src/main/java/com/saintdan/framework/config/OAuth2ServerConfiguration.java | package com.saintdan.framework.config;
import com.saintdan.framework.config.client.CustomClientDetailsService;
import com.saintdan.framework.config.user.CustomUserDetailsService;
import com.saintdan.framework.constant.ResourceURL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
/**
* OAuth2 server configuration.
*
* @author <a href="http://github.com/saintdan">Liao Yifan</a>
* @date 6/30/15
* @since JDK1.8
*/
@Configuration
public class OAuth2ServerConfiguration {
private static final String RESOURCE_ID = "rest_api";
private static final String WELCOME_URL = "/welcome";
private static final String USER_URL = new String(new StringBuilder(ResourceURL.RESOURCES).append(ResourceURL.USERS));
private static final String ROLE_URL = new String(new StringBuilder(ResourceURL.RESOURCES).append(ResourceURL.ROLES));
private static final String GROUP_URL = new String(new StringBuilder(ResourceURL.RESOURCES).append(ResourceURL.GROUPS));
private static final String RESOURCE_URL = new String(new StringBuilder(ResourceURL.RESOURCES).append(ResourceURL.RESOURCES));
/**
* OAuth2 resource server configuration.
*/
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends
ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources
.resourceId(RESOURCE_ID);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.authorizeRequests()
// User resource
.antMatchers(HttpMethod.GET, USER_URL).hasAnyAuthority("root", "user")
.antMatchers(HttpMethod.POST, USER_URL).hasAnyAuthority("root", "user")
.antMatchers(HttpMethod.PUT, USER_URL).hasAnyAuthority("root", "user")
.antMatchers(HttpMethod.DELETE, USER_URL).hasAnyAuthority("root", "user")
// role resource
.antMatchers(HttpMethod.GET, ROLE_URL).hasAnyAuthority("root", "role")
.antMatchers(HttpMethod.POST, ROLE_URL).hasAnyAuthority("root", "role")
.antMatchers(HttpMethod.PUT, ROLE_URL).hasAnyAuthority("root", "role")
.antMatchers(HttpMethod.DELETE, ROLE_URL).hasAnyAuthority("root", "role")
// group resource
.antMatchers(HttpMethod.GET, GROUP_URL).hasAnyAuthority("root", "group")
.antMatchers(HttpMethod.POST, GROUP_URL).hasAnyAuthority("root", "group")
.antMatchers(HttpMethod.PUT, GROUP_URL).hasAnyAuthority("root", "group")
.antMatchers(HttpMethod.DELETE, GROUP_URL).hasAnyAuthority("root", "group")
// resource resource
.antMatchers(HttpMethod.GET, RESOURCE_URL).hasAnyAuthority("root", "resource")
.antMatchers(HttpMethod.POST, RESOURCE_URL).hasAnyAuthority("root", "resource")
.antMatchers(HttpMethod.PUT, RESOURCE_URL).hasAnyAuthority("root", "resource")
.antMatchers(HttpMethod.DELETE, RESOURCE_URL).hasAnyAuthority("root", "resource")
// welcome resource
.antMatchers(HttpMethod.GET, WELCOME_URL).access("#oauth2.hasScope('read')");
}
}
/**
* OAuth2 authorization server configuration.
*/
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends
AuthorizationServerConfigurerAdapter {
// Token store type.
private TokenStore tokenStore = new InMemoryTokenStore();
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private CustomClientDetailsService clientDetailsService;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints
.tokenStore(this.tokenStore)
.authenticationManager(this.authenticationManager)
.userDetailsService(userDetailsService);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService);
// clients
// .inMemory()
// .withClient("ios_app")
// .authorizedGrantTypes("password", "refresh_token")
// .authorities("USER")
// .scopes("read")
// .resourceIds(RESOURCE_ID)
// .secret("123456");
// You can add other clients like:
/*
clients
.inMemory()
.withClient("android_app")
.authorizedGrantTypes("password", "refresh_token")
.authorities("USER")
.scopes("read")
.resourceIds(RESOURCE_ID)
.secret("654321");
*/
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(this.tokenStore);
return tokenServices;
}
}
}
| Fix client typo error.
| src/main/java/com/saintdan/framework/config/OAuth2ServerConfiguration.java | Fix client typo error. |
|
Java | mit | 5307fd45289449f9225844f42f56c7dcc3cc59e7 | 0 | TechReborn/TechReborn | /*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2018 TechReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package techreborn.client.gui;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fml.client.config.GuiUtils;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard;
import reborncore.api.tile.IUpgradeable;
import reborncore.common.tile.TileLegacyMachineBase;
import techreborn.client.container.builder.BuiltContainer;
import techreborn.client.gui.slot.GuiFluidConfiguration;
import techreborn.client.gui.slot.GuiSlotConfiguration;
import techreborn.client.gui.widget.GuiButtonPowerBar;
import techreborn.init.TRItems;
import techreborn.items.DynamicCell;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Prospector
*/
public class GuiBase extends GuiContainer {
public int xSize = 176;
public int ySize = 176;
public TRBuilder builder = new TRBuilder();
public TileEntity tile;
public BuiltContainer container;
public static SlotConfigType slotConfigType = SlotConfigType.NONE;
public boolean upgrades;
public GuiBase(EntityPlayer player, TileEntity tile, BuiltContainer container) {
super(container);
this.tile = tile;
this.container = container;
slotConfigType = SlotConfigType.NONE;
}
protected void drawSlot(int x, int y, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += guiLeft;
y += guiTop;
}
builder.drawSlot(this, x - 1, y - 1);
}
protected void drawScrapSlot(int x, int y, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += guiLeft;
y += guiTop;
}
builder.drawScrapSlot(this, x - 1, y - 1);
}
protected void drawOutputSlotBar(int x, int y, int count, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += guiLeft;
y += guiTop;
}
builder.drawOutputSlotBar(this, x - 4, y - 4, count);
}
protected void drawArmourSlots(int x, int y, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += guiLeft;
y += guiTop;
}
builder.drawSlot(this, x - 1, y - 1);
builder.drawSlot(this, x - 1, y - 1 + 18);
builder.drawSlot(this, x - 1, y - 1 + 18 + 18);
builder.drawSlot(this, x - 1, y - 1 + 18 + 18 + 18);
}
protected void drawOutputSlot(int x, int y, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += guiLeft;
y += guiTop;
}
builder.drawOutputSlot(this, x - 5, y - 5);
}
protected void drawSelectedStack(int x, int y, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += guiLeft;
y += guiTop;
}
builder.drawSelectedStack(this, x, y);
}
@Override
public void initGui() {
super.initGui();
GuiSlotConfiguration.init(this);
if(getMachine().getTank() != null && getMachine().showTankConfig()){
GuiFluidConfiguration.init(this);
}
}
@Override
protected void drawGuiContainerBackgroundLayer(float p_146976_1_, int mouseX, int mouseY) {
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
builder.drawDefaultBackground(this, guiLeft, guiTop, xSize, ySize);
if (drawPlayerSlots()) {
builder.drawPlayerSlots(this, guiLeft + xSize / 2, guiTop + 93, true);
}
if (tryAddUpgrades() && tile instanceof IUpgradeable) {
IUpgradeable upgradeable = (IUpgradeable) tile;
if (upgradeable.canBeUpgraded()) {
builder.drawUpgrades(this, upgradeable, guiLeft, guiTop);
upgrades = true;
}
}
if(getMachine().hasSlotConfig()){
builder.drawSlotTab(this, guiLeft, guiTop, mouseX, mouseY, upgrades, new ItemStack(TRItems.WRENCH));
}
if(getMachine().showTankConfig()){
builder.drawSlotTab(this, guiLeft, guiTop + 27, mouseX, mouseY, upgrades, DynamicCell.getCellWithFluid(FluidRegistry.LAVA));
}
}
public boolean drawPlayerSlots() {
return true;
}
public boolean tryAddUpgrades() {
return true;
}
@SideOnly(Side.CLIENT)
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
this.buttonList.clear();
drawTitle();
if(slotConfigType == SlotConfigType.ITEMS && getMachine().hasSlotConfig()){
GuiSlotConfiguration.draw(this, mouseX, mouseY);
}
if(slotConfigType == SlotConfigType.FLUIDS && getMachine().showTankConfig()){
GuiFluidConfiguration.draw(this, mouseX, mouseY);
}
int offset = 0;
if(!upgrades){
offset = 80;
}
if (builder.isInRect(guiLeft - 19, guiTop + 92 - offset, 12, 12, mouseX, mouseY) && getMachine().hasSlotConfig()) {
List<String> list = new ArrayList<>();
list.add("Configure slots");
GuiUtils.drawHoveringText(list, mouseX - guiLeft , mouseY - guiTop , width, height, -1, mc.fontRenderer);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1);
}
if (builder.isInRect(guiLeft - 19, guiTop + 92 - offset + 27, 12, 12, mouseX, mouseY) && getMachine().showTankConfig()) {
List<String> list = new ArrayList<>();
list.add("Configure Fluids");
GuiUtils.drawHoveringText(list, mouseX - guiLeft , mouseY - guiTop , width, height, -1, mc.fontRenderer);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1);
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
this.drawDefaultBackground();
super.drawScreen(mouseX, mouseY, partialTicks);
this.renderHoveredToolTip(mouseX, mouseY);
}
protected void drawTitle() {
drawCentredString(I18n.format(tile.getBlockType().getTranslationKey() + ".name"), 6, 4210752, Layer.FOREGROUND);
}
protected void drawCentredString(String string, int y, int colour, Layer layer) {
drawString(string, (xSize / 2 - mc.fontRenderer.getStringWidth(string) / 2), y, colour, layer);
}
protected void drawCentredString(String string, int y, int colour, int modifier, Layer layer) {
drawString(string, (xSize / 2 - (mc.fontRenderer.getStringWidth(string)) / 2) + modifier, y, colour, layer);
}
protected void drawString(String string, int x, int y, int colour, Layer layer) {
int factorX = 0;
int factorY = 0;
if (layer == Layer.BACKGROUND) {
factorX = guiLeft;
factorY = guiTop;
}
mc.fontRenderer.drawString(string, x + factorX, y + factorY, colour);
GlStateManager.color(1, 1, 1, 1);
}
public void addPowerButton(int x, int y, int id, Layer layer) {
int factorX = 0;
int factorY = 0;
if (layer == Layer.BACKGROUND) {
factorX = guiLeft;
factorY = guiTop;
}
buttonList.add(new GuiButtonPowerBar(id, x + factorX, y + factorY, this, layer));
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
if(slotConfigType == SlotConfigType.ITEMS && getMachine().hasSlotConfig()){
if(GuiSlotConfiguration.mouseClicked(mouseX, mouseY, mouseButton, this)){
return;
}
}
if(slotConfigType == SlotConfigType.FLUIDS && getMachine().showTankConfig()){
if(GuiFluidConfiguration.mouseClicked(mouseX, mouseY, mouseButton, this)){
return;
}
}
super.mouseClicked(mouseX, mouseY, mouseButton);
}
@Override
protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) {
if(slotConfigType == SlotConfigType.ITEMS && getMachine().hasSlotConfig()){
GuiSlotConfiguration.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick, this);
}
if(slotConfigType == SlotConfigType.FLUIDS && getMachine().showTankConfig()){
GuiFluidConfiguration.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick, this);
}
super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick);
}
@Override
protected void mouseReleased(int mouseX, int mouseY, int state) {
int offset = 0;
if(!upgrades){
offset = 80;
}
if(isPointInRegion(-26, 84 - offset, 30, 30, mouseX, mouseY) && getMachine().hasSlotConfig()){
if(slotConfigType != SlotConfigType.ITEMS){
slotConfigType = SlotConfigType.ITEMS;
} else {
slotConfigType = SlotConfigType.NONE;
}
if(slotConfigType == SlotConfigType.ITEMS){
GuiSlotConfiguration.reset();
}
}
if(isPointInRegion(-26, 84 - offset + 27, 30, 30, mouseX, mouseY) && getMachine().showTankConfig()){
if(slotConfigType != SlotConfigType.FLUIDS){
slotConfigType = SlotConfigType.FLUIDS;
} else {
slotConfigType = SlotConfigType.NONE;
}
}
if(slotConfigType == SlotConfigType.ITEMS && getMachine().hasSlotConfig()){
if(GuiSlotConfiguration.mouseReleased(mouseX, mouseY, state, this)){
return;
}
}
if(slotConfigType == SlotConfigType.FLUIDS && getMachine().showTankConfig()){
if(GuiFluidConfiguration.mouseReleased(mouseX, mouseY, state, this)){
return;
}
}
super.mouseReleased(mouseX, mouseY, state);
}
@Override
protected void keyTyped(char typedChar, int keyCode) throws IOException {
if(slotConfigType == SlotConfigType.ITEMS){
if(isCtrlKeyDown() && keyCode == Keyboard.KEY_C){
GuiSlotConfiguration.copyToClipboard();
return;
} else if(isCtrlKeyDown() && keyCode == Keyboard.KEY_V){
GuiSlotConfiguration.pasteFromClipboard();
return;
}
}
super.keyTyped(typedChar, keyCode);
}
@Override
public void onGuiClosed() {
slotConfigType = SlotConfigType.NONE;
super.onGuiClosed();
}
public boolean isPointInRect(int rectX, int rectY, int rectWidth, int rectHeight, int pointX, int pointY) {
return super.isPointInRegion(rectX, rectY, rectWidth, rectHeight, pointX, pointY);
}
public TileLegacyMachineBase getMachine(){
return (TileLegacyMachineBase) tile;
}
public enum Layer {
BACKGROUND, FOREGROUND
}
public enum SlotConfigType{
NONE,
ITEMS,
FLUIDS
}
}
| src/main/java/techreborn/client/gui/GuiBase.java | /*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2018 TechReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package techreborn.client.gui;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fml.client.config.GuiUtils;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard;
import reborncore.api.tile.IUpgradeable;
import reborncore.common.tile.TileLegacyMachineBase;
import techreborn.client.container.builder.BuiltContainer;
import techreborn.client.gui.slot.GuiFluidConfiguration;
import techreborn.client.gui.slot.GuiSlotConfiguration;
import techreborn.client.gui.widget.GuiButtonPowerBar;
import techreborn.init.TRItems;
import techreborn.items.DynamicCell;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Prospector
*/
public class GuiBase extends GuiContainer {
public int xSize = 176;
public int ySize = 176;
public TRBuilder builder = new TRBuilder();
public TileEntity tile;
public BuiltContainer container;
public static SlotConfigType slotConfigType = SlotConfigType.NONE;
public boolean upgrades;
public GuiBase(EntityPlayer player, TileEntity tile, BuiltContainer container) {
super(container);
this.tile = tile;
this.container = container;
slotConfigType = SlotConfigType.NONE;
}
protected void drawSlot(int x, int y, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += guiLeft;
y += guiTop;
}
builder.drawSlot(this, x - 1, y - 1);
}
protected void drawScrapSlot(int x, int y, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += guiLeft;
y += guiTop;
}
builder.drawScrapSlot(this, x - 1, y - 1);
}
protected void drawOutputSlotBar(int x, int y, int count, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += guiLeft;
y += guiTop;
}
builder.drawOutputSlotBar(this, x - 4, y - 4, count);
}
protected void drawArmourSlots(int x, int y, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += guiLeft;
y += guiTop;
}
builder.drawSlot(this, x - 1, y - 1);
builder.drawSlot(this, x - 1, y - 1 + 18);
builder.drawSlot(this, x - 1, y - 1 + 18 + 18);
builder.drawSlot(this, x - 1, y - 1 + 18 + 18 + 18);
}
protected void drawOutputSlot(int x, int y, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += guiLeft;
y += guiTop;
}
builder.drawOutputSlot(this, x - 5, y - 5);
}
protected void drawSelectedStack(int x, int y, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += guiLeft;
y += guiTop;
}
builder.drawSelectedStack(this, x, y);
}
@Override
public void initGui() {
super.initGui();
GuiSlotConfiguration.init(this);
if(getMachine().getTank() != null && getMachine().showTankConfig()){
GuiFluidConfiguration.init(this);
}
}
@Override
protected void drawGuiContainerBackgroundLayer(float p_146976_1_, int mouseX, int mouseY) {
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
builder.drawDefaultBackground(this, guiLeft, guiTop, xSize, ySize);
if (drawPlayerSlots()) {
builder.drawPlayerSlots(this, guiLeft + xSize / 2, guiTop + 93, true);
}
if (tryAddUpgrades() && tile instanceof IUpgradeable) {
IUpgradeable upgradeable = (IUpgradeable) tile;
if (upgradeable.canBeUpgraded()) {
builder.drawUpgrades(this, upgradeable, guiLeft, guiTop);
upgrades = true;
}
}
if(getMachine().hasSlotConfig()){
builder.drawSlotTab(this, guiLeft, guiTop, mouseX, mouseY, upgrades, new ItemStack(TRItems.WRENCH));
}
if(getMachine().showTankConfig()){
builder.drawSlotTab(this, guiLeft, guiTop + 27, mouseX, mouseY, upgrades, DynamicCell.getCellWithFluid(FluidRegistry.LAVA));
}
}
public boolean drawPlayerSlots() {
return true;
}
public boolean tryAddUpgrades() {
return true;
}
@SideOnly(Side.CLIENT)
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
this.buttonList.clear();
drawTitle();
if(slotConfigType == SlotConfigType.ITEMS && getMachine().hasSlotConfig()){
GuiSlotConfiguration.draw(this, mouseX, mouseY);
}
if(slotConfigType == SlotConfigType.FLUIDS && getMachine().showTankConfig()){
GuiFluidConfiguration.draw(this, mouseX, mouseY);
}
int offset = 0;
if(!upgrades){
offset = 80;
}
if (builder.isInRect(guiLeft - 19, guiTop + 92 - offset, 12, 12, mouseX, mouseY) && getMachine().hasSlotConfig()) {
List<String> list = new ArrayList<>();
list.add("Configure slots");
GuiUtils.drawHoveringText(list, mouseX - guiLeft , mouseY - guiTop , width, height, -1, mc.fontRenderer);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1);
}
if (builder.isInRect(guiLeft - 19, guiTop + 92 - offset + 27, 12, 12, mouseX, mouseY) && getMachine().hasSlotConfig()) {
List<String> list = new ArrayList<>();
list.add("Configure Fluids");
GuiUtils.drawHoveringText(list, mouseX - guiLeft , mouseY - guiTop , width, height, -1, mc.fontRenderer);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1);
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
this.drawDefaultBackground();
super.drawScreen(mouseX, mouseY, partialTicks);
this.renderHoveredToolTip(mouseX, mouseY);
}
protected void drawTitle() {
drawCentredString(I18n.format(tile.getBlockType().getTranslationKey() + ".name"), 6, 4210752, Layer.FOREGROUND);
}
protected void drawCentredString(String string, int y, int colour, Layer layer) {
drawString(string, (xSize / 2 - mc.fontRenderer.getStringWidth(string) / 2), y, colour, layer);
}
protected void drawCentredString(String string, int y, int colour, int modifier, Layer layer) {
drawString(string, (xSize / 2 - (mc.fontRenderer.getStringWidth(string)) / 2) + modifier, y, colour, layer);
}
protected void drawString(String string, int x, int y, int colour, Layer layer) {
int factorX = 0;
int factorY = 0;
if (layer == Layer.BACKGROUND) {
factorX = guiLeft;
factorY = guiTop;
}
mc.fontRenderer.drawString(string, x + factorX, y + factorY, colour);
GlStateManager.color(1, 1, 1, 1);
}
public void addPowerButton(int x, int y, int id, Layer layer) {
int factorX = 0;
int factorY = 0;
if (layer == Layer.BACKGROUND) {
factorX = guiLeft;
factorY = guiTop;
}
buttonList.add(new GuiButtonPowerBar(id, x + factorX, y + factorY, this, layer));
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
if(slotConfigType == SlotConfigType.ITEMS && getMachine().hasSlotConfig()){
if(GuiSlotConfiguration.mouseClicked(mouseX, mouseY, mouseButton, this)){
return;
}
}
if(slotConfigType == SlotConfigType.FLUIDS && getMachine().showTankConfig()){
if(GuiFluidConfiguration.mouseClicked(mouseX, mouseY, mouseButton, this)){
return;
}
}
super.mouseClicked(mouseX, mouseY, mouseButton);
}
@Override
protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) {
if(slotConfigType == SlotConfigType.ITEMS && getMachine().hasSlotConfig()){
GuiSlotConfiguration.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick, this);
}
if(slotConfigType == SlotConfigType.FLUIDS && getMachine().showTankConfig()){
GuiFluidConfiguration.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick, this);
}
super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick);
}
@Override
protected void mouseReleased(int mouseX, int mouseY, int state) {
int offset = 0;
if(!upgrades){
offset = 80;
}
if(isPointInRegion(-26, 84 - offset, 30, 30, mouseX, mouseY) && getMachine().hasSlotConfig()){
if(slotConfigType != SlotConfigType.ITEMS){
slotConfigType = SlotConfigType.ITEMS;
} else {
slotConfigType = SlotConfigType.NONE;
}
if(slotConfigType == SlotConfigType.ITEMS){
GuiSlotConfiguration.reset();
}
}
if(isPointInRegion(-26, 84 - offset + 27, 30, 30, mouseX, mouseY) && getMachine().hasSlotConfig()){
if(slotConfigType != SlotConfigType.FLUIDS){
slotConfigType = SlotConfigType.FLUIDS;
} else {
slotConfigType = SlotConfigType.NONE;
}
}
if(slotConfigType == SlotConfigType.ITEMS && getMachine().hasSlotConfig()){
if(GuiSlotConfiguration.mouseReleased(mouseX, mouseY, state, this)){
return;
}
}
if(slotConfigType == SlotConfigType.FLUIDS && getMachine().showTankConfig()){
if(GuiFluidConfiguration.mouseReleased(mouseX, mouseY, state, this)){
return;
}
}
super.mouseReleased(mouseX, mouseY, state);
}
@Override
protected void keyTyped(char typedChar, int keyCode) throws IOException {
if(slotConfigType == SlotConfigType.ITEMS){
if(isCtrlKeyDown() && keyCode == Keyboard.KEY_C){
GuiSlotConfiguration.copyToClipboard();
return;
} else if(isCtrlKeyDown() && keyCode == Keyboard.KEY_V){
GuiSlotConfiguration.pasteFromClipboard();
return;
}
}
super.keyTyped(typedChar, keyCode);
}
@Override
public void onGuiClosed() {
slotConfigType = SlotConfigType.NONE;
super.onGuiClosed();
}
public boolean isPointInRect(int rectX, int rectY, int rectWidth, int rectHeight, int pointX, int pointY) {
return super.isPointInRegion(rectX, rectY, rectWidth, rectHeight, pointX, pointY);
}
public TileLegacyMachineBase getMachine(){
return (TileLegacyMachineBase) tile;
}
public enum Layer {
BACKGROUND, FOREGROUND
}
public enum SlotConfigType{
NONE,
ITEMS,
FLUIDS
}
}
| Fix fluid config showing when it shouldn't
| src/main/java/techreborn/client/gui/GuiBase.java | Fix fluid config showing when it shouldn't |
|
Java | mit | e249129adb4b705607044265743478bb8a6559e5 | 0 | greboid/DMDirc,ShaneMcC/DMDirc-Client,DMDirc/DMDirc,csmith/DMDirc,ShaneMcC/DMDirc-Client,ShaneMcC/DMDirc-Client,greboid/DMDirc,csmith/DMDirc,csmith/DMDirc,greboid/DMDirc,greboid/DMDirc,DMDirc/DMDirc,csmith/DMDirc,ShaneMcC/DMDirc-Client,DMDirc/DMDirc,DMDirc/DMDirc | /*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.config;
import com.dmdirc.Main;
import com.dmdirc.interfaces.ConfigChangeListener;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.util.ConfigFile;
import com.dmdirc.util.InvalidConfigFileException;
import com.dmdirc.util.WeakList;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* An identity is a group of settings that are applied to a connection, server,
* network or channel. Identities may be automatically applied in certain
* cases, or the user may manually apply them.
* <p>
* Note: this class has a natural ordering that is inconsistent with equals.
*
* @author chris
*/
public class Identity extends ConfigSource implements Serializable,
Comparable<Identity> {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** The domain used for identity settings. */
private static final String DOMAIN = "identity".intern();
/** The domain used for profile settings. */
private static final String PROFILE_DOMAIN = "profile".intern();
/** The target for this identity. */
protected final ConfigTarget myTarget;
/** The configuration details for this identity. */
protected final ConfigFile file;
/** The global config manager. */
protected ConfigManager globalConfig;
/** The config change listeners for this source. */
protected final List<ConfigChangeListener> listeners
= new WeakList<ConfigChangeListener>();
/** Whether this identity needs to be saved. */
protected boolean needSave;
/**
* Creates a new instance of Identity.
*
* @param file The file to load this identity from
* @param forceDefault Whether to force this identity to be loaded as default
* identity or not
* @throws InvalidIdentityFileException Missing required properties
* @throws IOException Input/output exception
*/
public Identity(final File file, final boolean forceDefault) throws IOException,
InvalidIdentityFileException {
super();
this.file = new ConfigFile(file);
this.file.setAutomake(true);
initFile(forceDefault, new FileInputStream(file));
myTarget = getTarget(forceDefault);
if (myTarget.getType() == ConfigTarget.TYPE.PROFILE) {
migrateProfile();
}
}
/**
* Creates a new read-only identity.
*
* @param stream The input stream to read the identity from
* @param forceDefault Whether to force this identity to be loaded as default
* identity or not
* @throws InvalidIdentityFileException Missing required properties
* @throws IOException Input/output exception
*/
public Identity(final InputStream stream, final boolean forceDefault) throws IOException,
InvalidIdentityFileException {
super();
this.file = new ConfigFile(stream);
this.file.setAutomake(true);
initFile(forceDefault, stream);
myTarget = getTarget(forceDefault);
if (myTarget.getType() == ConfigTarget.TYPE.PROFILE) {
migrateProfile();
}
}
/**
* Creates a new identity from the specified config file.
*
* @param configFile The config file to use
* @param target The target of this identity
*/
public Identity(final ConfigFile configFile, final ConfigTarget target) {
super();
this.file = configFile;
this.file.setAutomake(true);
this.myTarget = target;
if (myTarget.getType() == ConfigTarget.TYPE.PROFILE) {
migrateProfile();
}
}
/**
* Determines and returns the target for this identity from its contents.
*
* @param forceDefault Whether to force this to be a default identity
* @return A ConfigTarget for this identity
* @throws InvalidIdentityFileException If the identity isn't valid
*/
private ConfigTarget getTarget(final boolean forceDefault)
throws InvalidIdentityFileException {
final ConfigTarget target = new ConfigTarget();
if (hasOption(DOMAIN, "ircd")) {
target.setIrcd(getOption(DOMAIN, "ircd"));
} else if (hasOption(DOMAIN, "network")) {
target.setNetwork(getOption(DOMAIN, "network"));
} else if (hasOption(DOMAIN, "server")) {
target.setServer(getOption(DOMAIN, "server"));
} else if (hasOption(DOMAIN, "channel")) {
target.setChannel(getOption(DOMAIN, "channel"));
} else if (hasOption(DOMAIN, "globaldefault")) {
target.setGlobalDefault();
} else if (hasOption(DOMAIN, "global") || (forceDefault && !isProfile())) {
target.setGlobal();
} else if (isProfile()) {
target.setProfile();
} else {
throw new InvalidIdentityFileException("No target and no profile");
}
if (hasOption(DOMAIN, "order")) {
target.setOrder(getOptionInt(DOMAIN, "order"));
}
return target;
}
/**
* Initialises this identity from a file.
*
* @param forceDefault Whether to force this to be a default identity
* @param stream The stream to load properties from if needed (or null)
* @param file The file to load this identity from (or null)
* @throws InvalidIdentityFileException if the identity file is invalid
* @throws IOException On I/O exception when reading the identity
*/
private void initFile(final boolean forceDefault, final InputStream stream)
throws InvalidIdentityFileException, IOException {
try {
this.file.read();
} catch (InvalidConfigFileException ex) {
throw new InvalidIdentityFileException(ex);
}
if (!hasOption(DOMAIN, "name") && !forceDefault) {
throw new InvalidIdentityFileException("No name specified");
}
}
/**
* Attempts to reload this identity from disk. If this identity has been
* modified (i.e., {@code needSave} is true), then this method silently
* returns straight away. All relevant ConfigChangeListeners are fired for
* new, altered and deleted properties. The target of the identity will not
* be changed by this method, even if it has changed on disk.
*
* @throws java.io.IOException On I/O exception when reading the identity
* @throws InvalidConfigFileException if the config file is no longer valid
*/
public synchronized void reload() throws IOException, InvalidConfigFileException {
if (needSave) {
return;
}
final Map<String, Map<String, String>> oldProps = file.getKeyDomains();
file.read();
for (Map.Entry<String, Map<String, String>> entry : file.getKeyDomains().entrySet()) {
final String domain = entry.getKey();
for (Map.Entry<String, String> subentry : entry.getValue().entrySet()) {
final String key = subentry.getKey();
final String value = subentry.getValue();
if (!oldProps.containsKey(domain)) {
fireReloadChange(domain, key);
} else if (!oldProps.get(domain).containsKey(key)
|| !oldProps.get(domain).get(key).equals(value)) {
fireReloadChange(domain, key);
oldProps.get(domain).remove(key);
}
}
if (oldProps.containsKey(domain)) {
for (String key : oldProps.get(domain).keySet()) {
fireReloadChange(domain, key);
}
}
}
}
/**
* Fires the config changed listener for the specified option after this
* identity is reloaded.
*
* @param domain The domain of the option that's changed
* @param key The key of the option that's changed
*/
private void fireReloadChange(final String domain, final String key) {
for (ConfigChangeListener listener : new ArrayList<ConfigChangeListener>(listeners)) {
listener.configChanged(domain, key);
}
}
/**
* Returns the name of this identity.
*
* @return The name of this identity
*/
public String getName() {
if (hasOption(DOMAIN, "name")) {
return getOption(DOMAIN, "name");
} else {
return "Unnamed";
}
}
/**
* Checks if this profile needs migrating from the old method of
* storing nicknames (profile.nickname + profile.altnicks) to the new
* method (profile.nicknames), and performs the migration if needed.
*
* @since 0.6.3
*/
protected void migrateProfile() {
if (hasOption(PROFILE_DOMAIN, "nickname")) {
// Migrate
setOption(PROFILE_DOMAIN, "nicknames", getOption(PROFILE_DOMAIN, "nickname")
+ (hasOption(PROFILE_DOMAIN, "altnicks") ? "\n"
+ getOption(PROFILE_DOMAIN, "altnicks") : ""));
unsetOption(PROFILE_DOMAIN, "nickname");
unsetOption(PROFILE_DOMAIN, "altnicks");
}
}
/**
* Determines whether this identity can be used as a profile when
* connecting to a server. Profiles are identities that can supply
* nick, ident, real name, etc.
*
* @return True iff this identity can be used as a profile
*/
public boolean isProfile() {
return (hasOption(PROFILE_DOMAIN, "nicknames")
|| hasOption(PROFILE_DOMAIN, "nickname"))
&& hasOption(PROFILE_DOMAIN, "realname");
}
/** {@inheritDoc} */
@Override
protected boolean hasOption(final String domain, final String option) {
return file.isKeyDomain(domain) && file.getKeyDomain(domain).containsKey(option);
}
/** {@inheritDoc} */
@Override
public synchronized String getOption(final String domain, final String option) {
return file.getKeyDomain(domain).get(option);
}
/**
* Sets the specified option in this identity to the specified value.
*
* @param domain The domain of the option
* @param option The name of the option
* @param value The new value for the option
*/
public synchronized void setOption(final String domain, final String option,
final String value) {
final String oldValue = getOption(domain, option);
if (myTarget.getType() == ConfigTarget.TYPE.GLOBAL) {
// If we're the global config, don't set useless settings that are
// covered by global defaults.
if (globalConfig == null) {
globalConfig = new ConfigManager("", "", "");
}
globalConfig.removeIdentity(this);
if (globalConfig.hasOption(domain, option)
&& globalConfig.getOption(domain, option).equals(value)) {
if (oldValue == null) {
return;
} else {
unsetOption(domain, option);
return;
}
}
}
if ((oldValue == null && value != null)
|| (oldValue != null && !oldValue.equals(value))) {
file.getKeyDomain(domain).put(option, value);
needSave = true;
for (ConfigChangeListener listener :
new ArrayList<ConfigChangeListener>(listeners)) {
listener.configChanged(domain, option);
}
}
}
/**
* Sets the specified option in this identity to the specified value.
*
* @param domain The domain of the option
* @param option The name of the option
* @param value The new value for the option
*/
public void setOption(final String domain, final String option,
final int value) {
setOption(domain, option, String.valueOf(value));
}
/**
* Sets the specified option in this identity to the specified value.
*
* @param domain The domain of the option
* @param option The name of the option
* @param value The new value for the option
*/
public void setOption(final String domain, final String option,
final boolean value) {
setOption(domain, option, String.valueOf(value));
}
/**
* Sets the specified option in this identity to the specified value.
*
* @param domain The domain of the option
* @param option The name of the option
* @param value The new value for the option
*/
public void setOption(final String domain, final String option,
final List<String> value) {
final StringBuilder temp = new StringBuilder();
for (String part : value) {
temp.append('\n');
temp.append(part);
}
setOption(domain, option, temp.length() > 0 ? temp.substring(1) : temp.toString());
}
/**
* Unsets a specified option.
*
* @param domain domain of the option
* @param option name of the option
*/
public synchronized void unsetOption(final String domain, final String option) {
file.getKeyDomain(domain).remove(option);
needSave = true;
for (ConfigChangeListener listener : new ArrayList<ConfigChangeListener>(listeners)) {
listener.configChanged(domain, option);
}
}
/**
* Returns the set of domains available in this identity.
*
* @since 0.6
* @return The set of domains used by this identity
*/
public Set<String> getDomains() {
return new HashSet<String>(file.getKeyDomains().keySet());
}
/**
* Retrieves a map of all options within the specified domain in this
* identity.
*
* @param domain The domain to retrieve
* @since 0.6
* @return A map of option names to values
*/
public Map<String, String> getOptions(final String domain) {
return new HashMap<String, String>(file.getKeyDomain(domain));
}
/**
* Saves this identity to disk if it has been updated.
*/
public synchronized void save() {
if (needSave && file != null && file.isWritable()) {
if (myTarget != null && myTarget.getType() == ConfigTarget.TYPE.GLOBAL) {
// If we're the global config, unset useless settings that are
// covered by global defaults.
if (globalConfig == null) {
globalConfig = new ConfigManager("", "", "");
}
globalConfig.removeIdentity(this);
for (Map.Entry<String, Map<String, String>> entry
: file.getKeyDomains().entrySet()) {
final String domain = entry.getKey();
for (Map.Entry<String, String> subentry : entry.getValue().entrySet()) {
final String key = subentry.getKey();
final String value = subentry.getValue();
if (globalConfig.hasOption(domain, key) &&
globalConfig.getOption(domain, key).equals(value)) {
file.getKeyDomain(domain).remove(key);
}
}
}
}
if (file.isKeyDomain("temp")) {
file.getKeyDomain("temp").clear();
}
try {
file.write();
needSave = false;
} catch (IOException ex) {
Logger.userError(ErrorLevel.MEDIUM,
"Unable to save identity file: " + ex.getMessage());
}
}
}
/**
* Deletes this identity from disk.
*/
public synchronized void delete() {
if (file != null) {
file.delete();
}
IdentityManager.removeIdentity(this);
}
/**
* Retrieves this identity's target.
*
* @return The target of this identity
*/
public ConfigTarget getTarget() {
return myTarget;
}
/**
* Retrieve this identity's ConfigFile.
*
* @return The ConfigFile object used by this identity
* @deprecated Direct access should be avoided to prevent synchronisation
* issues
*/
@Deprecated
public ConfigFile getFile() {
return file;
}
/**
* Adds a new config change listener for this identity.
*
* @param listener The listener to be added
*/
public void addListener(final ConfigChangeListener listener) {
listeners.add(listener);
}
/**
* Removes the specific config change listener from this identity.
*
* @param listener The listener to be removed
*/
public void removeListener(final ConfigChangeListener listener) {
listeners.remove(listener);
}
/**
* Returns a string representation of this object (its name).
*
* @return A string representation of this object
*/
@Override
public String toString() {
return getName();
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return getName().hashCode() + getTarget().hashCode();
}
/** {@inheritDoc} */
@Override
public boolean equals(final Object obj) {
if (obj instanceof Identity
&& getName().equals(((Identity) obj).getName())
&& getTarget() == ((Identity) obj).getTarget()) {
return true;
}
return false;
}
/**
* Compares this identity to another config source to determine which
* is more specific.
*
* @param target The Identity to compare to
* @return -1 if this config source is less specific, 0 if they're equal,
* +1 if this config is more specific.
*/
@Override
public int compareTo(final Identity target) {
return target.getTarget().compareTo(myTarget);
}
/**
* Creates a new identity containing the specified properties.
*
* @param settings The settings to populate the identity with
* @return A new identity containing the specified properties
* @throws IOException If the file cannot be created
* @throws InvalidIdentityFileException If the settings are invalid
* @since 0.6.3
*/
protected static Identity createIdentity(final Map<String, Map<String, String>> settings)
throws IOException, InvalidIdentityFileException {
if (!settings.containsKey(DOMAIN) || !settings.get(DOMAIN).containsKey("name")
|| settings.get(DOMAIN).get("name").isEmpty()) {
throw new InvalidIdentityFileException("identity.name is not set");
}
final String fs = System.getProperty("file.separator");
final String location = Main.getConfigDir() + "identities" + fs;
final String name = settings.get(DOMAIN).get("name");
File file = new File(location + name);
int attempt = 0;
while (file.exists()) {
file = new File(location + name + "-" + ++attempt);
}
final ConfigFile configFile = new ConfigFile(file);
for (Map.Entry<String, Map<String, String>> entry : settings.entrySet()) {
configFile.addDomain(entry.getKey(), entry.getValue());
}
configFile.write();
final Identity identity = new Identity(file, false);
IdentityManager.addIdentity(identity);
return identity;
}
/**
* Generates an empty identity for the specified target.
*
* @param target The target for the new identity
* @return An empty identity for the specified target
* @throws IOException if the file can't be written
* @see #createIdentity(java.util.Map)
*/
public static Identity buildIdentity(final ConfigTarget target)
throws IOException {
final Map<String, Map<String, String>> settings
= new HashMap<String, Map<String, String>>();
settings.put(DOMAIN, new HashMap<String, String>(2));
settings.get(DOMAIN).put("name", target.getData());
settings.get(DOMAIN).put(target.getTypeName(), target.getData());
try {
return createIdentity(settings);
} catch (InvalidIdentityFileException ex) {
Logger.appError(ErrorLevel.MEDIUM, "Unable to create identity", ex);
return null;
}
}
/**
* Generates an empty profile witht he specified name. Note the name is used
* as a file name, so should be sanitised.
*
* @param name The name of the profile to create
* @return A new profile with the specified name
* @throws IOException If the file can't be written
* @see #createIdentity(java.util.Map)
*/
public static Identity buildProfile(final String name) throws IOException {
final Map<String, Map<String, String>> settings
= new HashMap<String, Map<String, String>>();
settings.put(DOMAIN, new HashMap<String, String>(1));
settings.put(PROFILE_DOMAIN, new HashMap<String, String>(2));
final String nick = System.getProperty("user.name").replace(' ', '_');
settings.get(DOMAIN).put("name", name);
settings.get(PROFILE_DOMAIN).put("nicknames", nick);
settings.get(PROFILE_DOMAIN).put("realname", nick);
try {
return createIdentity(settings);
} catch (InvalidIdentityFileException ex) {
Logger.appError(ErrorLevel.MEDIUM, "Unable to create identity", ex);
return null;
}
}
}
| src/com/dmdirc/config/Identity.java | /*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.config;
import com.dmdirc.Main;
import com.dmdirc.interfaces.ConfigChangeListener;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.util.ConfigFile;
import com.dmdirc.util.InvalidConfigFileException;
import com.dmdirc.util.WeakList;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* An identity is a group of settings that are applied to a connection, server,
* network or channel. Identities may be automatically applied in certain
* cases, or the user may manually apply them.
* <p>
* Note: this class has a natural ordering that is inconsistent with equals.
*
* @author chris
*/
public class Identity extends ConfigSource implements Serializable,
Comparable<Identity> {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** The domain used for identity settings. */
private static final String DOMAIN = "identity".intern();
/** The domain used for profile settings. */
private static final String PROFILE_DOMAIN = "profile".intern();
/** The target for this identity. */
protected final ConfigTarget myTarget;
/** The configuration details for this identity. */
protected final ConfigFile file;
/** The global config manager. */
protected ConfigManager globalConfig;
/** The config change listeners for this source. */
protected final List<ConfigChangeListener> listeners
= new WeakList<ConfigChangeListener>();
/** Whether this identity needs to be saved. */
protected boolean needSave;
/**
* Creates a new instance of Identity.
*
* @param file The file to load this identity from
* @param forceDefault Whether to force this identity to be loaded as default
* identity or not
* @throws InvalidIdentityFileException Missing required properties
* @throws IOException Input/output exception
*/
public Identity(final File file, final boolean forceDefault) throws IOException,
InvalidIdentityFileException {
super();
this.file = new ConfigFile(file);
this.file.setAutomake(true);
initFile(forceDefault, new FileInputStream(file));
myTarget = getTarget(forceDefault);
if (myTarget.getType() == ConfigTarget.TYPE.PROFILE) {
migrateProfile();
}
}
/**
* Creates a new read-only identity.
*
* @param stream The input stream to read the identity from
* @param forceDefault Whether to force this identity to be loaded as default
* identity or not
* @throws InvalidIdentityFileException Missing required properties
* @throws IOException Input/output exception
*/
public Identity(final InputStream stream, final boolean forceDefault) throws IOException,
InvalidIdentityFileException {
super();
this.file = new ConfigFile(stream);
this.file.setAutomake(true);
initFile(forceDefault, stream);
myTarget = getTarget(forceDefault);
if (myTarget.getType() == ConfigTarget.TYPE.PROFILE) {
migrateProfile();
}
}
/**
* Creates a new identity from the specified config file.
*
* @param configFile The config file to use
* @param target The target of this identity
*/
public Identity(final ConfigFile configFile, final ConfigTarget target) {
super();
this.file = configFile;
this.file.setAutomake(true);
this.myTarget = target;
if (myTarget.getType() == ConfigTarget.TYPE.PROFILE) {
migrateProfile();
}
}
/**
* Determines and returns the target for this identity from its contents.
*
* @param forceDefault Whether to force this to be a default identity
* @return A ConfigTarget for this identity
* @throws InvalidIdentityFileException If the identity isn't valid
*/
private ConfigTarget getTarget(final boolean forceDefault)
throws InvalidIdentityFileException {
final ConfigTarget target = new ConfigTarget();
if (hasOption(DOMAIN, "ircd")) {
target.setIrcd(getOption(DOMAIN, "ircd"));
} else if (hasOption(DOMAIN, "network")) {
target.setNetwork(getOption(DOMAIN, "network"));
} else if (hasOption(DOMAIN, "server")) {
target.setServer(getOption(DOMAIN, "server"));
} else if (hasOption(DOMAIN, "channel")) {
target.setChannel(getOption(DOMAIN, "channel"));
} else if (hasOption(DOMAIN, "globaldefault")) {
target.setGlobalDefault();
} else if (hasOption(DOMAIN, "global") || (forceDefault && !isProfile())) {
target.setGlobal();
} else if (isProfile()) {
target.setProfile();
} else {
throw new InvalidIdentityFileException("No target and no profile");
}
if (hasOption(DOMAIN, "order")) {
target.setOrder(getOptionInt(DOMAIN, "order"));
}
return target;
}
/**
* Initialises this identity from a file.
*
* @param forceDefault Whether to force this to be a default identity
* @param stream The stream to load properties from if needed (or null)
* @param file The file to load this identity from (or null)
* @throws InvalidIdentityFileException if the identity file is invalid
* @throws IOException On I/O exception when reading the identity
*/
private void initFile(final boolean forceDefault, final InputStream stream)
throws InvalidIdentityFileException, IOException {
try {
this.file.read();
} catch (InvalidConfigFileException ex) {
throw new InvalidIdentityFileException(ex);
}
if (!hasOption(DOMAIN, "name") && !forceDefault) {
throw new InvalidIdentityFileException("No name specified");
}
}
/**
* Attempts to reload this identity from disk. If this identity has been
* modified (i.e., {@code needSave} is true), then this method silently
* returns straight away. All relevant ConfigChangeListeners are fired for
* new, altered and deleted properties. The target of the identity will not
* be changed by this method, even if it has changed on disk.
*
* @throws java.io.IOException On I/O exception when reading the identity
* @throws InvalidConfigFileException if the config file is no longer valid
*/
public synchronized void reload() throws IOException, InvalidConfigFileException {
if (needSave) {
return;
}
final Map<String, Map<String, String>> oldProps = file.getKeyDomains();
file.read();
for (Map.Entry<String, Map<String, String>> entry : file.getKeyDomains().entrySet()) {
final String domain = entry.getKey();
for (Map.Entry<String, String> subentry : entry.getValue().entrySet()) {
final String key = subentry.getKey();
final String value = subentry.getValue();
if (!oldProps.containsKey(domain)) {
fireReloadChange(domain, key);
} else if (!oldProps.get(domain).containsKey(key)
|| !oldProps.get(domain).get(key).equals(value)) {
fireReloadChange(domain, key);
oldProps.get(domain).remove(key);
}
}
if (oldProps.containsKey(domain)) {
for (String key : oldProps.get(domain).keySet()) {
fireReloadChange(domain, key);
}
}
}
}
/**
* Fires the config changed listener for the specified option after this
* identity is reloaded.
*
* @param domain The domain of the option that's changed
* @param key The key of the option that's changed
*/
private void fireReloadChange(final String domain, final String key) {
for (ConfigChangeListener listener : new ArrayList<ConfigChangeListener>(listeners)) {
listener.configChanged(domain, key);
}
}
/**
* Returns the name of this identity.
*
* @return The name of this identity
*/
public String getName() {
if (hasOption(DOMAIN, "name")) {
return getOption(DOMAIN, "name");
} else {
return "Unnamed";
}
}
/**
* Checks if this profile needs migrating from the old method of
* storing nicknames (profile.nickname + profile.altnicks) to the new
* method (profile.nicknames), and performs the migration if needed.
*
* @since 0.6.3
*/
protected void migrateProfile() {
if (hasOption(PROFILE_DOMAIN, "nickname")) {
// Migrate
setOption(PROFILE_DOMAIN, "nicknames", getOption(PROFILE_DOMAIN, "nickname")
+ (hasOption(PROFILE_DOMAIN, "altnicks") ? "\n"
+ getOption(PROFILE_DOMAIN, "altnicks") : ""));
unsetOption(PROFILE_DOMAIN, "nickname");
unsetOption(PROFILE_DOMAIN, "altnicks");
}
}
/**
* Determines whether this identity can be used as a profile when
* connecting to a server. Profiles are identities that can supply
* nick, ident, real name, etc.
*
* @return True iff this identity can be used as a profile
*/
public boolean isProfile() {
return (hasOption(PROFILE_DOMAIN, "nicknames")
|| hasOption(PROFILE_DOMAIN, "nickname"))
&& hasOption(PROFILE_DOMAIN, "realname");
}
/** {@inheritDoc} */
@Override
protected boolean hasOption(final String domain, final String option) {
return file.isKeyDomain(domain) && file.getKeyDomain(domain).containsKey(option);
}
/** {@inheritDoc} */
@Override
public String getOption(final String domain, final String option) {
return file.getKeyDomain(domain).get(option);
}
/**
* Sets the specified option in this identity to the specified value.
*
* @param domain The domain of the option
* @param option The name of the option
* @param value The new value for the option
*/
public synchronized void setOption(final String domain, final String option,
final String value) {
final String oldValue = getOption(domain, option);
if (myTarget.getType() == ConfigTarget.TYPE.GLOBAL) {
// If we're the global config, don't set useless settings that are
// covered by global defaults.
if (globalConfig == null) {
globalConfig = new ConfigManager("", "", "");
}
globalConfig.removeIdentity(this);
if (globalConfig.hasOption(domain, option)
&& globalConfig.getOption(domain, option).equals(value)) {
if (oldValue == null) {
return;
} else {
unsetOption(domain, option);
return;
}
}
}
if ((oldValue == null && value != null)
|| (oldValue != null && !oldValue.equals(value))) {
file.getKeyDomain(domain).put(option, value);
needSave = true;
for (ConfigChangeListener listener :
new ArrayList<ConfigChangeListener>(listeners)) {
listener.configChanged(domain, option);
}
}
}
/**
* Sets the specified option in this identity to the specified value.
*
* @param domain The domain of the option
* @param option The name of the option
* @param value The new value for the option
*/
public void setOption(final String domain, final String option,
final int value) {
setOption(domain, option, String.valueOf(value));
}
/**
* Sets the specified option in this identity to the specified value.
*
* @param domain The domain of the option
* @param option The name of the option
* @param value The new value for the option
*/
public void setOption(final String domain, final String option,
final boolean value) {
setOption(domain, option, String.valueOf(value));
}
/**
* Sets the specified option in this identity to the specified value.
*
* @param domain The domain of the option
* @param option The name of the option
* @param value The new value for the option
*/
public void setOption(final String domain, final String option,
final List<String> value) {
final StringBuilder temp = new StringBuilder();
for (String part : value) {
temp.append('\n');
temp.append(part);
}
setOption(domain, option, temp.length() > 0 ? temp.substring(1) : temp.toString());
}
/**
* Unsets a specified option.
*
* @param domain domain of the option
* @param option name of the option
*/
public synchronized void unsetOption(final String domain, final String option) {
file.getKeyDomain(domain).remove(option);
needSave = true;
for (ConfigChangeListener listener : new ArrayList<ConfigChangeListener>(listeners)) {
listener.configChanged(domain, option);
}
}
/**
* Returns the set of domains available in this identity.
*
* @since 0.6
* @return The set of domains used by this identity
*/
public Set<String> getDomains() {
return new HashSet<String>(file.getKeyDomains().keySet());
}
/**
* Retrieves a map of all options within the specified domain in this
* identity.
*
* @param domain The domain to retrieve
* @since 0.6
* @return A map of option names to values
*/
public Map<String, String> getOptions(final String domain) {
return new HashMap<String, String>(file.getKeyDomain(domain));
}
/**
* Saves this identity to disk if it has been updated.
*/
public synchronized void save() {
if (needSave && file != null && file.isWritable()) {
if (myTarget != null && myTarget.getType() == ConfigTarget.TYPE.GLOBAL) {
// If we're the global config, unset useless settings that are
// covered by global defaults.
if (globalConfig == null) {
globalConfig = new ConfigManager("", "", "");
}
globalConfig.removeIdentity(this);
for (Map.Entry<String, Map<String, String>> entry
: file.getKeyDomains().entrySet()) {
final String domain = entry.getKey();
for (Map.Entry<String, String> subentry : entry.getValue().entrySet()) {
final String key = subentry.getKey();
final String value = subentry.getValue();
if (globalConfig.hasOption(domain, key) &&
globalConfig.getOption(domain, key).equals(value)) {
file.getKeyDomain(domain).remove(key);
}
}
}
}
if (file.isKeyDomain("temp")) {
file.getKeyDomain("temp").clear();
}
try {
file.write();
needSave = false;
} catch (IOException ex) {
Logger.userError(ErrorLevel.MEDIUM,
"Unable to save identity file: " + ex.getMessage());
}
}
}
/**
* Deletes this identity from disk.
*/
public synchronized void delete() {
if (file != null) {
file.delete();
}
IdentityManager.removeIdentity(this);
}
/**
* Retrieves this identity's target.
*
* @return The target of this identity
*/
public ConfigTarget getTarget() {
return myTarget;
}
/**
* Retrieve this identity's ConfigFile.
*
* @return The ConfigFile object used by this identity
* @deprecated Direct access should be avoided to prevent synchronisation
* issues
*/
@Deprecated
public ConfigFile getFile() {
return file;
}
/**
* Adds a new config change listener for this identity.
*
* @param listener The listener to be added
*/
public void addListener(final ConfigChangeListener listener) {
listeners.add(listener);
}
/**
* Removes the specific config change listener from this identity.
*
* @param listener The listener to be removed
*/
public void removeListener(final ConfigChangeListener listener) {
listeners.remove(listener);
}
/**
* Returns a string representation of this object (its name).
*
* @return A string representation of this object
*/
@Override
public String toString() {
return getName();
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return getName().hashCode() + getTarget().hashCode();
}
/** {@inheritDoc} */
@Override
public boolean equals(final Object obj) {
if (obj instanceof Identity
&& getName().equals(((Identity) obj).getName())
&& getTarget() == ((Identity) obj).getTarget()) {
return true;
}
return false;
}
/**
* Compares this identity to another config source to determine which
* is more specific.
*
* @param target The Identity to compare to
* @return -1 if this config source is less specific, 0 if they're equal,
* +1 if this config is more specific.
*/
@Override
public int compareTo(final Identity target) {
return target.getTarget().compareTo(myTarget);
}
/**
* Creates a new identity containing the specified properties.
*
* @param settings The settings to populate the identity with
* @return A new identity containing the specified properties
* @throws IOException If the file cannot be created
* @throws InvalidIdentityFileException If the settings are invalid
* @since 0.6.3
*/
protected static Identity createIdentity(final Map<String, Map<String, String>> settings)
throws IOException, InvalidIdentityFileException {
if (!settings.containsKey(DOMAIN) || !settings.get(DOMAIN).containsKey("name")
|| settings.get(DOMAIN).get("name").isEmpty()) {
throw new InvalidIdentityFileException("identity.name is not set");
}
final String fs = System.getProperty("file.separator");
final String location = Main.getConfigDir() + "identities" + fs;
final String name = settings.get(DOMAIN).get("name");
File file = new File(location + name);
int attempt = 0;
while (file.exists()) {
file = new File(location + name + "-" + ++attempt);
}
final ConfigFile configFile = new ConfigFile(file);
for (Map.Entry<String, Map<String, String>> entry : settings.entrySet()) {
configFile.addDomain(entry.getKey(), entry.getValue());
}
configFile.write();
final Identity identity = new Identity(file, false);
IdentityManager.addIdentity(identity);
return identity;
}
/**
* Generates an empty identity for the specified target.
*
* @param target The target for the new identity
* @return An empty identity for the specified target
* @throws IOException if the file can't be written
* @see #createIdentity(java.util.Map)
*/
public static Identity buildIdentity(final ConfigTarget target)
throws IOException {
final Map<String, Map<String, String>> settings
= new HashMap<String, Map<String, String>>();
settings.put(DOMAIN, new HashMap<String, String>(2));
settings.get(DOMAIN).put("name", target.getData());
settings.get(DOMAIN).put(target.getTypeName(), target.getData());
try {
return createIdentity(settings);
} catch (InvalidIdentityFileException ex) {
Logger.appError(ErrorLevel.MEDIUM, "Unable to create identity", ex);
return null;
}
}
/**
* Generates an empty profile witht he specified name. Note the name is used
* as a file name, so should be sanitised.
*
* @param name The name of the profile to create
* @return A new profile with the specified name
* @throws IOException If the file can't be written
* @see #createIdentity(java.util.Map)
*/
public static Identity buildProfile(final String name) throws IOException {
final Map<String, Map<String, String>> settings
= new HashMap<String, Map<String, String>>();
settings.put(DOMAIN, new HashMap<String, String>(1));
settings.put(PROFILE_DOMAIN, new HashMap<String, String>(2));
final String nick = System.getProperty("user.name").replace(' ', '_');
settings.get(DOMAIN).put("name", name);
settings.get(PROFILE_DOMAIN).put("nicknames", nick);
settings.get(PROFILE_DOMAIN).put("realname", nick);
try {
return createIdentity(settings);
} catch (InvalidIdentityFileException ex) {
Logger.appError(ErrorLevel.MEDIUM, "Unable to create identity", ex);
return null;
}
}
}
| Synchronise access to Identity.getOption[s], as they could auto-create
key domains
| src/com/dmdirc/config/Identity.java | Synchronise access to Identity.getOption[s], as they could auto-create key domains |
|
Java | mit | 43c6c68097a4df4690b76a7c24e02fe94f2ebd11 | 0 | uniba-dsg/prope,uniba-dsg/prope,uniba-dsg/prope | package pete.metrics.adaptability.nodecounters;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import pete.metrics.adaptability.BpmnInspector;
/**
* Counts occurences of XML elements in a BPMN process, sorted by the name of
* the element. The list of relevant elements is determined internally
*
*/
public class SimpleNodeCounter implements NodeCounter {
private HashMap<String, AtomicInteger> elements;
private boolean isStrict;
private List<String> relevantElements;
public SimpleNodeCounter() {
setUp(true);
}
public SimpleNodeCounter(boolean isStrict) {
setUp(isStrict);
}
private void setUp(boolean isStrict) {
elements = new HashMap<String, AtomicInteger>();
this.isStrict = isStrict;
relevantElements = new ArrayList<>();
relevantElements.add("activity");
relevantElements.add("adHocSubProcess");
relevantElements.add("boundaryEvent");
relevantElements.add("businessRuleTask");
relevantElements.add("callActivity");
relevantElements.add("cancelEventDefinition");
relevantElements.add("catchEvent");
relevantElements.add("compensateEventDefinition");
relevantElements.add("complexGateway");
relevantElements.add("conditionalEventDefinition");
relevantElements.add("dataAssociation");
relevantElements.add("dataInput");
relevantElements.add("dataInputAssociation");
relevantElements.add("dataObject");
relevantElements.add("dataOutput");
relevantElements.add("dataOutputAssociation");
relevantElements.add("dataStore");
relevantElements.add("endEvent");
relevantElements.add("error");
relevantElements.add("errorBoundaryEvent");
relevantElements.add("errorEventDefinition");
relevantElements.add("escalation");
relevantElements.add("escalationEventDefinition");
relevantElements.add("event");
relevantElements.add("eventBasedGateway");
relevantElements.add("extension");
relevantElements.add("extensionElements");
relevantElements.add("formalExpression");
relevantElements.add("gateway");
relevantElements.add("globalBusinessRuleTask");
relevantElements.add("globalManualTask");
relevantElements.add("globalScriptTask");
relevantElements.add("globalUserTask");
relevantElements.add("globalTask");
relevantElements.add("implicitThrowEvent");
relevantElements.add("inclusiveGateway");
relevantElements.add("inputSet");
relevantElements.add("intermediateCatchEvent");
relevantElements.add("intermediateThrowEvent");
relevantElements.add("lane");
relevantElements.add("manualTask");
relevantElements.add("message");
relevantElements.add("messageEventDefinition");
relevantElements.add("messageFlow");
relevantElements.add("messageFlowAssociation");
relevantElements.add("loopCharacteristics");
relevantElements.add("multiInstanceLoopCharacteristics");
relevantElements.add("process");
relevantElements.add("receiveTask");
relevantElements.add("scripTask");
relevantElements.add("script");
relevantElements.add("sendTask");
relevantElements.add("sequenceFlow");
relevantElements.add("serviceTask");
relevantElements.add("signal");
relevantElements.add("signalEventDefinition");
relevantElements.add("standardLoopCharacteristics");
relevantElements.add("endEvent");
relevantElements.add("subProcess");
relevantElements.add("task");
relevantElements.add("terminateEventDefinition");
relevantElements.add("throwEvent");
relevantElements.add("timerEventDefinition");
relevantElements.add("transaction");
relevantElements.add("userTask");
relevantElements.add("isForCompensation");
}
@Override
public void addToCounts(Document dom) {
Node process = new BpmnInspector().getProcess(dom);
addNodeToCounts(process);
}
private void addNodeToCounts(Node node) {
// ignore text nodes
if (isTextNode(node)) {
return;
}
addToMap(node);
NodeList children = node.getChildNodes();
if (children != null) {
for (int i = 0; i < children.getLength(); i++) {
addNodeToCounts(children.item(i));
}
}
}
private boolean isTextNode(Node node) {
return node.getNodeType() == Node.TEXT_NODE;
}
private void addToMap(Node node) {
String nodeName = node.getLocalName();
if (isStrict && !relevantElements.contains(nodeName)) {
return;
}
if (elements.containsKey(nodeName)) {
AtomicInteger count = elements.get(nodeName);
count.incrementAndGet();
} else {
elements.put(nodeName, new AtomicInteger(1));
}
}
@Override
public void writeToCsv(Path file) {
try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(file,
Charset.defaultCharset()))) {
writer.println("element;number");
List<String> sortedKeyList = new LinkedList<>();
sortedKeyList.addAll(elements.keySet());
sortedKeyList.sort((e1, e2) -> e1.compareTo(e2));
for (String key : sortedKeyList) {
AtomicInteger value = elements.get(key);
writer.println(key + ";" + value);
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
@Override
public Map<String, AtomicInteger> getElementNumbers() {
return Collections.unmodifiableMap(elements);
}
}
| src/main/java/pete/metrics/adaptability/nodecounters/SimpleNodeCounter.java | package pete.metrics.adaptability.nodecounters;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import pete.metrics.adaptability.BpmnInspector;
/**
* Counts occurences of XML elements in a BPMN process, sorted by the name of
* the element. The list of relevant elements is determined internally
*
*/
public class SimpleNodeCounter implements NodeCounter {
private HashMap<String, AtomicInteger> elements;
private boolean isStrict;
private List<String> relevantElements;
public SimpleNodeCounter() {
setUp(true);
}
public SimpleNodeCounter(boolean isStrict) {
setUp(isStrict);
}
private void setUp(boolean isStrict) {
elements = new HashMap<String, AtomicInteger>();
this.isStrict = isStrict;
relevantElements = new ArrayList<>();
relevantElements.add("activity");
relevantElements.add("adHocSubProcess");
relevantElements.add("boundaryEvent");
relevantElements.add("businessRuleTask");
relevantElements.add("callActivity");
relevantElements.add("cancelEventDefinition");
relevantElements.add("catchEvent");
relevantElements.add("compensateEventDefinition");
relevantElements.add("complexGateway");
relevantElements.add("conditionalEventDefinition");
relevantElements.add("dataAssociation");
relevantElements.add("dataInput");
relevantElements.add("dataInputAssociation");
relevantElements.add("dataObject");
relevantElements.add("dataOutput");
relevantElements.add("dataOutputAssociation");
relevantElements.add("dataStore");
relevantElements.add("endEvent");
relevantElements.add("error");
relevantElements.add("errorBoundaryEvent");
relevantElements.add("errorEventDefinition");
relevantElements.add("escalation");
relevantElements.add("escalationEventDefinition");
relevantElements.add("event");
relevantElements.add("eventBasedGateway");
relevantElements.add("extension");
relevantElements.add("extensionElements");
relevantElements.add("formalExpression");
relevantElements.add("gateway");
relevantElements.add("globalBusinessRuleTask");
relevantElements.add("globalManualTask");
relevantElements.add("globalScriptTask");
relevantElements.add("globalUserTask");
relevantElements.add("globalTask");
relevantElements.add("implicitThrowEvent");
relevantElements.add("inclusiveGateway");
relevantElements.add("inputSet");
relevantElements.add("intermediateCatchEvent");
relevantElements.add("intermediateThrowEvent");
relevantElements.add("lane");
relevantElements.add("manualTask");
relevantElements.add("message");
relevantElements.add("messageEventDefinition");
relevantElements.add("messageFlow");
relevantElements.add("messageFlowAssociation");
relevantElements.add("loopCharacteristics");
relevantElements.add("multiInstanceLoopCharacteristics");
relevantElements.add("process");
relevantElements.add("receiveTask");
relevantElements.add("scripTask");
relevantElements.add("script");
relevantElements.add("sendTask");
relevantElements.add("sequenceFlow");
relevantElements.add("serviceTask");
relevantElements.add("signal");
relevantElements.add("signalEventDefinition");
relevantElements.add("standardLoopCharacteristics");
relevantElements.add("endEvent");
relevantElements.add("subProcess");
relevantElements.add("task");
relevantElements.add("terminateEventDefinition");
relevantElements.add("throwEvent");
relevantElements.add("timerEventDefinition");
relevantElements.add("transaction");
relevantElements.add("userTask");
relevantElements.add("isForCompensation");
}
@Override
public void addToCounts(Document dom) {
Node process = new BpmnInspector().getProcess(dom);
addNodeToCounts(process);
}
private void addNodeToCounts(Node node) {
// ignore text nodes
if (isTextNode(node)) {
return;
}
addToMap(node);
NodeList children = node.getChildNodes();
if (children != null) {
for (int i = 0; i < children.getLength(); i++) {
addNodeToCounts(children.item(i));
}
}
}
private boolean isTextNode(Node node) {
return node.getNodeType() == Node.TEXT_NODE;
}
private void addToMap(Node node) {
String nodeName = node.getLocalName();
if (isStrict && !relevantElements.contains(nodeName)) {
return;
}
if (elements.containsKey(nodeName)) {
AtomicInteger count = elements.get(nodeName);
count.incrementAndGet();
} else {
elements.put(nodeName, new AtomicInteger(1));
}
}
@Override
public void writeToCsv(Path file) {
try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(file,
Charset.defaultCharset()))) {
writer.println("element;number");
for (String key : elements.keySet()) {
AtomicInteger value = elements.get(key);
writer.println(key + ";" + value);
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
@Override
public Map<String, AtomicInteger> getElementNumbers() {
return Collections.unmodifiableMap(elements);
}
}
| Sort list of elements before serialization
Former-commit-id: 62eb03c109a04b5ba3eba3d3ecc508288a08acb2 | src/main/java/pete/metrics/adaptability/nodecounters/SimpleNodeCounter.java | Sort list of elements before serialization |
|
Java | mit | 2ae3bea79327a144f2a014d625faae9c75d7d2e2 | 0 | feltnerm/uwponopoly,feltnerm/uwponopoly,feltnerm/uwponopoly | /**
@author UWP_User
*/
import java.util.LinkedList;
import Config.Config;
import Player.Player;
public class Game implements runnable
{
private Thread gamethread;
private static int SPACES = 40;
private static int NUM_PLAYERS = 2;
private static int STARTING_CASH = 200;
private static int JAIL_FINE = 200;
private static int JAIL_FEE = 50;
private static boolean FREE_PARKING = false;
private static int GO_AMOUNT;
private static int INCOME_TAX_CASH;
private static float INCOME_TAX_PERCENT;
private boolean running = false;
private LinkedList<Player> players;
Config config;
public Game()
{
initPlayers();
}
public Game(Config config)
{
// Get configuration
this.config = config;
// Set defaults
this.SPACES = Integer.parseInt(config.get("SPACES"));
this.NUM_PLAYERS = Integer.parseInt(config.get("NUM_PLAYERS"));
this.STARTING_CASH = Integer.parseInt(config.get("STARTING_CASH"));
this.GO_AMOUNT = Integer.parseInt(config.get("GO_AMOUNT"));
this.INCOME_TAX_CASH = Integer.parseInt(config.get("INCOME_TAX_CASH"));
this.INCOME_TAX_PERCENT = Float.parseFloat(config.get("INCOME_TAX_PERCENT"));
this.JAIL_FINE = Integer.parseInt(config.get("JAIL_FINE"));
this.JAIL_FEE = Integer.parseInt(config.get("JAIL_FEE"));
this.FREE_PARKING = Boolean.parseBoolean(config.get("FREE_PARKING"));
initPlayers();
}
private void initPlayers()
{
for (int p = 0; p < this.NUM_PLAYERS; p++)
{
Player player = new Player();
this.players.add(p, player);
}
}
public void run() {
if (!this.running)
{
// run the game!
}
}
public void run_console() {
}
public void run_gui() {
}
}
| src/Game/Game.java | /**
@author UWP_User
*/
import java.util.LinkedList;
import Config.Config;
import Player.Player;
public class Game
{
private static int SPACES = 40;
private static int NUM_PLAYERS = 2;
private static int STARTING_CASH = 200;
private static int JAIL_FINE = 200;
private static int JAIL_FEE = 50;
private static boolean FREE_PARKING = false;
private static int GO_AMOUNT;
private static int INCOME_TAX_CASH;
private static float INCOME_TAX_PERCENT;
private boolean running = false;
private LinkedList<Player> players;
Config config;
public Game()
{
initPlayers();
}
public Game(Config config)
{
// Get configuration
this.config = config;
// Set defaults
this.SPACES = Integer.parseInt(config.get("SPACES"));
this.NUM_PLAYERS = Integer.parseInt(config.get("NUM_PLAYERS"));
this.STARTING_CASH = Integer.parseInt(config.get("STARTING_CASH"));
this.GO_AMOUNT = Integer.parseInt(config.get("GO_AMOUNT"));
this.INCOME_TAX_CASH = Integer.parseInt(config.get("INCOME_TAX_CASH"));
this.INCOME_TAX_PERCENT = Float.parseFloat(config.get("INCOME_TAX_PERCENT"));
this.JAIL_FINE = Integer.parseInt(config.get("JAIL_FINE"));
this.JAIL_FEE = Integer.parseInt(config.get("JAIL_FEE"));
this.FREE_PARKING = Boolean.parseBoolean(config.get("FREE_PARKING"));
initPlayers();
}
private void initPlayers()
{
for (int p = 0; p < this.NUM_PLAYERS; p++)
{
Player player = new Player();
this.players.add(p, player);
}
}
public void run() {
if (!this.running)
{
// run the game!
}
}
public void run_console() {
}
public void run_gui() {
}
}
| added gamethread
| src/Game/Game.java | added gamethread |
|
Java | mit | 3faae9a278d46fee72b92d40602fc316b381b55c | 0 | binaryoverload/FlareBot,FlareBot/FlareBot,weeryan17/FlareBot | package com.bwfcwalshy.flarebot;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Catch those dem errorz
* <br>
* Created by Arsen on 19.9.16..
*/
public class ErrorCatcher extends Filter<ILoggingEvent> {
private static final ExecutorService EXECUTOR = Executors.newCachedThreadPool();
@Override
public FilterReply decide(ILoggingEvent event) {
String msg = event.getFormattedMessage();
if(msg == null)
return FilterReply.NEUTRAL;
if (msg.startsWith("Received 40")) {
return FilterReply.DENY;
}
if (msg.startsWith("Attempt to send message on closed")) {
return FilterReply.DENY;
}
if (event.getMarker() != Markers.NO_ANNOUNCE
&& FlareBot.getInstance().getClient() != null
&& FlareBot.getInstance().getClient().isReady()
&& event.getLevel() == Level.ERROR) {
EXECUTOR.submit(() -> {
Throwable throwable = null;
if (event.getThrowableProxy() != null && event.getThrowableProxy() instanceof ThrowableProxy) {
throwable = ((ThrowableProxy) event.getThrowableProxy()).getThrowable();
}
if (throwable != null) {
MessageUtils.sendException(msg, throwable, FlareBot.getInstance().getUpdateChannel());
} else MessageUtils.sendMessage(msg, FlareBot.getInstance().getUpdateChannel());
});
}
return FilterReply.NEUTRAL;
}
}
| src/main/java/com/bwfcwalshy/flarebot/ErrorCatcher.java | package com.bwfcwalshy.flarebot;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Catch those dem errorz
* <br>
* Created by Arsen on 19.9.16..
*/
public class ErrorCatcher extends Filter<ILoggingEvent> {
private static final ExecutorService EXECUTOR = Executors.newCachedThreadPool();
@Override
public FilterReply decide(ILoggingEvent event) {
String msg = event.getFormattedMessage();
if (msg.startsWith("Received 40")) {
return FilterReply.DENY;
}
if (msg.startsWith("Attempt to send message on closed")) {
return FilterReply.DENY;
}
if (event.getMarker() != Markers.NO_ANNOUNCE
&& FlareBot.getInstance().getClient() != null
&& FlareBot.getInstance().getClient().isReady()
&& event.getLevel() == Level.ERROR) {
EXECUTOR.submit(() -> {
Throwable throwable = null;
if (event.getThrowableProxy() != null && event.getThrowableProxy() instanceof ThrowableProxy) {
throwable = ((ThrowableProxy) event.getThrowableProxy()).getThrowable();
}
if (throwable != null) {
MessageUtils.sendException(msg, throwable, FlareBot.getInstance().getUpdateChannel());
} else MessageUtils.sendMessage(msg, FlareBot.getInstance().getUpdateChannel());
});
}
return FilterReply.NEUTRAL;
}
}
| Fix ErrorCatcher.java
| src/main/java/com/bwfcwalshy/flarebot/ErrorCatcher.java | Fix ErrorCatcher.java |
|
Java | mit | 1d6ac985459bf376177ebeaa2453e213095e0b12 | 0 | tobiatesan/serleena-android,tobiatesan/serleena-android | ///////////////////////////////////////////////////////////////////////////////
//
// This file is part of Serleena.
//
// The MIT License (MIT)
//
// Copyright (C) 2015 Antonio Cavestro, Gabriele Pozzan, Matteo Lisotto,
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
/**
* Name: IExperienceSelectionView
* Package: com.hitchikers.serleena.presentation
* Author: Tobia Tesan <[email protected]>
*
* History:
* Version Programmer Changes
* 1.0 Tobia Tesan Creazione del file
*/
package com.kyloth.serleena.presentation;
import com.kyloth.serleena.model.IExperience;
/**
* E' l'interfaccia realizzata dalla Vista della schermata di selezione
* dell'esperienza.
*
* @use Viene utilizzato dal Presenter ExperienceSelectionPresenter per mantenere un riferimento alla vista associata, e comunicare con essa.
* @author Tobia Tesan <[email protected]>
* @version 1.0
* @since 1.0
*/
public interface IExperienceSelectionView {
/**
* Visualizza una lista di nomi di esperienze tra cui scegliere.
*
* @since 1.0
*/
void setExperiences(Iterable<IExperience> experiences);
/**
* Lega un Presenter alla vista.
*
* @since 1.0
*/
void attachPresenter(IExperienceSelectionPresenter presenter);
}
| serleena/app/src/main/java/com/kyloth/serleena/presentation/IExperienceSelectionView.java | ///////////////////////////////////////////////////////////////////////////////
//
// This file is part of Serleena.
//
// The MIT License (MIT)
//
// Copyright (C) 2015 Antonio Cavestro, Gabriele Pozzan, Matteo Lisotto,
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
/**
* Name: IExperienceSelectionView
* Package: com.hitchikers.serleena.presentation
* Author: Tobia Tesan <[email protected]>
*
* History:
* Version Programmer Changes
* 1.0 Tobia Tesan Creazione del file
*/
package com.kyloth.serleena.presentation;
/**
* E' l'interfaccia realizzata dalla Vista della schermata di selezione
* dell'esperienza.
*
* @use Viene utilizzato dal Presenter ExperienceSelectionPresenter per mantenere un riferimento alla vista associata, e comunicare con essa.
* @author Tobia Tesan <[email protected]>
* @version 1.0
* @since 1.0
*/
public interface IExperienceSelectionView {
/**
* Visualizza una lista di nomi di esperienze tra cui scegliere.
*
* @since 1.0
*/
void setList(Iterable<String> names);
/**
* Lega un Presenter alla vista.
*
* @since 1.0
*/
void attachPresenter(IExperienceSelectionPresenter presenter);
}
| PRSNT: Aggiungi IExperienceSelectionView.setExperiences()
Viene aggiunto setExperiences() in sostituzione di setList().
| serleena/app/src/main/java/com/kyloth/serleena/presentation/IExperienceSelectionView.java | PRSNT: Aggiungi IExperienceSelectionView.setExperiences() |
|
Java | mit | fa37f92bf7b1ee0ce2a8711ae8f438a8ea952a1c | 0 | fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg | package ua.com.fielden.platform.entity.query.generation.elements;
import ua.com.fielden.platform.entity.query.generation.DbVersion;
public class DateOf extends SingleOperandFunction {
public DateOf(final ISingleOperand operand, final DbVersion dbVersion) {
super(dbVersion, operand);
}
@Override
public String sql() {
switch (getDbVersion()) {
case H2:
return "CAST(" + getOperand().sql() + " AS DATE)";
case MSSQL:
return "DATEADD(dd, DATEDIFF(dd, 0, " + getOperand().sql() + "), 0)";
case POSTGRESQL:
return "DATE_TRUNC('day', " + getOperand().sql() + ")";
default:
throw new IllegalStateException("Function [" + getClass().getSimpleName() +"] is not yet implemented for RDBMS [" + getDbVersion() + "]!");
}
}
} | platform-dao/src/main/java/ua/com/fielden/platform/entity/query/generation/elements/DateOf.java | package ua.com.fielden.platform.entity.query.generation.elements;
import ua.com.fielden.platform.entity.query.generation.DbVersion;
public class DateOf extends SingleOperandFunction {
public DateOf(final ISingleOperand operand, final DbVersion dbVersion) {
super(dbVersion, operand);
}
@Override
public String sql() {
switch (getDbVersion()) {
case H2:
case MSSQL:
case POSTGRESQL:
return "DATE_PART('day', " + getOperand().sql() + ")";
default:
throw new IllegalStateException("Function [" + getClass().getSimpleName() +"] is not yet implemented for RDBMS [" + getDbVersion() + "]!");
}
}
} | Corrected.
git-svn-id: 1325a6c4fed28e15898c6416993928475140201d@4643 50ee8237-08a1-5d4c-b143-727193748607
| platform-dao/src/main/java/ua/com/fielden/platform/entity/query/generation/elements/DateOf.java | Corrected. |
|
Java | mit | 710341df788fe26d3df504147ab94e8259f44ff0 | 0 | CMP-Studio/react-native-push-notification,zo0r/react-native-push-notification,zo0r/react-native-push-notification,ErikMikkelson/react-native-push-notification,zo0r/react-native-push-notification,CMP-Studio/react-native-push-notification,ErikMikkelson/react-native-push-notification | package com.dieam.reactnativepushnotification.modules;
import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Random;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
public class RNPushNotificationHelper {
public static final String PREFERENCES_KEY = "RNPushNotification";
private static final long DEFAULT_VIBRATION = 1000L;
private static final String TAG = RNPushNotificationHelper.class.getSimpleName();
private Context mContext;
private final SharedPreferences mSharedPreferences;
public RNPushNotificationHelper(Application context) {
mContext = context;
mSharedPreferences = (SharedPreferences)context.getSharedPreferences(PREFERENCES_KEY, Context.MODE_PRIVATE);
}
public Class getMainActivityClass() {
String packageName = mContext.getPackageName();
Intent launchIntent = mContext.getPackageManager().getLaunchIntentForPackage(packageName);
String className = launchIntent.getComponent().getClassName();
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
private AlarmManager getAlarmManager() {
return (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
}
private PendingIntent getScheduleNotificationIntent(Bundle bundle) {
int notificationID = Integer.parseInt(bundle.getString("id"));
Intent notificationIntent = new Intent(mContext, RNPushNotificationPublisher.class);
notificationIntent.putExtra(RNPushNotificationPublisher.NOTIFICATION_ID, notificationID);
notificationIntent.putExtras(bundle);
return PendingIntent.getBroadcast(mContext, notificationID, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public void sendNotificationScheduled(Bundle bundle) {
Class intentClass = getMainActivityClass();
if (intentClass == null) {
Log.e("RNPushNotification", "No activity class found for the notification");
return;
}
if (bundle.getString("message") == null) {
Log.e("RNPushNotification", "No message specified for the notification");
return;
}
if(bundle.getString("id") == null) {
Log.e("RNPushNotification", "No notification ID specified for the notification");
return;
}
double fireDate = bundle.getDouble("fireDate");
if (fireDate == 0) {
Log.e("RNPushNotification", "No date specified for the scheduled notification");
return;
}
storeNotificationToPreferences(bundle);
sendNotificationScheduledCore(bundle);
}
public void sendNotificationScheduledCore(Bundle bundle) {
long fireDate = (long)bundle.getDouble("fireDate");
// If the fireDate is in past, this will fire immediately and show the
// notification to the user
PendingIntent pendingIntent = getScheduleNotificationIntent(bundle);
Log.d("RNPushNotification", String.format("Setting a notification with id %s at time %s",
bundle.getString("id"), Long.toString(fireDate)));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getAlarmManager().setExact(AlarmManager.RTC_WAKEUP, fireDate, pendingIntent);
} else {
getAlarmManager().set(AlarmManager.RTC_WAKEUP, fireDate, pendingIntent);
}
}
private void storeNotificationToPreferences(Bundle bundle) {
RNPushNotificationAttributes notificationAttributes = new RNPushNotificationAttributes();
notificationAttributes.fromBundle(bundle);
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(notificationAttributes.getId(), notificationAttributes.toJson().toString());
commitPreferences(editor);
}
private void commitPreferences(SharedPreferences.Editor editor) {
if (Build.VERSION.SDK_INT < 9) {
editor.commit();
} else {
editor.apply();
}
}
public void sendNotification(Bundle bundle) {
try {
Class intentClass = getMainActivityClass();
if (intentClass == null) {
Log.e("RNPushNotification", "No activity class found for the notification");
return;
}
if (bundle.getString("message") == null) {
Log.e("RNPushNotification", "No message specified for the notification");
return;
}
if(bundle.getString("id") == null) {
Log.e("RNPushNotification", "No notification ID specified for the notification");
return;
}
Resources res = mContext.getResources();
String packageName = mContext.getPackageName();
String title = bundle.getString("title");
if (title == null) {
ApplicationInfo appInfo = mContext.getApplicationInfo();
title = mContext.getPackageManager().getApplicationLabel(appInfo).toString();
}
NotificationCompat.Builder notification = new NotificationCompat.Builder(mContext)
.setContentTitle(title)
.setTicker(bundle.getString("ticker"))
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(bundle.getBoolean("autoCancel", true));
String group = bundle.getString("group");
if (group != null) {
notification.setGroup(group);
}
notification.setContentText(bundle.getString("message"));
String largeIcon = bundle.getString("largeIcon");
String subText = bundle.getString("subText");
if (subText != null) {
notification.setSubText(subText);
}
String numberString = bundle.getString("number");
if ( numberString != null ) {
notification.setNumber(Integer.parseInt(numberString));
}
int smallIconResId;
int largeIconResId;
String smallIcon = bundle.getString("smallIcon");
if (smallIcon != null) {
smallIconResId = res.getIdentifier(smallIcon, "mipmap", packageName);
} else {
smallIconResId = res.getIdentifier("ic_notification", "mipmap", packageName);
}
if (smallIconResId == 0) {
smallIconResId = res.getIdentifier("ic_launcher", "mipmap", packageName);
if (smallIconResId == 0) {
smallIconResId = android.R.drawable.ic_dialog_info;
}
}
if (largeIcon != null) {
largeIconResId = res.getIdentifier(largeIcon, "mipmap", packageName);
} else {
largeIconResId = res.getIdentifier("ic_launcher", "mipmap", packageName);
}
Bitmap largeIconBitmap = BitmapFactory.decodeResource(res, largeIconResId);
if (largeIconResId != 0 && (largeIcon != null || android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP)) {
notification.setLargeIcon(largeIconBitmap);
}
notification.setSmallIcon(smallIconResId);
String bigText = bundle.getString("bigText");
if (bigText == null) {
bigText = bundle.getString("message");
}
notification.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText));
Intent intent = new Intent(mContext, intentClass);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
bundle.putBoolean("userInteraction", true);
intent.putExtra("notification", bundle);
if (!bundle.containsKey("playSound") || bundle.getBoolean("playSound")) {
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
String soundName = bundle.getString("sound");
if(soundName != null) {
if(!"default".equalsIgnoreCase(soundName)) {
soundUri = Uri.parse(soundName);
}
}
notification.setSound(soundUri);
}
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notification.setCategory(NotificationCompat.CATEGORY_CALL);
String color = bundle.getString("color");
if (color != null) {
notification.setColor(Color.parseColor(color));
}
}
int notificationID = Integer.parseInt(bundle.getString("id"));
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, notificationID, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notification.setContentIntent(pendingIntent);
if (!bundle.containsKey("vibrate") || bundle.getBoolean("vibrate")) {
long vibration = bundle.containsKey("vibration") ? (long) bundle.getDouble("vibration") : DEFAULT_VIBRATION;
if (vibration == 0)
vibration = DEFAULT_VIBRATION;
notification.setVibrate(new long[]{0, vibration});
}
JSONArray actionsArray = null;
try {
actionsArray = bundle.getString("actions") != null ? new JSONArray(bundle.getString("actions")) : null;
} catch (JSONException e) {
Log.e("RNPushNotification", "Exception while converting actions to JSON object.", e);
}
if (actionsArray != null) {
// No icon for now. The icon value of 0 shows no icon.
int icon = 0;
// Add button for each actions.
for (int i = 0; i < actionsArray.length(); i++) {
String action = null;
try {
action = actionsArray.getString(i);
} catch (JSONException e) {
Log.e("RNPushNotification", "Exception while getting action from actionsArray.", e);
continue;
}
Intent actionIntent = new Intent();
actionIntent.setAction(action);
// Add "action" for later identifying which button gets pressed.
bundle.putString("action", action);
actionIntent.putExtra("notification", bundle);
PendingIntent pendingActionIntent = PendingIntent.getBroadcast(mContext, notificationID, actionIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.addAction(icon, action, pendingActionIntent);
}
}
Notification info = notification.build();
info.defaults |= Notification.DEFAULT_LIGHTS;
if(mSharedPreferences.getString(Integer.toString(notificationID), null) != null) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.remove(Integer.toString(notificationID));
commitPreferences(editor);
}
if (bundle.containsKey("tag")) {
String tag = bundle.getString("tag");
notificationManager.notify(tag, notificationID, info);
} else {
notificationManager.notify(notificationID, info);
}
// Can't use setRepeating for recurring notifications because setRepeating
// is inexact by default starting API 19 and the notifications are not fired
// at the exact time. During testing, it was found that notifications could
// late by many minutes.
this.scheduleNextNotificationIfRepeating(bundle);
} catch (Exception e) {
Log.e(TAG, "failed to send push notification", e);
}
}
private void scheduleNextNotificationIfRepeating(Bundle bundle) {
String repeatType = bundle.getString("repeatType");
long repeatTime = (long)bundle.getDouble("repeatTime");
if(repeatType != null) {
long fireDate = (long)bundle.getDouble("fireDate");
int msecInAMinute = 60000;
boolean validRepeatType = Arrays.asList("time", "week", "day", "hour", "minute").contains(repeatType);
// Sanity checks
if (!validRepeatType) {
Log.w("RNPushNotification", String.format("Invalid repeatType specified as %s", repeatType));
return;
}
if (repeatType == "time" && repeatTime <= 0) {
Log.w("RNPushNotification", "repeatType specified as time but no repeatTime " +
"has been mentioned");
return;
}
long newFireDate = 0;
switch (repeatType) {
case "time" :
newFireDate = fireDate + repeatTime;
break;
case "week":
newFireDate = fireDate + 7 * 24 * 60 * msecInAMinute;
break;
case "day":
newFireDate = fireDate + 24 * 60 * msecInAMinute;
break;
case "hour":
newFireDate = fireDate + 60 * msecInAMinute;
break;
case "minute":
newFireDate = fireDate + msecInAMinute;
break;
}
// Sanity check, should never happen
if(newFireDate != 0) {
Log.d("RNPushNotification", String.format("Repeating notification with id %s at time %s",
bundle.getString("id"), Long.toString(newFireDate)));
bundle.putDouble("fireDate", newFireDate);
this.sendNotificationScheduled(bundle);
}
}
}
public void cancelAll() {
Set<String> ids = mSharedPreferences.getAll().keySet();
for (String id: ids) {
this.cancelNotification(id);
}
}
public void cancelNotification(String notificationIDString) {
// Sanity check. Only delete if it has been scheduled
if (mSharedPreferences.contains(notificationIDString)) {
Log.d("RNPushNotification", "Cancelling notification with ID " + notificationIDString);
NotificationManager notificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Integer.parseInt(notificationIDString));
Bundle b = new Bundle();
b.putString("id", notificationIDString);
getAlarmManager().cancel(getScheduleNotificationIntent(b));
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.remove(notificationIDString);
commitPreferences(editor);
} else {
Log.d("RNPushNotification", "Didn't find a notification with " + notificationIDString +
" while cancelling a local notification");
}
}
}
| android/src/main/java/com/dieam/reactnativepushnotification/modules/RNPushNotificationHelper.java | package com.dieam.reactnativepushnotification.modules;
import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Random;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
public class RNPushNotificationHelper {
public static final String PREFERENCES_KEY = "RNPushNotification";
private static final long DEFAULT_VIBRATION = 1000L;
private static final String TAG = RNPushNotificationHelper.class.getSimpleName();
private Context mContext;
private final SharedPreferences mSharedPreferences;
public RNPushNotificationHelper(Application context) {
mContext = context;
mSharedPreferences = (SharedPreferences)context.getSharedPreferences(PREFERENCES_KEY, Context.MODE_PRIVATE);
}
public Class getMainActivityClass() {
String packageName = mContext.getPackageName();
Intent launchIntent = mContext.getPackageManager().getLaunchIntentForPackage(packageName);
String className = launchIntent.getComponent().getClassName();
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
private AlarmManager getAlarmManager() {
return (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
}
private PendingIntent getScheduleNotificationIntent(Bundle bundle) {
int notificationID = Integer.parseInt(bundle.getString("id"));
Intent notificationIntent = new Intent(mContext, RNPushNotificationPublisher.class);
notificationIntent.putExtra(RNPushNotificationPublisher.NOTIFICATION_ID, notificationID);
notificationIntent.putExtras(bundle);
return PendingIntent.getBroadcast(mContext, notificationID, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public void sendNotificationScheduled(Bundle bundle) {
Class intentClass = getMainActivityClass();
if (intentClass == null) {
Log.e("RNPushNotification", "No activity class found for the notification");
return;
}
if (bundle.getString("message") == null) {
Log.e("RNPushNotification", "No message specified for the notification");
return;
}
if(bundle.getString("id") == null) {
Log.e("RNPushNotification", "No notification ID specified for the notification");
return;
}
double fireDate = bundle.getDouble("fireDate");
if (fireDate == 0) {
Log.e("RNPushNotification", "No date specified for the scheduled notification");
return;
}
storeNotificationToPreferences(bundle);
sendNotificationScheduledCore(bundle);
}
public void sendNotificationScheduledCore(Bundle bundle) {
long fireDate = (long)bundle.getDouble("fireDate");
// If the fireDate is in past, this will fire immediately and show the
// notification to the user
PendingIntent pendingIntent = getScheduleNotificationIntent(bundle);
Log.d("RNPushNotification", String.format("Setting a notification with id %s at time %s",
bundle.getString("id"), Long.toString(fireDate)));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getAlarmManager().setExact(AlarmManager.RTC_WAKEUP, fireDate, pendingIntent);
} else {
getAlarmManager().set(AlarmManager.RTC_WAKEUP, fireDate, pendingIntent);
}
}
private void storeNotificationToPreferences(Bundle bundle) {
RNPushNotificationAttributes notificationAttributes = new RNPushNotificationAttributes();
notificationAttributes.fromBundle(bundle);
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(notificationAttributes.getId(), notificationAttributes.toJson().toString());
commitPreferences(editor);
}
private void commitPreferences(SharedPreferences.Editor editor) {
if (Build.VERSION.SDK_INT < 9) {
editor.commit();
} else {
editor.apply();
}
}
public void sendNotification(Bundle bundle) {
try {
Class intentClass = getMainActivityClass();
if (intentClass == null) {
Log.e("RNPushNotification", "No activity class found for the notification");
return;
}
if (bundle.getString("message") == null) {
Log.e("RNPushNotification", "No message specified for the notification");
return;
}
if(bundle.getString("id") == null) {
Log.e("RNPushNotification", "No notification ID specified for the notification");
return;
}
Resources res = mContext.getResources();
String packageName = mContext.getPackageName();
String title = bundle.getString("title");
if (title == null) {
ApplicationInfo appInfo = mContext.getApplicationInfo();
title = mContext.getPackageManager().getApplicationLabel(appInfo).toString();
}
NotificationCompat.Builder notification = new NotificationCompat.Builder(mContext)
.setContentTitle(title)
.setTicker(bundle.getString("ticker"))
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(bundle.getBoolean("autoCancel", true));
String group = bundle.getString("group");
if (group != null) {
notification.setGroup(group);
}
notification.setContentText(bundle.getString("message"));
String largeIcon = bundle.getString("largeIcon");
String subText = bundle.getString("subText");
if (subText != null) {
notification.setSubText(subText);
}
String numberString = bundle.getString("number");
if ( numberString != null ) {
notification.setNumber(Integer.parseInt(numberString));
}
int smallIconResId;
int largeIconResId;
String smallIcon = bundle.getString("smallIcon");
if (smallIcon != null) {
smallIconResId = res.getIdentifier(smallIcon, "mipmap", packageName);
} else {
smallIconResId = res.getIdentifier("ic_notification", "mipmap", packageName);
}
if (smallIconResId == 0) {
smallIconResId = res.getIdentifier("ic_launcher", "mipmap", packageName);
if (smallIconResId == 0) {
smallIconResId = android.R.drawable.ic_dialog_info;
}
}
if (largeIcon != null) {
largeIconResId = res.getIdentifier(largeIcon, "mipmap", packageName);
} else {
largeIconResId = res.getIdentifier("ic_launcher", "mipmap", packageName);
}
Bitmap largeIconBitmap = BitmapFactory.decodeResource(res, largeIconResId);
if (largeIconResId != 0 && (largeIcon != null || android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP)) {
notification.setLargeIcon(largeIconBitmap);
}
notification.setSmallIcon(smallIconResId);
String bigText = bundle.getString("bigText");
if (bigText == null) {
bigText = bundle.getString("message");
}
notification.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText));
Intent intent = new Intent(mContext, intentClass);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
bundle.putBoolean("userInteraction", true);
intent.putExtra("notification", bundle);
if (!bundle.containsKey("playSound") || bundle.getBoolean("playSound")) {
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
String soundName = bundle.getString("sound");
if(soundName != null) {
if(!"default".equalsIgnoreCase(soundName)) {
soundUri = Uri.parse(soundName);
}
}
notification.setSound(soundUri);
}
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notification.setCategory(NotificationCompat.CATEGORY_CALL);
String color = bundle.getString("color");
if (color != null) {
notification.setColor(Color.parseColor(color));
}
}
int notificationID = Integer.parseInt(bundle.getString("id"));
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, notificationID, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notification.setContentIntent(pendingIntent);
if (!bundle.containsKey("vibrate") || bundle.getBoolean("vibrate")) {
long vibration = bundle.containsKey("vibration") ? (long) bundle.getDouble("vibration") : DEFAULT_VIBRATION;
if (vibration == 0)
vibration = DEFAULT_VIBRATION;
notification.setVibrate(new long[]{0, vibration});
}
JSONArray actionsArray = null;
try {
actionsArray = new JSONArray(bundle.getString("actions"));
} catch (JSONException e) {
Log.e("RNPushNotification", "Exception while converting actions to JSON object.", e);
}
if (actionsArray != null) {
// No icon for now. The icon value of 0 shows no icon.
int icon = 0;
// Add button for each actions.
for (int i = 0; i < actionsArray.length(); i++) {
String action = null;
try {
action = actionsArray.getString(i);
} catch (JSONException e) {
Log.e("RNPushNotification", "Exception while getting action from actionsArray.", e);
continue;
}
Intent actionIntent = new Intent();
actionIntent.setAction(action);
// Add "action" for later identifying which button gets pressed.
bundle.putString("action", action);
actionIntent.putExtra("notification", bundle);
PendingIntent pendingActionIntent = PendingIntent.getBroadcast(mContext, notificationID, actionIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.addAction(icon, action, pendingActionIntent);
}
}
Notification info = notification.build();
info.defaults |= Notification.DEFAULT_LIGHTS;
if(mSharedPreferences.getString(Integer.toString(notificationID), null) != null) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.remove(Integer.toString(notificationID));
commitPreferences(editor);
}
if (bundle.containsKey("tag")) {
String tag = bundle.getString("tag");
notificationManager.notify(tag, notificationID, info);
} else {
notificationManager.notify(notificationID, info);
}
// Can't use setRepeating for recurring notifications because setRepeating
// is inexact by default starting API 19 and the notifications are not fired
// at the exact time. During testing, it was found that notifications could
// late by many minutes.
this.scheduleNextNotificationIfRepeating(bundle);
} catch (Exception e) {
Log.e(TAG, "failed to send push notification", e);
}
}
private void scheduleNextNotificationIfRepeating(Bundle bundle) {
String repeatType = bundle.getString("repeatType");
long repeatTime = (long)bundle.getDouble("repeatTime");
if(repeatType != null) {
long fireDate = (long)bundle.getDouble("fireDate");
int msecInAMinute = 60000;
boolean validRepeatType = Arrays.asList("time", "week", "day", "hour", "minute").contains(repeatType);
// Sanity checks
if (!validRepeatType) {
Log.w("RNPushNotification", String.format("Invalid repeatType specified as %s", repeatType));
return;
}
if (repeatType == "time" && repeatTime <= 0) {
Log.w("RNPushNotification", "repeatType specified as time but no repeatTime " +
"has been mentioned");
return;
}
long newFireDate = 0;
switch (repeatType) {
case "time" :
newFireDate = fireDate + repeatTime;
break;
case "week":
newFireDate = fireDate + 7 * 24 * 60 * msecInAMinute;
break;
case "day":
newFireDate = fireDate + 24 * 60 * msecInAMinute;
break;
case "hour":
newFireDate = fireDate + 60 * msecInAMinute;
break;
case "minute":
newFireDate = fireDate + msecInAMinute;
break;
}
// Sanity check, should never happen
if(newFireDate != 0) {
Log.d("RNPushNotification", String.format("Repeating notification with id %s at time %s",
bundle.getString("id"), Long.toString(newFireDate)));
bundle.putDouble("fireDate", newFireDate);
this.sendNotificationScheduled(bundle);
}
}
}
public void cancelAll() {
Set<String> ids = mSharedPreferences.getAll().keySet();
for (String id: ids) {
this.cancelNotification(id);
}
}
public void cancelNotification(String notificationIDString) {
// Sanity check. Only delete if it has been scheduled
if (mSharedPreferences.contains(notificationIDString)) {
Log.d("RNPushNotification", "Cancelling notification with ID " + notificationIDString);
NotificationManager notificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Integer.parseInt(notificationIDString));
Bundle b = new Bundle();
b.putString("id", notificationIDString);
getAlarmManager().cancel(getScheduleNotificationIntent(b));
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.remove(notificationIDString);
commitPreferences(editor);
} else {
Log.d("RNPushNotification", "Didn't find a notification with " + notificationIDString +
" while cancelling a local notification");
}
}
}
| Fix minor bug in handling notification actions
| android/src/main/java/com/dieam/reactnativepushnotification/modules/RNPushNotificationHelper.java | Fix minor bug in handling notification actions |
|
Java | epl-1.0 | 2af95f95edc9d9a4fdccd5f69d2422b77fb45b3d | 0 | debrief/limpet,pecko/limpet,pecko/limpet,debrief/limpet,debrief/limpet,pecko/limpet | package info.limpet.data;
import static javax.measure.unit.NonSI.HOUR;
import static javax.measure.unit.NonSI.KILOMETERS_PER_HOUR;
import static javax.measure.unit.NonSI.KILOMETRES_PER_HOUR;
import static javax.measure.unit.NonSI.MINUTE;
import static javax.measure.unit.SI.KILO;
import static javax.measure.unit.SI.METRE;
import static javax.measure.unit.SI.METRES_PER_SECOND;
import info.limpet.ICollection;
import info.limpet.ICommand;
import info.limpet.IContext;
import info.limpet.IOperation;
import info.limpet.IQuantityCollection;
import info.limpet.IStore;
import info.limpet.IStore.IStoreItem;
import info.limpet.ITemporalQuantityCollection;
import info.limpet.data.impl.MockContext;
import info.limpet.data.impl.ObjectCollection;
import info.limpet.data.impl.QuantityCollection;
import info.limpet.data.impl.TemporalQuantityCollection;
import info.limpet.data.impl.samples.SampleData;
import info.limpet.data.impl.samples.StockTypes;
import info.limpet.data.impl.samples.StockTypes.NonTemporal.Angle_Degrees;
import info.limpet.data.impl.samples.StockTypes.Temporal.Speed_Kts;
import info.limpet.data.operations.AddQuantityOperation;
import info.limpet.data.operations.CollectionComplianceTests;
import info.limpet.data.operations.DivideQuantityOperation;
import info.limpet.data.operations.MultiplyQuantityOperation;
import info.limpet.data.operations.SimpleMovingAverageOperation;
import info.limpet.data.operations.SubtractQuantityOperation;
import info.limpet.data.operations.UnitConversionOperation;
import info.limpet.data.operations.UnitaryMathOperation;
import info.limpet.data.operations.admin.OperationsLibrary;
import info.limpet.data.store.InMemoryStore;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.measure.Measurable;
import javax.measure.Measure;
import javax.measure.converter.UnitConverter;
import javax.measure.quantity.Angle;
import javax.measure.quantity.Dimensionless;
import javax.measure.quantity.Duration;
import javax.measure.quantity.Length;
import javax.measure.quantity.Quantity;
import javax.measure.quantity.Velocity;
import javax.measure.unit.Unit;
import junit.framework.TestCase;
public class TestOperations extends TestCase
{
private IContext context = new MockContext();
@SuppressWarnings(
{ "rawtypes", "unchecked" })
public void testInterpolateTests()
{
// place to store results data
InMemoryStore store = new SampleData().getData(10);
// ok, let's try one that works
List<IStoreItem> selection = new ArrayList<IStoreItem>();
// ///////////////
// TEST INVALID PERMUTATIONS
// ///////////////
ICollection speed_good_1 = (ICollection) store.get(SampleData.SPEED_ONE);
ICollection speed_good_2 = (ICollection) store.get(SampleData.SPEED_TWO);
ICollection speed_longer = (ICollection) store
.get(SampleData.SPEED_THREE_LONGER);
selection.add(speed_good_1);
selection.add(speed_longer);
Collection<ICommand<ICollection>> actions = new AddQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("correct number of actions returned", 1, actions.size());
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
actions = new AddQuantityOperation().actionsFor(selection, store, context);
assertEquals("correct number of actions returned", 2, actions.size());
ICommand<?> addAction = actions.iterator().next();
assertNotNull("found action", addAction);
}
public void testTrig()
{
// prepare some data
Speed_Kts speedData = new StockTypes.Temporal.Speed_Kts("speed");
speedData.add(100, 23);
speedData.add(200, 44);
Angle_Degrees angleData = new StockTypes.NonTemporal.Angle_Degrees("degs");
angleData.add(200d);
angleData.add(123d);
StockTypes.Temporal.Angle_Degrees temporalAngleData = new StockTypes.Temporal.Angle_Degrees(
"degs", null);
temporalAngleData.add(1000, 200d);
temporalAngleData.add(3000, 123d);
temporalAngleData.add(4000, 13d);
List<ICollection> selection = new ArrayList<ICollection>();
InMemoryStore store = new InMemoryStore();
HashMap<String, List<IOperation<?>>> ops = OperationsLibrary
.getOperations();
List<IOperation<?>> arith = ops.get(OperationsLibrary.ARITHMETIC);
// ok, now find the trig op
Iterator<IOperation<?>> iter = arith.iterator();
IOperation<ICollection> sinOp = null;
IOperation<ICollection> cosOp = null;
while (iter.hasNext())
{
IOperation<?> thisO = (IOperation<?>) iter.next();
if (thisO instanceof UnitaryMathOperation)
{
UnitaryMathOperation umo = (UnitaryMathOperation) thisO;
if (umo.getName().equals("Sin"))
{
sinOp = umo;
}
if (umo.getName().equals("Cos"))
{
cosOp = umo;
}
}
}
assertNotNull("check we found it", sinOp);
// ok, try it with empty data
Collection<ICommand<ICollection>> validOps = sinOp.actionsFor(selection,
null, null);
assertEquals("null for empty selection", 0, validOps.size());
// add some speed data
selection.add(speedData);
// ok, try it with empty data
validOps = sinOp.actionsFor(selection, store, null);
assertEquals("empty for invalid selection", 0, validOps.size());
// add some valid data
selection.add(angleData);
// ok, try it with empty data
validOps = sinOp.actionsFor(selection, store, null);
assertEquals("empty for invalid selection", 0, validOps.size());
// ok, try it with empty data
validOps = cosOp.actionsFor(selection, store, null);
assertEquals(" cos also empty for invalid selection", 0, validOps.size());
// and remove the speed data
selection.remove(speedData);
// ok, try it with empty data
validOps = sinOp.actionsFor(selection, store, context);
assertEquals("non-empty for valid selection", 1, validOps.size());
ICommand<ICollection> theOp = validOps.iterator().next();
theOp.execute();
assertEquals("has new dataset", 1, store.size());
ICollection output = theOp.getOutputs().iterator().next();
// check the size
assertEquals("correct size", 2, output.size());
// check data type
assertTrue("isn't temporal", !output.isTemporal());
assertTrue("is quantity", output.isQuantity());
// ok, try it temporal data
selection.remove(angleData);
selection.add(temporalAngleData);
validOps = sinOp.actionsFor(selection, store, context);
assertEquals("non-empty for valid selection", 1, validOps.size());
theOp = validOps.iterator().next();
theOp.execute();
assertEquals("has new dataset", 2, store.size());
output = theOp.getOutputs().iterator().next();
// check the size
assertEquals("correct size", 3, output.size());
// check data type
assertTrue("isn't temporal", output.isTemporal());
}
public void testAppliesTo()
{
// the units for this measurement
Unit<Velocity> kmh = KILO(METRE).divide(HOUR).asType(Velocity.class);
Unit<Velocity> kmm = KILO(METRE).divide(MINUTE).asType(Velocity.class);
Unit<Length> m = (METRE).asType(Length.class);
// the target collection
QuantityCollection<Velocity> speed_good_1 = new QuantityCollection<Velocity>(
"Speed 1", kmh);
QuantityCollection<Velocity> speed_good_2 = new QuantityCollection<Velocity>(
"Speed 2", kmh);
QuantityCollection<Velocity> speed_longer = new QuantityCollection<Velocity>(
"Speed 3", kmh);
QuantityCollection<Velocity> speed_diff_units = new QuantityCollection<Velocity>(
"Speed 4", kmm);
QuantityCollection<Length> len1 = new QuantityCollection<Length>(
"Length 1", m);
TemporalQuantityCollection<Velocity> temporal_speed_1 = new TemporalQuantityCollection<Velocity>(
"Speed 5", kmh);
TemporalQuantityCollection<Velocity> temporal_speed_2 = new TemporalQuantityCollection<Velocity>(
"Speed 6", kmh);
ObjectCollection<String> string_1 = new ObjectCollection<>("strings 1");
ObjectCollection<String> string_2 = new ObjectCollection<>("strings 2");
for (int i = 1; i <= 10; i++)
{
// create a measurement
double thisSpeed = i * 2;
Measurable<Velocity> speedVal1 = Measure.valueOf(thisSpeed, kmh);
Measurable<Velocity> speedVal2 = Measure.valueOf(thisSpeed * 2, kmh);
Measurable<Velocity> speedVal3 = Measure.valueOf(thisSpeed / 2, kmh);
Measurable<Velocity> speedVal4 = Measure.valueOf(thisSpeed / 2, kmm);
Measurable<Length> lenVal1 = Measure.valueOf(thisSpeed / 2, m);
// store the measurements
speed_good_1.add(speedVal1);
speed_good_2.add(speedVal2);
speed_longer.add(speedVal3);
speed_diff_units.add(speedVal4);
temporal_speed_1.add(i, speedVal2);
temporal_speed_2.add(i, speedVal3);
len1.add(lenVal1);
string_1.add(i + " ");
string_2.add(i + "a ");
}
Measurable<Velocity> speedVal3a = Measure.valueOf(2, kmh);
speed_longer.add(speedVal3a);
List<IStoreItem> selection = new ArrayList<IStoreItem>();
CollectionComplianceTests testOp = new CollectionComplianceTests();
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
assertTrue("all same dim", testOp.allEqualDimensions(selection));
assertTrue("all same units", testOp.allEqualUnits(selection));
assertTrue("all same length", testOp.allEqualLength(selection));
assertTrue("all quantities", testOp.allQuantity(selection));
assertFalse("all temporal", testOp.allTemporal(selection));
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
selection.add(speed_diff_units);
assertTrue("all same dim", testOp.allEqualDimensions(selection));
assertFalse("all same units", testOp.allEqualUnits(selection));
assertTrue("all same length", testOp.allEqualLength(selection));
assertTrue("all quantities", testOp.allQuantity(selection));
assertFalse("all temporal", testOp.allTemporal(selection));
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
selection.add(len1);
assertFalse("all same dim", testOp.allEqualDimensions(selection));
assertFalse("all same units", testOp.allEqualUnits(selection));
assertTrue("all same length", testOp.allEqualLength(selection));
assertTrue("all quantities", testOp.allQuantity(selection));
assertFalse("all temporal", testOp.allTemporal(selection));
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
selection.add(speed_longer);
assertTrue("all same dim", testOp.allEqualDimensions(selection));
assertTrue("all same units", testOp.allEqualUnits(selection));
assertFalse("all same length", testOp.allEqualLength(selection));
assertTrue("all quantities", testOp.allQuantity(selection));
assertFalse("all temporal", testOp.allTemporal(selection));
selection.clear();
selection.add(temporal_speed_1);
selection.add(temporal_speed_2);
assertTrue("all same dim", testOp.allEqualDimensions(selection));
assertTrue("all same units", testOp.allEqualUnits(selection));
assertTrue("all same length", testOp.allEqualLength(selection));
assertTrue("all quantities", testOp.allQuantity(selection));
assertTrue("all temporal", testOp.allTemporal(selection));
selection.clear();
selection.add(temporal_speed_1);
selection.add(string_1);
assertFalse("all same dim", testOp.allEqualDimensions(selection));
assertFalse("all same units", testOp.allEqualUnits(selection));
assertTrue("all same length", testOp.allEqualLength(selection));
assertFalse("all quantities", testOp.allQuantity(selection));
assertFalse("all temporal", testOp.allTemporal(selection));
selection.clear();
selection.add(string_1);
selection.add(string_1);
assertFalse("all same dim", testOp.allEqualDimensions(selection));
assertFalse("all same units", testOp.allEqualUnits(selection));
assertTrue("all same length", testOp.allEqualLength(selection));
assertTrue("all non quantities", testOp.allNonQuantity(selection));
assertFalse("all temporal", testOp.allTemporal(selection));
// ok, let's try one that works
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
InMemoryStore store = new InMemoryStore();
assertEquals("store empty", 0, store.size());
@SuppressWarnings(
{ "unchecked", "rawtypes" })
Collection<ICommand<ICollection>> actions = new AddQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("correct number of actions returned", 1, actions.size());
ICommand<?> addAction = actions.iterator().next();
addAction.execute();
assertEquals("new collection added to store", 1, store.size());
ICollection firstItem = (ICollection) store.iterator().next();
ICommand<?> precedent = firstItem.getPrecedent();
assertNotNull("has precedent", precedent);
assertEquals("Correct name",
"Add numeric values in provided series (indexed)", precedent.getName());
List<? extends IStoreItem> inputs = precedent.getInputs();
assertEquals("Has both precedents", 2, inputs.size());
Iterator<? extends IStoreItem> iIter = inputs.iterator();
while (iIter.hasNext())
{
ICollection thisC = (ICollection) iIter.next();
List<ICommand<?>> deps = thisC.getDependents();
assertEquals("has a depedent", 1, deps.size());
Iterator<ICommand<?>> dIter = deps.iterator();
while (dIter.hasNext())
{
ICommand<?> iCommand = dIter.next();
assertEquals("Correct dependent", precedent, iCommand);
}
}
List<? extends IStoreItem> outputs = precedent.getOutputs();
assertEquals("Has both dependents", 1, outputs.size());
Iterator<? extends IStoreItem> oIter = outputs.iterator();
while (oIter.hasNext())
{
ICollection thisC = (ICollection) oIter.next();
ICommand<?> dep = thisC.getPrecedent();
assertNotNull("has a depedent", dep);
assertEquals("Correct dependent", precedent, dep);
}
}
public void testDimensionlessMultiply()
{
// place to store results data
InMemoryStore store = new SampleData().getData(10);
// ok, let's try one that works
List<IStoreItem> selection = new ArrayList<IStoreItem>();
// ///////////////
// TEST INVALID PERMUTATIONS
// ///////////////
ICollection speed_good_1 = (ICollection) store.get(SampleData.SPEED_ONE);
ICollection speed_good_2 = (ICollection) store.get(SampleData.SPEED_TWO);
ICollection speed_irregular = (ICollection) store
.get(SampleData.SPEED_IRREGULAR2);
ICollection string_1 = (ICollection) store.get(SampleData.STRING_ONE);
ICollection len1 = (ICollection) store.get(SampleData.LENGTH_ONE);
ICollection factor = (ICollection) store
.get(SampleData.FLOATING_POINT_FACTOR);
selection.clear();
selection.add(speed_good_1);
selection.add(string_1);
Collection<ICommand<IStoreItem>> commands = new MultiplyQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("invalid collections - not both quantities", 0,
commands.size());
selection.clear();
selection.add(speed_good_1);
selection.add(len1);
commands = new MultiplyQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid collections - both quantities", 1, commands.size());
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
store.clear();
assertEquals("store empty", 0, store.size());
commands = new MultiplyQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid collections - both speeds", 1, commands.size());
// //////////////////////////
// now test valid collections
// /////////////////////////
selection.clear();
selection.add(speed_good_1);
selection.add(factor);
assertEquals("store empty", 0, store.size());
commands = new MultiplyQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid collections - one is singleton", 1, commands.size());
ICommand<IStoreItem> command = commands.iterator().next();
// test actions has single item: "Multiply series by constant"
assertEquals("correct name", "Multiply series", command.getName());
// apply action
command.execute();
// test store has a new item in it
assertEquals("store not empty", 1, store.size());
ICollection newS = (ICollection) store
.get("Product of Speed One Time, Floating point factor");
// test results is same length as thisSpeed
assertEquals("correct size", 10, newS.size());
selection.clear();
selection.add(speed_good_1);
selection.add(factor);
store.clear();
assertEquals("store empty", 0, store.size());
commands = new MultiplyQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid collections - one is singleton", 1, commands.size());
selection.clear();
selection.add(speed_good_1);
selection.add(speed_irregular);
store.clear();
assertEquals("store empty", 0, store.size());
commands = new MultiplyQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid collections - one is singleton", 1, commands.size());
command = commands.iterator().next();
command.execute();
ICollection output = (ICollection) command.getOutputs().iterator().next();
assertTrue(output.isTemporal());
assertTrue(output.isQuantity());
assertEquals("Correct len",
Math.max(speed_good_1.size(), speed_irregular.size()), output.size());
}
@SuppressWarnings("unchecked")
public void testUnitConversion()
{
// place to store results data
IStore store = new SampleData().getData(10);
List<ICollection> selection = new ArrayList<ICollection>(3);
// speed one defined in m/s
ICollection speed_good_1 = (ICollection) store.get(SampleData.SPEED_ONE);
selection.add(speed_good_1);
// test incompatible target unit
Collection<ICommand<ICollection>> commands = new UnitConversionOperation(
METRE).actionsFor(selection, store, context);
assertEquals("target unit not same dimension as input", 0, commands.size());
// test valid target unit
commands = new UnitConversionOperation(KILOMETRES_PER_HOUR).actionsFor(
selection, store, context);
assertEquals("valid unit dimensions", 1, commands.size());
ICommand<ICollection> command = commands.iterator().next();
// apply action
command.execute();
ICollection newS = (ICollection) store
.get("Speed One Time converted to km/h");
assertNotNull(newS);
// test results is same length as thisSpeed
assertEquals("correct size", 10, newS.size());
assertTrue("is temporal", newS.isTemporal());
// check that operation isn't offered if the dataset is already in
// that type
commands = new UnitConversionOperation(METRES_PER_SECOND).actionsFor(
selection, store, context);
assertEquals("already in destination units", 0, commands.size());
IQuantityCollection<?> inputSpeed = (IQuantityCollection<?>) speed_good_1;
Measurable<Velocity> firstInputSpeed = (Measurable<Velocity>) inputSpeed
.getValues().get(0);
IQuantityCollection<?> outputSpeed = (IQuantityCollection<?>) newS;
Measurable<Velocity> outputMEas = (Measurable<Velocity>) outputSpeed
.getValues().get(0);
double firstOutputSpeed = outputMEas
.doubleValue((Unit<Velocity>) outputSpeed.getUnits());
UnitConverter oc = inputSpeed.getUnits()
.getConverterTo(KILOMETERS_PER_HOUR);
assertEquals(oc.convert(firstInputSpeed
.doubleValue((Unit<Velocity>) inputSpeed.getUnits())), firstOutputSpeed);
}
public void testSimpleMovingAverage()
{
// place to store results data
IStore store = new SampleData().getData(10);
List<ICollection> selection = new ArrayList<>();
@SuppressWarnings("unchecked")
IQuantityCollection<Velocity> speed_good_1 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_ONE);
selection.add(speed_good_1);
int windowSize = 3;
Collection<ICommand<ICollection>> commands = new SimpleMovingAverageOperation(
windowSize).actionsFor(selection, store, context);
assertEquals(1, commands.size());
ICommand<ICollection> command = commands.iterator().next();
// apply action
command.execute();
@SuppressWarnings("unchecked")
IQuantityCollection<Velocity> newS = (IQuantityCollection<Velocity>) store
.get("Moving average of Speed One Time");
assertNotNull(newS);
// test results is same length as thisSpeed
assertEquals("correct size", 10, newS.size());
// calculate sum of input values [0..windowSize-1]
double sum = 0;
for (int i = 0; i < windowSize; i++)
{
Measurable<Velocity> inputQuantity = speed_good_1.getValues().get(i);
sum += inputQuantity.doubleValue(speed_good_1.getUnits());
}
double average = sum / windowSize;
// compare to output value [windowSize-1]
Measurable<Velocity> simpleMovingAverage = newS.getValues().get(
windowSize - 1);
assertEquals(average, simpleMovingAverage.doubleValue(newS.getUnits()), 0);
}
@SuppressWarnings(
{ "unchecked" })
public void testAddition()
{
InMemoryStore store = new SampleData().getData(10);
// test invalid dimensions
ITemporalQuantityCollection<Velocity> speed_good_1 = (ITemporalQuantityCollection<Velocity>) store
.get(SampleData.SPEED_ONE);
IQuantityCollection<Velocity> speed_good_2 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_TWO);
IQuantityCollection<Velocity> newS = (IQuantityCollection<Velocity>) store
.get("Sum of Speed One Time, Speed Two Time");
assertNotNull(newS);
assertEquals("correct size", 10, newS.size());
// assert same unit
assertEquals(newS.getUnits(), speed_good_1.getUnits());
double firstDifference = newS.getValues().get(0)
.doubleValue(newS.getUnits());
double speed1firstValue = speed_good_1.getValues().get(0)
.doubleValue(speed_good_1.getUnits());
double speed2firstValue = speed_good_2.getValues().get(0)
.doubleValue(speed_good_2.getUnits());
assertEquals(firstDifference, speed1firstValue + speed2firstValue);
// test that original series have dependents
assertEquals("first series has dependents", 2, speed_good_1.getDependents()
.size());
assertEquals("second series has dependents", 1, speed_good_2
.getDependents().size());
// test that new series has predecessors
assertNotNull("new series has precedent", newS.getPrecedent());
}
@SuppressWarnings(
{ "rawtypes", "unchecked" })
public void testSubtractionSingleton()
{
InMemoryStore store = new SampleData().getData(10);
List<ICollection> selection = new ArrayList<ICollection>(3);
// test invalid dimensions
IQuantityCollection<Velocity> speed_good_1 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_ONE);
IQuantityCollection<Velocity> speedSingle = new StockTypes.NonTemporal.Speed_MSec(
"singleton");
speedSingle.add(2d);
selection.add(speed_good_1);
selection.add(speedSingle);
Collection<ICommand<ICollection>> commands = new SubtractQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("got two commands", 4, commands.size());
// have a look
ICommand<ICollection> first = commands.iterator().next();
first.execute();
ICollection output = first.getOutputs().iterator().next();
assertNotNull("produced output", output);
assertEquals("correct size", speed_good_1.size(), output.size());
assertEquals("correct value", 2.3767, speed_good_1.getValues().get(0)
.doubleValue(Velocity.UNIT) * 2, 0.001);
}
@SuppressWarnings(
{ "rawtypes", "unchecked" })
public void testAddSingleton()
{
InMemoryStore store = new SampleData().getData(10);
List<ICollection> selection = new ArrayList<ICollection>(3);
// test invalid dimensions
IQuantityCollection<Velocity> speed_good_1 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_ONE);
IQuantityCollection<Velocity> speedSingle = new StockTypes.NonTemporal.Speed_MSec(
"singleton");
speedSingle.add(2d);
selection.add(speed_good_1);
selection.add(speedSingle);
Collection<ICommand<ICollection>> commands = new AddQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("got two commands", 2, commands.size());
// have a look
Iterator<ICommand<ICollection>> iter = commands.iterator();
iter.next();
ICommand<ICollection> first = iter.next();
first.execute();
IQuantityCollection<Velocity> output = (IQuantityCollection) first
.getOutputs().iterator().next();
assertNotNull("produced output", output);
assertTrue("output is temporal", output.isTemporal());
assertEquals("correct size", speed_good_1.size(), output.size());
assertEquals("correct value",
output.getValues().get(0).doubleValue(Velocity.UNIT), speed_good_1
.getValues().get(0).doubleValue(Velocity.UNIT) + 2, 0.001);
}
@SuppressWarnings(
{ "rawtypes", "unchecked" })
public void testSubtraction()
{
InMemoryStore store = new SampleData().getData(10);
int storeSize = store.size();
List<ICollection> selection = new ArrayList<ICollection>(3);
// test invalid dimensions
IQuantityCollection<Velocity> speed_good_1 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_ONE);
IQuantityCollection<Angle> angle_1 = (IQuantityCollection<Angle>) store
.get(SampleData.ANGLE_ONE);
selection.add(speed_good_1);
selection.add(angle_1);
Collection<ICommand<ICollection>> commands = new SubtractQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("invalid collections - not same dimensions", 0,
commands.size());
selection.clear();
// test not all quantities
ICollection string_1 = (ICollection) store.get(SampleData.STRING_ONE);
selection.add(speed_good_1);
selection.add(string_1);
commands = new SubtractQuantityOperation().actionsFor(selection, store,
context);
assertEquals("invalid collections - not all quantities", 0, commands.size());
selection.clear();
// test valid command
IQuantityCollection<Velocity> speed_good_2 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_TWO);
selection.add(speed_good_1);
selection.add(speed_good_2);
commands = new SubtractQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid command", 4, commands.size());
ICommand<ICollection> command = commands.iterator().next();
command.execute();
// test store has a new item in it
assertEquals("store not empty", storeSize + 1, store.size());
IQuantityCollection<Velocity> newS = (IQuantityCollection<Velocity>) store
.get(speed_good_2.getName() + " from " + speed_good_1.getName());
assertNotNull(newS);
assertEquals("correct size", 10, newS.size());
// assert same unit
assertEquals(newS.getUnits(), speed_good_1.getUnits());
double firstDifference = newS.getValues().get(0)
.doubleValue(newS.getUnits());
double speed1firstValue = speed_good_1.getValues().get(0)
.doubleValue(speed_good_1.getUnits());
double speed2firstValue = speed_good_2.getValues().get(0)
.doubleValue(speed_good_2.getUnits());
assertEquals(firstDifference, speed1firstValue - speed2firstValue);
}
@SuppressWarnings("unchecked")
public void testDivision()
{
// place to store results data
InMemoryStore store = new SampleData().getData(10);
List<IStoreItem> selection = new ArrayList<IStoreItem>();
IQuantityCollection<Velocity> speed_good_1 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_ONE);
ICollection speed_good_2 = (ICollection) store.get(SampleData.SPEED_TWO);
IQuantityCollection<Length> length_1 = (IQuantityCollection<Length>) store
.get(SampleData.LENGTH_ONE);
ICollection string_1 = (ICollection) store.get(SampleData.STRING_ONE);
IQuantityCollection<Dimensionless> factor = (IQuantityCollection<Dimensionless>) store
.get(SampleData.FLOATING_POINT_FACTOR);
ICollection speed_good_1_bigger = (ICollection) new SampleData()
.getData(20).get(SampleData.SPEED_ONE);
// /
// / TEST NOT APPLICABLE INPUT
// /
// test invalid number of inputs
selection.add(speed_good_1);
selection.add(speed_good_2);
selection.add(length_1);
Collection<ICommand<IStoreItem>> commands = new DivideQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("invalid number of inputs", 0, commands.size());
// test not all quantities
selection.clear();
selection.add(speed_good_1);
selection.add(string_1);
commands = new DivideQuantityOperation().actionsFor(selection, store,
context);
assertEquals("not all quantities", 0, commands.size());
// test different size
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_1_bigger);
commands = new DivideQuantityOperation().actionsFor(selection, store,
context);
assertEquals("collection not same size", 2, commands.size());
// /
// / TEST APPLICABLE INPUT
// /
// test length over speed
selection.clear();
selection.add(length_1);
selection.add(speed_good_1);
commands = new DivideQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid input", 2, commands.size());
ICommand<IStoreItem> command = commands.iterator().next();
command.execute();
IStoreItem output = command.getOutputs().iterator().next();
IQuantityCollection<Quantity> iQ = (IQuantityCollection<Quantity>) output;
assertEquals("correct units", "[T]", iQ.getUnits().getDimension()
.toString());
store.clear();
command.execute();
assertEquals(1, store.size());
IQuantityCollection<Duration> duration = (IQuantityCollection<Duration>) store
.iterator().next();
assertEquals(speed_good_1.size(), duration.size());
double firstDuration = duration.getValues().get(0)
.doubleValue(duration.getUnits());
double firstLength = length_1.getValues().get(0)
.doubleValue(length_1.getUnits());
double firstSpeed = speed_good_1.getValues().get(0)
.doubleValue(speed_good_1.getUnits());
assertEquals(firstLength / firstSpeed, firstDuration);
// test length over factor
selection.clear();
selection.add(length_1);
selection.add(factor);
commands = new DivideQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid input", 2, commands.size());
Iterator<ICommand<IStoreItem>> iterator = commands.iterator();
command = iterator.next();
store.clear();
command.execute();
assertEquals(1, store.size());
IQuantityCollection<Length> resultLength = (IQuantityCollection<Length>) store
.iterator().next();
assertEquals(length_1.size(), resultLength.size());
double firstResultLength = resultLength.getValues().get(0)
.doubleValue(resultLength.getUnits());
double factorValue = factor.getValues().get(0)
.doubleValue(factor.getUnits());
assertEquals(firstLength / factorValue, firstResultLength);
// test command #2: factor over length
command = iterator.next();
store.clear();
command.execute();
IQuantityCollection<Quantity> resultQuantity = (IQuantityCollection<Quantity>) store
.iterator().next();
// assert expected unit (1/m)
assertEquals("1/" + length_1.getUnits().toString(), resultQuantity
.getUnits().toString());
assertEquals(length_1.size(), resultQuantity.size());
double firstResultQuantity = resultQuantity.getValues().get(0)
.doubleValue(resultQuantity.getUnits());
assertEquals(factorValue / firstLength, firstResultQuantity);
}
}
| info.limpet.test/src/info/limpet/data/TestOperations.java | package info.limpet.data;
import static javax.measure.unit.NonSI.HOUR;
import static javax.measure.unit.NonSI.KILOMETERS_PER_HOUR;
import static javax.measure.unit.NonSI.KILOMETRES_PER_HOUR;
import static javax.measure.unit.NonSI.MINUTE;
import static javax.measure.unit.SI.KILO;
import static javax.measure.unit.SI.METRE;
import static javax.measure.unit.SI.METRES_PER_SECOND;
import info.limpet.ICollection;
import info.limpet.ICommand;
import info.limpet.IContext;
import info.limpet.IOperation;
import info.limpet.IQuantityCollection;
import info.limpet.IStore;
import info.limpet.IStore.IStoreItem;
import info.limpet.ITemporalQuantityCollection;
import info.limpet.data.impl.MockContext;
import info.limpet.data.impl.ObjectCollection;
import info.limpet.data.impl.QuantityCollection;
import info.limpet.data.impl.TemporalQuantityCollection;
import info.limpet.data.impl.samples.SampleData;
import info.limpet.data.impl.samples.StockTypes;
import info.limpet.data.impl.samples.StockTypes.NonTemporal.Angle_Degrees;
import info.limpet.data.impl.samples.StockTypes.Temporal.Speed_Kts;
import info.limpet.data.operations.AddQuantityOperation;
import info.limpet.data.operations.CollectionComplianceTests;
import info.limpet.data.operations.DivideQuantityOperation;
import info.limpet.data.operations.MultiplyQuantityOperation;
import info.limpet.data.operations.SimpleMovingAverageOperation;
import info.limpet.data.operations.SubtractQuantityOperation;
import info.limpet.data.operations.UnitConversionOperation;
import info.limpet.data.operations.UnitaryMathOperation;
import info.limpet.data.operations.admin.OperationsLibrary;
import info.limpet.data.store.InMemoryStore;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.measure.Measurable;
import javax.measure.Measure;
import javax.measure.converter.UnitConverter;
import javax.measure.quantity.Angle;
import javax.measure.quantity.Dimensionless;
import javax.measure.quantity.Duration;
import javax.measure.quantity.Length;
import javax.measure.quantity.Quantity;
import javax.measure.quantity.Velocity;
import javax.measure.unit.Unit;
import junit.framework.TestCase;
public class TestOperations extends TestCase
{
private IContext context = new MockContext();
@SuppressWarnings(
{ "rawtypes", "unchecked" })
public void testInterpolateTests()
{
// place to store results data
InMemoryStore store = new SampleData().getData(10);
// ok, let's try one that works
List<IStoreItem> selection = new ArrayList<IStoreItem>();
// ///////////////
// TEST INVALID PERMUTATIONS
// ///////////////
ICollection speed_good_1 = (ICollection) store.get(SampleData.SPEED_ONE);
ICollection speed_good_2 = (ICollection) store.get(SampleData.SPEED_TWO);
ICollection speed_longer = (ICollection) store
.get(SampleData.SPEED_THREE_LONGER);
selection.add(speed_good_1);
selection.add(speed_longer);
Collection<ICommand<ICollection>> actions = new AddQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("correct number of actions returned", 1, actions.size());
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
actions = new AddQuantityOperation().actionsFor(selection, store, context);
assertEquals("correct number of actions returned", 2, actions.size());
ICommand<?> addAction = actions.iterator().next();
assertNotNull("found action", addAction);
}
public void testTrig()
{
// prepare some data
Speed_Kts speedData = new StockTypes.Temporal.Speed_Kts("speed");
speedData.add(100, 23);
speedData.add(200, 44);
Angle_Degrees angleData = new StockTypes.NonTemporal.Angle_Degrees("degs");
angleData.add(200d);
angleData.add(123d);
StockTypes.Temporal.Angle_Degrees temporalAngleData = new StockTypes.Temporal.Angle_Degrees("degs", null);
temporalAngleData.add(1000, 200d);
temporalAngleData.add(3000, 123d);
List<ICollection> selection = new ArrayList<ICollection>();
InMemoryStore store = new InMemoryStore();
HashMap<String, List<IOperation<?>>> ops = OperationsLibrary
.getOperations();
List<IOperation<?>> arith = ops.get(OperationsLibrary.ARITHMETIC);
// ok, now find the trig op
Iterator<IOperation<?>> iter = arith.iterator();
IOperation<ICollection> sinOp = null;
IOperation<ICollection> cosOp = null;
while (iter.hasNext())
{
IOperation<?> thisO = (IOperation<?>) iter.next();
if (thisO instanceof UnitaryMathOperation)
{
UnitaryMathOperation umo = (UnitaryMathOperation) thisO;
if (umo.getName().equals("Sin"))
{
sinOp = umo;
}
if (umo.getName().equals("Cos"))
{
cosOp = umo;
}
}
}
assertNotNull("check we found it", sinOp);
// ok, try it with empty data
Collection<ICommand<ICollection>> validOps = sinOp.actionsFor(selection,
null, null);
assertEquals("null for empty selection", 0, validOps.size());
// add some speed data
selection.add(speedData);
// ok, try it with empty data
validOps = sinOp.actionsFor(selection, store, null);
assertEquals("empty for invalid selection", 0, validOps.size());
// add some valid data
selection.add(angleData);
// ok, try it with empty data
validOps = sinOp.actionsFor(selection, store, null);
assertEquals("empty for invalid selection", 0, validOps.size());
// ok, try it with empty data
validOps = cosOp.actionsFor(selection, store, null);
assertEquals(" cos also empty for invalid selection", 0, validOps.size());
// and remove the speed data
selection.remove(speedData);
// ok, try it with empty data
validOps = sinOp.actionsFor(selection, store, context);
assertEquals("non-empty for valid selection", 1, validOps.size());
ICommand<ICollection> theOp = validOps.iterator().next();
theOp.execute();
assertEquals("has new dataset", 1, store.size());
ICollection output = theOp.getOutputs().iterator().next();
// check the size
assertEquals("correct size", 2, output.size());
}
public void testAppliesTo()
{
// the units for this measurement
Unit<Velocity> kmh = KILO(METRE).divide(HOUR).asType(Velocity.class);
Unit<Velocity> kmm = KILO(METRE).divide(MINUTE).asType(Velocity.class);
Unit<Length> m = (METRE).asType(Length.class);
// the target collection
QuantityCollection<Velocity> speed_good_1 = new QuantityCollection<Velocity>(
"Speed 1", kmh);
QuantityCollection<Velocity> speed_good_2 = new QuantityCollection<Velocity>(
"Speed 2", kmh);
QuantityCollection<Velocity> speed_longer = new QuantityCollection<Velocity>(
"Speed 3", kmh);
QuantityCollection<Velocity> speed_diff_units = new QuantityCollection<Velocity>(
"Speed 4", kmm);
QuantityCollection<Length> len1 = new QuantityCollection<Length>(
"Length 1", m);
TemporalQuantityCollection<Velocity> temporal_speed_1 = new TemporalQuantityCollection<Velocity>(
"Speed 5", kmh);
TemporalQuantityCollection<Velocity> temporal_speed_2 = new TemporalQuantityCollection<Velocity>(
"Speed 6", kmh);
ObjectCollection<String> string_1 = new ObjectCollection<>("strings 1");
ObjectCollection<String> string_2 = new ObjectCollection<>("strings 2");
for (int i = 1; i <= 10; i++)
{
// create a measurement
double thisSpeed = i * 2;
Measurable<Velocity> speedVal1 = Measure.valueOf(thisSpeed, kmh);
Measurable<Velocity> speedVal2 = Measure.valueOf(thisSpeed * 2, kmh);
Measurable<Velocity> speedVal3 = Measure.valueOf(thisSpeed / 2, kmh);
Measurable<Velocity> speedVal4 = Measure.valueOf(thisSpeed / 2, kmm);
Measurable<Length> lenVal1 = Measure.valueOf(thisSpeed / 2, m);
// store the measurements
speed_good_1.add(speedVal1);
speed_good_2.add(speedVal2);
speed_longer.add(speedVal3);
speed_diff_units.add(speedVal4);
temporal_speed_1.add(i, speedVal2);
temporal_speed_2.add(i, speedVal3);
len1.add(lenVal1);
string_1.add(i + " ");
string_2.add(i + "a ");
}
Measurable<Velocity> speedVal3a = Measure.valueOf(2, kmh);
speed_longer.add(speedVal3a);
List<IStoreItem> selection = new ArrayList<IStoreItem>();
CollectionComplianceTests testOp = new CollectionComplianceTests();
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
assertTrue("all same dim", testOp.allEqualDimensions(selection));
assertTrue("all same units", testOp.allEqualUnits(selection));
assertTrue("all same length", testOp.allEqualLength(selection));
assertTrue("all quantities", testOp.allQuantity(selection));
assertFalse("all temporal", testOp.allTemporal(selection));
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
selection.add(speed_diff_units);
assertTrue("all same dim", testOp.allEqualDimensions(selection));
assertFalse("all same units", testOp.allEqualUnits(selection));
assertTrue("all same length", testOp.allEqualLength(selection));
assertTrue("all quantities", testOp.allQuantity(selection));
assertFalse("all temporal", testOp.allTemporal(selection));
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
selection.add(len1);
assertFalse("all same dim", testOp.allEqualDimensions(selection));
assertFalse("all same units", testOp.allEqualUnits(selection));
assertTrue("all same length", testOp.allEqualLength(selection));
assertTrue("all quantities", testOp.allQuantity(selection));
assertFalse("all temporal", testOp.allTemporal(selection));
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
selection.add(speed_longer);
assertTrue("all same dim", testOp.allEqualDimensions(selection));
assertTrue("all same units", testOp.allEqualUnits(selection));
assertFalse("all same length", testOp.allEqualLength(selection));
assertTrue("all quantities", testOp.allQuantity(selection));
assertFalse("all temporal", testOp.allTemporal(selection));
selection.clear();
selection.add(temporal_speed_1);
selection.add(temporal_speed_2);
assertTrue("all same dim", testOp.allEqualDimensions(selection));
assertTrue("all same units", testOp.allEqualUnits(selection));
assertTrue("all same length", testOp.allEqualLength(selection));
assertTrue("all quantities", testOp.allQuantity(selection));
assertTrue("all temporal", testOp.allTemporal(selection));
selection.clear();
selection.add(temporal_speed_1);
selection.add(string_1);
assertFalse("all same dim", testOp.allEqualDimensions(selection));
assertFalse("all same units", testOp.allEqualUnits(selection));
assertTrue("all same length", testOp.allEqualLength(selection));
assertFalse("all quantities", testOp.allQuantity(selection));
assertFalse("all temporal", testOp.allTemporal(selection));
selection.clear();
selection.add(string_1);
selection.add(string_1);
assertFalse("all same dim", testOp.allEqualDimensions(selection));
assertFalse("all same units", testOp.allEqualUnits(selection));
assertTrue("all same length", testOp.allEqualLength(selection));
assertTrue("all non quantities", testOp.allNonQuantity(selection));
assertFalse("all temporal", testOp.allTemporal(selection));
// ok, let's try one that works
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
InMemoryStore store = new InMemoryStore();
assertEquals("store empty", 0, store.size());
@SuppressWarnings(
{ "unchecked", "rawtypes" })
Collection<ICommand<ICollection>> actions = new AddQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("correct number of actions returned", 1, actions.size());
ICommand<?> addAction = actions.iterator().next();
addAction.execute();
assertEquals("new collection added to store", 1, store.size());
ICollection firstItem = (ICollection) store.iterator().next();
ICommand<?> precedent = firstItem.getPrecedent();
assertNotNull("has precedent", precedent);
assertEquals("Correct name",
"Add numeric values in provided series (indexed)", precedent.getName());
List<? extends IStoreItem> inputs = precedent.getInputs();
assertEquals("Has both precedents", 2, inputs.size());
Iterator<? extends IStoreItem> iIter = inputs.iterator();
while (iIter.hasNext())
{
ICollection thisC = (ICollection) iIter.next();
List<ICommand<?>> deps = thisC.getDependents();
assertEquals("has a depedent", 1, deps.size());
Iterator<ICommand<?>> dIter = deps.iterator();
while (dIter.hasNext())
{
ICommand<?> iCommand = dIter.next();
assertEquals("Correct dependent", precedent, iCommand);
}
}
List<? extends IStoreItem> outputs = precedent.getOutputs();
assertEquals("Has both dependents", 1, outputs.size());
Iterator<? extends IStoreItem> oIter = outputs.iterator();
while (oIter.hasNext())
{
ICollection thisC = (ICollection) oIter.next();
ICommand<?> dep = thisC.getPrecedent();
assertNotNull("has a depedent", dep);
assertEquals("Correct dependent", precedent, dep);
}
}
public void testDimensionlessMultiply()
{
// place to store results data
InMemoryStore store = new SampleData().getData(10);
// ok, let's try one that works
List<IStoreItem> selection = new ArrayList<IStoreItem>();
// ///////////////
// TEST INVALID PERMUTATIONS
// ///////////////
ICollection speed_good_1 = (ICollection) store.get(SampleData.SPEED_ONE);
ICollection speed_good_2 = (ICollection) store.get(SampleData.SPEED_TWO);
ICollection speed_irregular = (ICollection) store
.get(SampleData.SPEED_IRREGULAR2);
ICollection string_1 = (ICollection) store.get(SampleData.STRING_ONE);
ICollection len1 = (ICollection) store.get(SampleData.LENGTH_ONE);
ICollection factor = (ICollection) store
.get(SampleData.FLOATING_POINT_FACTOR);
selection.clear();
selection.add(speed_good_1);
selection.add(string_1);
Collection<ICommand<IStoreItem>> commands = new MultiplyQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("invalid collections - not both quantities", 0,
commands.size());
selection.clear();
selection.add(speed_good_1);
selection.add(len1);
commands = new MultiplyQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid collections - both quantities", 1, commands.size());
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_2);
store.clear();
assertEquals("store empty", 0, store.size());
commands = new MultiplyQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid collections - both speeds", 1, commands.size());
// //////////////////////////
// now test valid collections
// /////////////////////////
selection.clear();
selection.add(speed_good_1);
selection.add(factor);
assertEquals("store empty", 0, store.size());
commands = new MultiplyQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid collections - one is singleton", 1, commands.size());
ICommand<IStoreItem> command = commands.iterator().next();
// test actions has single item: "Multiply series by constant"
assertEquals("correct name", "Multiply series", command.getName());
// apply action
command.execute();
// test store has a new item in it
assertEquals("store not empty", 1, store.size());
ICollection newS = (ICollection) store
.get("Product of Speed One Time, Floating point factor");
// test results is same length as thisSpeed
assertEquals("correct size", 10, newS.size());
selection.clear();
selection.add(speed_good_1);
selection.add(factor);
store.clear();
assertEquals("store empty", 0, store.size());
commands = new MultiplyQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid collections - one is singleton", 1, commands.size());
selection.clear();
selection.add(speed_good_1);
selection.add(speed_irregular);
store.clear();
assertEquals("store empty", 0, store.size());
commands = new MultiplyQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid collections - one is singleton", 1, commands.size());
command = commands.iterator().next();
command.execute();
ICollection output = (ICollection) command.getOutputs().iterator().next();
assertTrue(output.isTemporal());
assertTrue(output.isQuantity());
assertEquals("Correct len",
Math.max(speed_good_1.size(), speed_irregular.size()), output.size());
}
@SuppressWarnings("unchecked")
public void testUnitConversion()
{
// place to store results data
IStore store = new SampleData().getData(10);
List<ICollection> selection = new ArrayList<ICollection>(3);
// speed one defined in m/s
ICollection speed_good_1 = (ICollection) store.get(SampleData.SPEED_ONE);
selection.add(speed_good_1);
// test incompatible target unit
Collection<ICommand<ICollection>> commands = new UnitConversionOperation(
METRE).actionsFor(selection, store, context);
assertEquals("target unit not same dimension as input", 0, commands.size());
// test valid target unit
commands = new UnitConversionOperation(KILOMETRES_PER_HOUR).actionsFor(
selection, store, context);
assertEquals("valid unit dimensions", 1, commands.size());
ICommand<ICollection> command = commands.iterator().next();
// apply action
command.execute();
ICollection newS = (ICollection) store
.get("Speed One Time converted to km/h");
assertNotNull(newS);
// test results is same length as thisSpeed
assertEquals("correct size", 10, newS.size());
assertTrue("is temporal", newS.isTemporal());
// check that operation isn't offered if the dataset is already in
// that type
commands = new UnitConversionOperation(METRES_PER_SECOND).actionsFor(
selection, store, context);
assertEquals("already in destination units", 0, commands.size());
IQuantityCollection<?> inputSpeed = (IQuantityCollection<?>) speed_good_1;
Measurable<Velocity> firstInputSpeed = (Measurable<Velocity>) inputSpeed
.getValues().get(0);
IQuantityCollection<?> outputSpeed = (IQuantityCollection<?>) newS;
Measurable<Velocity> outputMEas = (Measurable<Velocity>) outputSpeed
.getValues().get(0);
double firstOutputSpeed = outputMEas
.doubleValue((Unit<Velocity>) outputSpeed.getUnits());
UnitConverter oc = inputSpeed.getUnits()
.getConverterTo(KILOMETERS_PER_HOUR);
assertEquals(oc.convert(firstInputSpeed
.doubleValue((Unit<Velocity>) inputSpeed.getUnits())), firstOutputSpeed);
}
public void testSimpleMovingAverage()
{
// place to store results data
IStore store = new SampleData().getData(10);
List<ICollection> selection = new ArrayList<>();
@SuppressWarnings("unchecked")
IQuantityCollection<Velocity> speed_good_1 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_ONE);
selection.add(speed_good_1);
int windowSize = 3;
Collection<ICommand<ICollection>> commands = new SimpleMovingAverageOperation(
windowSize).actionsFor(selection, store, context);
assertEquals(1, commands.size());
ICommand<ICollection> command = commands.iterator().next();
// apply action
command.execute();
@SuppressWarnings("unchecked")
IQuantityCollection<Velocity> newS = (IQuantityCollection<Velocity>) store
.get("Moving average of Speed One Time");
assertNotNull(newS);
// test results is same length as thisSpeed
assertEquals("correct size", 10, newS.size());
// calculate sum of input values [0..windowSize-1]
double sum = 0;
for (int i = 0; i < windowSize; i++)
{
Measurable<Velocity> inputQuantity = speed_good_1.getValues().get(i);
sum += inputQuantity.doubleValue(speed_good_1.getUnits());
}
double average = sum / windowSize;
// compare to output value [windowSize-1]
Measurable<Velocity> simpleMovingAverage = newS.getValues().get(
windowSize - 1);
assertEquals(average, simpleMovingAverage.doubleValue(newS.getUnits()), 0);
}
@SuppressWarnings(
{ "unchecked" })
public void testAddition()
{
InMemoryStore store = new SampleData().getData(10);
// test invalid dimensions
ITemporalQuantityCollection<Velocity> speed_good_1 = (ITemporalQuantityCollection<Velocity>) store
.get(SampleData.SPEED_ONE);
IQuantityCollection<Velocity> speed_good_2 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_TWO);
IQuantityCollection<Velocity> newS = (IQuantityCollection<Velocity>) store
.get("Sum of Speed One Time, Speed Two Time");
assertNotNull(newS);
assertEquals("correct size", 10, newS.size());
// assert same unit
assertEquals(newS.getUnits(), speed_good_1.getUnits());
double firstDifference = newS.getValues().get(0)
.doubleValue(newS.getUnits());
double speed1firstValue = speed_good_1.getValues().get(0)
.doubleValue(speed_good_1.getUnits());
double speed2firstValue = speed_good_2.getValues().get(0)
.doubleValue(speed_good_2.getUnits());
assertEquals(firstDifference, speed1firstValue + speed2firstValue);
// test that original series have dependents
assertEquals("first series has dependents", 2, speed_good_1.getDependents()
.size());
assertEquals("second series has dependents", 1, speed_good_2
.getDependents().size());
// test that new series has predecessors
assertNotNull("new series has precedent", newS.getPrecedent());
}
@SuppressWarnings(
{ "rawtypes", "unchecked" })
public void testSubtractionSingleton()
{
InMemoryStore store = new SampleData().getData(10);
List<ICollection> selection = new ArrayList<ICollection>(3);
// test invalid dimensions
IQuantityCollection<Velocity> speed_good_1 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_ONE);
IQuantityCollection<Velocity> speedSingle = new StockTypes.NonTemporal.Speed_MSec(
"singleton");
speedSingle.add(2d);
selection.add(speed_good_1);
selection.add(speedSingle);
Collection<ICommand<ICollection>> commands = new SubtractQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("got two commands", 4, commands.size());
// have a look
ICommand<ICollection> first = commands.iterator().next();
first.execute();
ICollection output = first.getOutputs().iterator().next();
assertNotNull("produced output", output);
assertEquals("correct size", speed_good_1.size(), output.size());
assertEquals("correct value", 2.3767, speed_good_1.getValues().get(0)
.doubleValue(Velocity.UNIT) * 2, 0.001);
}
@SuppressWarnings(
{ "rawtypes", "unchecked" })
public void testAddSingleton()
{
InMemoryStore store = new SampleData().getData(10);
List<ICollection> selection = new ArrayList<ICollection>(3);
// test invalid dimensions
IQuantityCollection<Velocity> speed_good_1 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_ONE);
IQuantityCollection<Velocity> speedSingle = new StockTypes.NonTemporal.Speed_MSec(
"singleton");
speedSingle.add(2d);
selection.add(speed_good_1);
selection.add(speedSingle);
Collection<ICommand<ICollection>> commands = new AddQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("got two commands", 2, commands.size());
// have a look
Iterator<ICommand<ICollection>> iter = commands.iterator();
iter.next();
ICommand<ICollection> first = iter.next();
first.execute();
IQuantityCollection<Velocity> output = (IQuantityCollection) first
.getOutputs().iterator().next();
assertNotNull("produced output", output);
assertTrue("output is temporal", output.isTemporal());
assertEquals("correct size", speed_good_1.size(), output.size());
assertEquals("correct value",
output.getValues().get(0).doubleValue(Velocity.UNIT), speed_good_1
.getValues().get(0).doubleValue(Velocity.UNIT) + 2, 0.001);
}
@SuppressWarnings(
{ "rawtypes", "unchecked" })
public void testSubtraction()
{
InMemoryStore store = new SampleData().getData(10);
int storeSize = store.size();
List<ICollection> selection = new ArrayList<ICollection>(3);
// test invalid dimensions
IQuantityCollection<Velocity> speed_good_1 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_ONE);
IQuantityCollection<Angle> angle_1 = (IQuantityCollection<Angle>) store
.get(SampleData.ANGLE_ONE);
selection.add(speed_good_1);
selection.add(angle_1);
Collection<ICommand<ICollection>> commands = new SubtractQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("invalid collections - not same dimensions", 0,
commands.size());
selection.clear();
// test not all quantities
ICollection string_1 = (ICollection) store.get(SampleData.STRING_ONE);
selection.add(speed_good_1);
selection.add(string_1);
commands = new SubtractQuantityOperation().actionsFor(selection, store,
context);
assertEquals("invalid collections - not all quantities", 0, commands.size());
selection.clear();
// test valid command
IQuantityCollection<Velocity> speed_good_2 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_TWO);
selection.add(speed_good_1);
selection.add(speed_good_2);
commands = new SubtractQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid command", 4, commands.size());
ICommand<ICollection> command = commands.iterator().next();
command.execute();
// test store has a new item in it
assertEquals("store not empty", storeSize + 1, store.size());
IQuantityCollection<Velocity> newS = (IQuantityCollection<Velocity>) store
.get(speed_good_2.getName() + " from " + speed_good_1.getName());
assertNotNull(newS);
assertEquals("correct size", 10, newS.size());
// assert same unit
assertEquals(newS.getUnits(), speed_good_1.getUnits());
double firstDifference = newS.getValues().get(0)
.doubleValue(newS.getUnits());
double speed1firstValue = speed_good_1.getValues().get(0)
.doubleValue(speed_good_1.getUnits());
double speed2firstValue = speed_good_2.getValues().get(0)
.doubleValue(speed_good_2.getUnits());
assertEquals(firstDifference, speed1firstValue - speed2firstValue);
}
@SuppressWarnings("unchecked")
public void testDivision()
{
// place to store results data
InMemoryStore store = new SampleData().getData(10);
List<IStoreItem> selection = new ArrayList<IStoreItem>();
IQuantityCollection<Velocity> speed_good_1 = (IQuantityCollection<Velocity>) store
.get(SampleData.SPEED_ONE);
ICollection speed_good_2 = (ICollection) store.get(SampleData.SPEED_TWO);
IQuantityCollection<Length> length_1 = (IQuantityCollection<Length>) store
.get(SampleData.LENGTH_ONE);
ICollection string_1 = (ICollection) store.get(SampleData.STRING_ONE);
IQuantityCollection<Dimensionless> factor = (IQuantityCollection<Dimensionless>) store
.get(SampleData.FLOATING_POINT_FACTOR);
ICollection speed_good_1_bigger = (ICollection) new SampleData()
.getData(20).get(SampleData.SPEED_ONE);
// /
// / TEST NOT APPLICABLE INPUT
// /
// test invalid number of inputs
selection.add(speed_good_1);
selection.add(speed_good_2);
selection.add(length_1);
Collection<ICommand<IStoreItem>> commands = new DivideQuantityOperation()
.actionsFor(selection, store, context);
assertEquals("invalid number of inputs", 0, commands.size());
// test not all quantities
selection.clear();
selection.add(speed_good_1);
selection.add(string_1);
commands = new DivideQuantityOperation().actionsFor(selection, store,
context);
assertEquals("not all quantities", 0, commands.size());
// test different size
selection.clear();
selection.add(speed_good_1);
selection.add(speed_good_1_bigger);
commands = new DivideQuantityOperation().actionsFor(selection, store,
context);
assertEquals("collection not same size", 2, commands.size());
// /
// / TEST APPLICABLE INPUT
// /
// test length over speed
selection.clear();
selection.add(length_1);
selection.add(speed_good_1);
commands = new DivideQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid input", 2, commands.size());
ICommand<IStoreItem> command = commands.iterator().next();
command.execute();
IStoreItem output = command.getOutputs().iterator().next();
IQuantityCollection<Quantity> iQ = (IQuantityCollection<Quantity>) output;
assertEquals("correct units", "[T]", iQ.getUnits().getDimension()
.toString());
store.clear();
command.execute();
assertEquals(1, store.size());
IQuantityCollection<Duration> duration = (IQuantityCollection<Duration>) store
.iterator().next();
assertEquals(speed_good_1.size(), duration.size());
double firstDuration = duration.getValues().get(0)
.doubleValue(duration.getUnits());
double firstLength = length_1.getValues().get(0)
.doubleValue(length_1.getUnits());
double firstSpeed = speed_good_1.getValues().get(0)
.doubleValue(speed_good_1.getUnits());
assertEquals(firstLength / firstSpeed, firstDuration);
// test length over factor
selection.clear();
selection.add(length_1);
selection.add(factor);
commands = new DivideQuantityOperation().actionsFor(selection, store,
context);
assertEquals("valid input", 2, commands.size());
Iterator<ICommand<IStoreItem>> iterator = commands.iterator();
command = iterator.next();
store.clear();
command.execute();
assertEquals(1, store.size());
IQuantityCollection<Length> resultLength = (IQuantityCollection<Length>) store
.iterator().next();
assertEquals(length_1.size(), resultLength.size());
double firstResultLength = resultLength.getValues().get(0)
.doubleValue(resultLength.getUnits());
double factorValue = factor.getValues().get(0)
.doubleValue(factor.getUnits());
assertEquals(firstLength / factorValue, firstResultLength);
// test command #2: factor over length
command = iterator.next();
store.clear();
command.execute();
IQuantityCollection<Quantity> resultQuantity = (IQuantityCollection<Quantity>) store
.iterator().next();
// assert expected unit (1/m)
assertEquals("1/" + length_1.getUnits().toString(), resultQuantity
.getUnits().toString());
assertEquals(length_1.size(), resultQuantity.size());
double firstResultQuantity = resultQuantity.getValues().get(0)
.doubleValue(resultQuantity.getUnits());
assertEquals(factorValue / firstLength, firstResultQuantity);
}
}
| testing complete
| info.limpet.test/src/info/limpet/data/TestOperations.java | testing complete |
|
Java | mpl-2.0 | b0550a397369099d73ed9bf758612539df89e9e9 | 0 | etomica/etomica,ajschult/etomica,etomica/etomica,ajschult/etomica,etomica/etomica,ajschult/etomica | package etomica.atom.iterator;
import etomica.Atom;
import etomica.AtomIterator;
import etomica.AtomPair;
import etomica.AtomPairIterator;
import etomica.AtomSet;
import etomica.action.AtomsetAction;
/**
* Pair iterator synthesized from two atom iterators, such that the inner-loop
* iteration depends on the outer-loop atom. Pairs are formed from
* the atoms yielded by the two atom iterators. The inner-loop iterator must
* implement AtomIteratorAtomDependent, and its set(Atom) method will be invoked
* with the current outer-loop atom at the start of each inner-loop iteration.
* All pairs returned by iterator are the same Atom[] instance, and
* differ only in the Atom instances held by it.
*/
/* History of changes
* 08/25/04 (DAK et al) new
*/
public class ApiInnerVariable implements AtomPairIterator, ApiComposite {
/**
* Construct a pair iterator using the given atom iterators. Requires
* call to reset() before beginning iteration.
*/
public ApiInnerVariable(AtomIterator aiOuter,
AtomIteratorAtomDependent aiInner) {
this.aiOuter = aiOuter;
this.aiInner = aiInner;
unset();
}
/**
* Accessor method for the outer-loop atom iterator.
* @return the current outer-loop iterator
*/
public AtomIterator getOuterIterator() {return aiOuter;}
/**
* Accessor method for the inner-loop atom iterator.
* @return the current inner-loop iterator
*/
public AtomIterator getInnerIterator() {return aiInner;}
/**
* Sets the iterator such that hasNext is false.
*/
public void unset() {
hasNext = false;
}
/**
* Indicates whether the given atom pair will be returned by the
* iterator during its iteration. The order of the atoms in the pair
* is significant (this means that a value of true is returned only if
* one of the pairs returned by the iterator will have the same two
* atoms in the same atom1/atom2 position as the given pair). Not dependent
* on state of hasNext.
*/
public boolean contains(AtomSet pair) {
if(aiOuter.contains(((AtomPair)pair).atom0)) {
aiInner.setAtom(((AtomPair)pair).atom0);
return aiInner.contains(((AtomPair)pair).atom1);
}
return false;
}
/**
* Returns the number of pairs given by this iterator. Independent
* of state of hasNext. Clobbers the iteration state (i.e., status
* of hasNext/next) but does not recondition iterator (i.e., does not
* change set of iterates that would be given on iteration after reset).
* Must perform reset if attempting iteration after using size() method.
*/
public int size() {
int sum = 0;
aiOuter.reset();
while(aiOuter.hasNext()) {
aiInner.setAtom(aiOuter.nextAtom());
sum += aiInner.size();
}
return sum;
}
/**
* Indicates whether the iterator has completed its iteration.
*/
public boolean hasNext() {return hasNext;}
/**
* Resets the iterator, so that it is ready to go through all of its pairs.
*/
public void reset() {
aiOuter.reset();
hasNext = false;
needUpdate1 = false;
while(aiOuter.hasNext()) { //loop over outer iterator...
pair.atom0 = aiOuter.nextAtom();
aiInner.setAtom(pair.atom0);
aiInner.reset();
if(aiInner.hasNext()) { //until inner iterator has another
hasNext = true;
break; //...until iterator 2 hasNext
}
}//end while
}
/**
* Returns the next pair without advancing the iterator.
* If the iterator has reached the end of its iteration,
* returns null.
*/
public AtomSet peek() {
if(!hasNext) {return null;}
if(needUpdate1) {pair.atom0 = atom1; needUpdate1 = false;} //aiOuter was advanced
pair.atom1 = (Atom)aiInner.peek();
return pair;
}
public AtomSet next() {
return nextPair();
}
/**
* Returns the next pair of atoms. The same Atom[] instance
* is returned every time, but the Atoms it holds are (of course)
* different for each iterate.
*/
public AtomPair nextPair() {
if(!hasNext) return null;
//we use this update flag to indicate that atom1 in pair needs to be set to a new value.
//it is not done directly in the while-loop because pair must first return with the old atom1 intact
if(needUpdate1) {pair.atom0 = atom1; needUpdate1 = false;} //aiOuter was advanced
pair.atom1 = aiInner.nextAtom();
while(!aiInner.hasNext()) { //Inner is done for this atom1, loop until it is prepared for next
if(aiOuter.hasNext()) { //Outer has another atom1...
atom1 = aiOuter.nextAtom(); //...get it
aiInner.setAtom(atom1);
aiInner.reset();
needUpdate1 = true; //...flag update of pair.atom1 for next time
}
else {hasNext = false; break;} //Outer has no more; all done with pairs
}//end while
return pair;
}
/**
* Performs the given action on all pairs returned by this iterator.
*/
public void allAtoms(AtomsetAction act) {
aiOuter.reset();
while(aiOuter.hasNext()) {
pair.atom0 = aiOuter.nextAtom();
aiInner.setAtom(pair.atom0);
aiInner.reset();
while(aiInner.hasNext()){
pair.atom1 = aiInner.nextAtom();
act.actionPerformed(pair);
}
}
}
public final int nBody() {return 2;}
protected final AtomPair pair = new AtomPair();
protected boolean hasNext, needUpdate1;
protected Atom atom1;
/**
* The iterators used to generate the sets of atoms.
* The inner one is not necessarily atom dependent.
*/
protected final AtomIteratorAtomDependent aiInner;
protected final AtomIterator aiOuter;
} //end of class AtomPairIterator
| etomica/atom/iterator/ApiInnerVariable.java | package etomica.atom.iterator;
import etomica.Atom;
import etomica.AtomIterator;
import etomica.AtomPair;
import etomica.AtomPairIterator;
import etomica.AtomSet;
import etomica.action.AtomsetAction;
/**
* Pair iterator synthesized from two atom iterators, such that the inner-loop
* iteration depends on the outer-loop atom. Pairs are formed from
* the atoms yielded by the two atom iterators. The inner-loop iterator must
* implement AtomIteratorAtomDependent, and its set(Atom) method will be invoked
* with the current outer-loop atom at the start of each inner-loop iteration.
* All pairs returned by iterator are the same Atom[] instance, and
* differ only in the Atom instances held by it.
*/
/* History of changes
* 08/25/04 (DAK et al) new
*/
public class ApiInnerVariable implements AtomPairIterator, ApiComposite {
/**
* Construct a pair iterator using the given atom iterators. Requires
* call to reset() before beginning iteration.
*/
public ApiInnerVariable(AtomIterator aiOuter,
AtomIteratorAtomDependent aiInner) {
this.aiOuter = aiOuter;
this.aiInner = aiInner;
unset();
}
/**
* Accessor method for the outer-loop atom iterator.
* @return the current outer-loop iterator
*/
public AtomIterator getOuterIterator() {return aiOuter;}
/**
* Accessor method for the inner-loop atom iterator.
* @return the current inner-loop iterator
*/
public AtomIterator getInnerIterator() {return aiInner;}
// /**
// * Defines the atom iterator that performs the inner-loop iteration to
// * generate the pairs.
// * @param inner The new inner-loop iterator.
// */
// public void setInnerIterator(AtomIteratorAtomDependent inner) {
// this.aiInner = inner;
// unset();
// }
//
// /**
// * Defines the iterator the performs the outer-loop iteration to
// * generate the pairs.
// * @param outer The new outer-loop iterator.
// */
// public void setOuterIterator(AtomIterator outer) {
// this.aiOuter = outer;
// unset();
// }
/**
* Sets the iterator such that hasNext is false.
*/
public void unset() {
hasNext = false;
}
/**
* Indicates whether the given atom pair will be returned by the
* iterator during its iteration. The order of the atoms in the pair
* is significant (this means that a value of true is returned only if
* one of the pairs returned by the iterator will have the same two
* atoms in the same atom1/atom2 position as the given pair). Not dependent
* on state of hasNext.
*/
public boolean contains(AtomSet pair) {
if(aiOuter.contains(((AtomPair)pair).atom0)) {
aiInner.setAtom(((AtomPair)pair).atom0);
return aiInner.contains(((AtomPair)pair).atom1);
}
return false;
}
/**
* Returns the number of pairs given by this iterator. Independent
* of state of hasNext. Clobbers the iteration state (i.e., status
* of hasNext/next) but does not recondition iterator (i.e., does not
* change set of iterates that would be given on iteration after reset).
* Must perform reset if attempting iteration after using size() method.
*/
public int size() {
int sum = 0;
aiOuter.reset();
while(aiOuter.hasNext()) {
aiInner.setAtom(aiOuter.nextAtom());
sum += aiInner.size();
}
return sum;
}
/**
* Indicates whether the iterator has completed its iteration.
*/
public boolean hasNext() {return hasNext;}
/**
* Resets the iterator, so that it is ready to go through all of its pairs.
*/
public void reset() {
aiOuter.reset();
hasNext = false;
needUpdate1 = false;
while(aiOuter.hasNext()) { //loop over outer iterator...
pair.atom0 = aiOuter.nextAtom();
aiInner.setAtom(pair.atom0);
aiInner.reset();
if(aiInner.hasNext()) { //until inner iterator has another
hasNext = true;
break; //...until iterator 2 hasNext
}
}//end while
}
/**
* Returns the next pair without advancing the iterator.
* If the iterator has reached the end of its iteration,
* returns null.
*/
public AtomSet peek() {
if(!hasNext) {return null;}
if(needUpdate1) {pair.atom0 = atom1; needUpdate1 = false;} //aiOuter was advanced
pair.atom1 = (Atom)aiInner.peek();
return pair;
}
public AtomSet next() {
return nextPair();
}
/**
* Returns the next pair of atoms. The same Atom[] instance
* is returned every time, but the Atoms it holds are (of course)
* different for each iterate.
*/
public AtomPair nextPair() {
if(!hasNext) return null;
//we use this update flag to indicate that atom1 in pair needs to be set to a new value.
//it is not done directly in the while-loop because pair must first return with the old atom1 intact
if(needUpdate1) {pair.atom0 = atom1; needUpdate1 = false;} //aiOuter was advanced
pair.atom1 = aiInner.nextAtom();
while(!aiInner.hasNext()) { //Inner is done for this atom1, loop until it is prepared for next
if(aiOuter.hasNext()) { //Outer has another atom1...
atom1 = aiOuter.nextAtom(); //...get it
aiInner.setAtom(atom1);
aiInner.reset();
needUpdate1 = true; //...flag update of pair.atom1 for next time
}
else {hasNext = false; break;} //Outer has no more; all done with pairs
}//end while
return pair;
}
/**
* Performs the given action on all pairs returned by this iterator.
*/
public void allAtoms(AtomsetAction act) {
aiOuter.reset();
while(aiOuter.hasNext()) {
pair.atom0 = aiOuter.nextAtom();
aiInner.setAtom(pair.atom0);
aiInner.reset();
while(aiInner.hasNext()){
pair.atom1 = aiInner.nextAtom();
act.actionPerformed(pair);
}
}
}
public final int nBody() {return 2;}
protected final AtomPair pair = new AtomPair();
protected boolean hasNext, needUpdate1;
protected Atom atom1;
/**
* The iterators used to generate the sets of atoms.
* The inner one is not necessarily atom dependent.
*/
protected final AtomIteratorAtomDependent aiInner;
protected final AtomIterator aiOuter;
/* public static void main(String[] args) throws java.io.IOException {
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
Simulation.instance = new Simulation();
Phase phase = new Phase();
Phase phase2 = new Phase();
Species species = new SpeciesSpheres();
species.setNMolecules(8);
Simulation.instance.elementCoordinator.go();
//Phase phase = TestAll.setupTestPhase(4);
Atom atom = ((AtomGroup)phase.firstSpecies().getAtom(2)).firstChild();
// Atom atom = phase.firstSpecies().getAtom(2);
AtomPairIterator iterator = new AtomPairIterator(phase);
IteratorDirective id = new IteratorDirective();
String line;
System.out.println("reset()"); iterator.reset();
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(DOWN)"); iterator.reset(id.set(IteratorDirective.DOWN));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(NEITHER)"); iterator.reset(id.set(IteratorDirective.NEITHER));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(BOTH)"); iterator.reset(id.set(IteratorDirective.BOTH));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(atom,UP)"); iterator.reset(id.set(atom).set(IteratorDirective.UP));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(atom,DOWN)"); iterator.reset(id.set(atom).set(IteratorDirective.DOWN));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(atom,NEITHER)"); iterator.reset(id.set(atom).set(IteratorDirective.NEITHER));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(atom,BOTH)"); iterator.reset(id.set(atom).set(IteratorDirective.BOTH));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
atom = phase.lastAtom();
System.out.println("reset(lastatom,UP)"); iterator.reset(id.set(atom).set(IteratorDirective.UP));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(lastatom,DOWN)"); iterator.reset(id.set(atom).set(IteratorDirective.DOWN));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(lastatom,NEITHER)"); iterator.reset(id.set(atom).set(IteratorDirective.NEITHER));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(lastatom,BOTH)"); iterator.reset(id.set(atom).set(IteratorDirective.BOTH));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
Species species2 = new SpeciesSpheres();
species.setNMolecules(4);
species2.setNMolecules(5);
Simulation.instance.elementCoordinator.go();
System.out.println("second species added");
iterator = new AtomPairIterator(phase,
species.getAgent(phase).makeLeafAtomIterator(),
species2.getAgent(phase).makeLeafAtomIterator());
atom = ((AtomGroup)species2.getAgent(phase).getAtom(3)).firstChild();
System.out.println("reset(atom,UP)"); iterator.reset(id.set(atom).set(IteratorDirective.UP));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(atom,DOWN)"); iterator.reset(id.set(atom).set(IteratorDirective.DOWN));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(atom,NEITHER)"); iterator.reset(id.set(atom).set(IteratorDirective.NEITHER));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(atom,BOTH)"); iterator.reset(id.set(atom).set(IteratorDirective.BOTH));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
atom = ((AtomGroup)species.getAgent(phase).getAtom(3)).firstChild();
System.out.println("reset(atom,UP)"); iterator.reset(id.set(atom).set(IteratorDirective.UP));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(atom,DOWN)"); iterator.reset(id.set(atom).set(IteratorDirective.DOWN));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(atom,NEITHER)"); iterator.reset(id.set(atom).set(IteratorDirective.NEITHER));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(atom,BOTH)"); iterator.reset(id.set(atom).set(IteratorDirective.BOTH));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(UP)"); iterator.reset(id.set().set(IteratorDirective.UP));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(DOWN)"); iterator.reset(id.set().set(IteratorDirective.DOWN));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(NEITHER)"); iterator.reset(id.set().set(IteratorDirective.NEITHER));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("reset(BOTH)"); iterator.reset(id.set().set(IteratorDirective.BOTH));
while(iterator.hasNext()) {AtomPair pair = iterator.next();System.out.println(pair.atom1().toString()+ " " + pair.atom2().toString());} line = in.readLine();
System.out.println("Done");
line = in.readLine();
System.exit(0);
}//end of main
*/
} //end of class AtomPairIterator
| clean up
| etomica/atom/iterator/ApiInnerVariable.java | clean up |
|
Java | apache-2.0 | 13b50290211cdcb46a3cc6c5b2eafedacfe8e0c1 | 0 | katre/bazel,perezd/bazel,meteorcloudy/bazel,bazelbuild/bazel,cushon/bazel,meteorcloudy/bazel,cushon/bazel,ButterflyNetwork/bazel,meteorcloudy/bazel,meteorcloudy/bazel,bazelbuild/bazel,bazelbuild/bazel,meteorcloudy/bazel,cushon/bazel,bazelbuild/bazel,cushon/bazel,perezd/bazel,perezd/bazel,perezd/bazel,ButterflyNetwork/bazel,ButterflyNetwork/bazel,cushon/bazel,bazelbuild/bazel,bazelbuild/bazel,katre/bazel,ButterflyNetwork/bazel,perezd/bazel,katre/bazel,meteorcloudy/bazel,katre/bazel,ButterflyNetwork/bazel,perezd/bazel,katre/bazel,cushon/bazel,ButterflyNetwork/bazel,perezd/bazel,meteorcloudy/bazel,katre/bazel | // Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.starlarkbuildapi;
import com.google.devtools.build.docgen.annot.DocCategory;
import com.google.devtools.build.lib.cmdline.Label;
import javax.annotation.Nullable;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.StarlarkValue;
/** The interface for files in Starlark. */
@StarlarkBuiltin(
name = "File",
category = DocCategory.BUILTIN,
doc =
"This object is created during the analysis phase to represent a file or directory that "
+ "will be read or written during the execution phase. It is not an open file"
+ " handle, "
+ "and cannot be used to directly read or write file contents. Rather, you use it to "
+ "construct the action graph in a rule implementation function by passing it to "
+ "action-creating functions. See the "
+ "<a href='../rules.$DOC_EXT#files'>Rules page</a> for more information."
+ "" // curse google-java-format b/145078219
+ "<p>When a <code>File</code> is passed to an <a"
+ " href='Args.html'><code>Args</code></a> object without using a"
+ " <code>map_each</code> function, it is converted to a string by taking the value of"
+ " its <code>path</code> field.")
public interface FileApi extends StarlarkValue {
@StarlarkMethod(
name = "dirname",
structField = true,
doc =
"The name of the directory containing this file. It's taken from "
+ "<a href=\"#path\">path</a> and is always relative to the execution directory.")
String getDirname();
@StarlarkMethod(
name = "basename",
structField = true,
doc = "The base name of this file. This is the name of the file inside the directory.")
String getFilename();
@StarlarkMethod(
name = "extension",
structField = true,
doc =
"The file extension of this file, following (not including) the rightmost period. "
+ "Empty string if the file's basename includes no periods.")
String getExtension();
@StarlarkMethod(
name = "owner",
structField = true,
allowReturnNones = true,
doc = "A label of a target that produces this File.")
@Nullable
Label getOwnerLabel();
@StarlarkMethod(
name = "root",
structField = true,
doc = "The root beneath which this file resides.")
FileRootApi getRoot();
@StarlarkMethod(
name = "is_source",
structField = true,
doc = "Returns true if this is a source file, i.e. it is not generated.")
boolean isSourceArtifact();
@StarlarkMethod(
name = "is_directory",
structField = true,
doc = "Returns true if this is a directory.")
boolean isDirectory();
@StarlarkMethod(
name = "short_path",
structField = true,
doc =
"The path of this file relative to its root. This excludes the aforementioned "
+ "<i>root</i>, i.e. configuration-specific fragments of the path. This is also the "
+ "path under which the file is mapped if it's in the runfiles of a binary.")
String getRunfilesPathString();
@StarlarkMethod(
name = "path",
structField = true,
doc =
"The execution path of this file, relative to the workspace's execution directory. It "
+ "consists of two parts, an optional first part called the <i>root</i> (see also "
+ "the <a href=\"root.html\">root</a> module), and the second part which is the "
+ "<code>short_path</code>. The root may be empty, which it usually is for "
+ "non-generated files. For generated files it usually contains a "
+ "configuration-specific path fragment that encodes things like the target CPU "
+ "architecture that was used while building said file. Use the "
+ "<code>short_path</code> for the path under which the file is mapped if it's in "
+ "the runfiles of a binary.")
String getExecPathString();
@StarlarkMethod(
name = "tree_relative_path",
structField = true,
doc =
"The path of this file relative to the root of the ancestor's tree, if the ancestor's "
+ "<a href=\"#is_directory\">is_directory</a> field is true. <code>tree_relative_path"
+ "</code> is only available for expanded files of a directory in an action command, "
+ "i.e. <a href=\"Args.html#add_all\">Args.add_all()</a>. For other types of files, "
+ "it is an error to access this field.")
String getTreeRelativePathString() throws EvalException;
}
| src/main/java/com/google/devtools/build/lib/starlarkbuildapi/FileApi.java | // Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.starlarkbuildapi;
import com.google.devtools.build.docgen.annot.DocCategory;
import com.google.devtools.build.lib.cmdline.Label;
import javax.annotation.Nullable;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.StarlarkValue;
/** The interface for files in Starlark. */
@StarlarkBuiltin(
name = "File",
category = DocCategory.BUILTIN,
doc =
"This object is created during the analysis phase to represent a file or directory that "
+ "will be read or written during the execution phase. It is not an open file"
+ " handle, "
+ "and cannot be used to directly read or write file contents. Rather, you use it to "
+ "construct the action graph in a rule implementation function by passing it to "
+ "action-creating functions. See the "
+ "<a href='../rules.$DOC_EXT#files'>Rules page</a> for more information."
+ "" // curse google-java-format b/145078219
+ "<p>When a <code>File</code> is passed to an <a"
+ " href='Args.html'><code>Args</code></a> object without using a"
+ " <code>map_each</code> function, it is converted to a string by taking the value of"
+ " its <code>path</code> field.")
public interface FileApi extends StarlarkValue {
@StarlarkMethod(
name = "dirname",
structField = true,
doc =
"The name of the directory containing this file. It's taken from "
+ "<a href=\"#path\">path</a> and is always relative to the execution directory.")
String getDirname();
@StarlarkMethod(
name = "basename",
structField = true,
doc = "The base name of this file. This is the name of the file inside the directory.")
String getFilename();
@StarlarkMethod(
name = "extension",
structField = true,
doc =
"The file extension of this file, following (not including) the rightmost period."
+ "Empty string if the file's basename includes no periods.")
String getExtension();
@StarlarkMethod(
name = "owner",
structField = true,
allowReturnNones = true,
doc = "A label of a target that produces this File.")
@Nullable
Label getOwnerLabel();
@StarlarkMethod(
name = "root",
structField = true,
doc = "The root beneath which this file resides.")
FileRootApi getRoot();
@StarlarkMethod(
name = "is_source",
structField = true,
doc = "Returns true if this is a source file, i.e. it is not generated.")
boolean isSourceArtifact();
@StarlarkMethod(
name = "is_directory",
structField = true,
doc = "Returns true if this is a directory.")
boolean isDirectory();
@StarlarkMethod(
name = "short_path",
structField = true,
doc =
"The path of this file relative to its root. This excludes the aforementioned "
+ "<i>root</i>, i.e. configuration-specific fragments of the path. This is also the "
+ "path under which the file is mapped if it's in the runfiles of a binary.")
String getRunfilesPathString();
@StarlarkMethod(
name = "path",
structField = true,
doc =
"The execution path of this file, relative to the workspace's execution directory. It "
+ "consists of two parts, an optional first part called the <i>root</i> (see also "
+ "the <a href=\"root.html\">root</a> module), and the second part which is the "
+ "<code>short_path</code>. The root may be empty, which it usually is for "
+ "non-generated files. For generated files it usually contains a "
+ "configuration-specific path fragment that encodes things like the target CPU "
+ "architecture that was used while building said file. Use the "
+ "<code>short_path</code> for the path under which the file is mapped if it's in "
+ "the runfiles of a binary.")
String getExecPathString();
@StarlarkMethod(
name = "tree_relative_path",
structField = true,
doc =
"The path of this file relative to the root of the ancestor's tree, if the ancestor's "
+ "<a href=\"#is_directory\">is_directory</a> field is true. <code>tree_relative_path"
+ "</code> is only available for expanded files of a directory in an action command, "
+ "i.e. <a href=\"Args.html#add_all\">Args.add_all()</a>. For other types of files, "
+ "it is an error to access this field.")
String getTreeRelativePathString() throws EvalException;
}
| Add missing space to File.extension doc
RELNOTES: None.
PiperOrigin-RevId: 373818503
| src/main/java/com/google/devtools/build/lib/starlarkbuildapi/FileApi.java | Add missing space to File.extension doc |
|
Java | apache-2.0 | 9caf137cd5305dd0438e85b7021df324c78ea9cd | 0 | dlemmermann/CalendarFX,imario42/CalendarFX,imario42/CalendarFX,dlemmermann/CalendarFX | /**
* Copyright (C) 2015, 2016 Dirk Lemmermann Software & Consulting (dlsc.com)
*
* This file is part of CalendarFX.
*/
package com.calendarfx.view;
import com.calendarfx.model.*;
import com.calendarfx.util.LoggingDomain;
import com.calendarfx.view.page.DayPage;
import com.calendarfx.view.popover.DatePopOver;
import com.calendarfx.view.popover.EntryPopOverContentPane;
import impl.com.calendarfx.view.ViewHelper;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.WeakInvalidationListener;
import javafx.beans.binding.Bindings;
import javafx.beans.property.*;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.collections.ObservableSet;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.effect.Light.Point;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.InputEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.util.Callback;
import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;
import org.controlsfx.control.PropertySheet.Item;
import java.text.MessageFormat;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import static java.time.DayOfWeek.SATURDAY;
import static java.time.DayOfWeek.SUNDAY;
import static java.util.Objects.requireNonNull;
import static javafx.scene.control.SelectionMode.MULTIPLE;
import static javafx.scene.input.ContextMenuEvent.CONTEXT_MENU_REQUESTED;
import static javafx.scene.input.MouseButton.PRIMARY;
/**
* The superclass for all controls that are showing calendar information. This
* class is responsible for:
* <p>
* <ul>
* <li>Binding to other date controls</li>
* <li>Providing the current date, "today", first day of week</li>
* <li>Creating sources, calendars, entries</li>
* <li>Context menu</li>
* <li>Showing details for a given date or entry</li>
* <li>Providing a virtual grid for editing</li>
* <li>Selection handling</li>
* <li>Printing</li>
* </ul>
* <h2>Binding</h2> Date controls are bound to each other to create complex date
* controls like the {@link CalendarView}. When date controls are bound to each
* other via the {@link #bind(DateControl, boolean)} method then most of their
* properties will be bound to each other. This not only includes date and time
* zone properties but also all the factory and detail callbacks. This allows an
* application to create a complex calendar control and to configure only that
* control without worrying about the date controls that are nested inside of
* it. The children will all "inherit" their settings from the parent control.
* <p>
* <h2>Current Date, Today, First Day of Week</h2> The {@link #dateProperty()}
* is used to store the date that the control has to display. For the
* {@link DayView} this would mean that it has to show exactly that date. The
* {@link DetailedWeekView} would only have to guarantee that it shows the week that
* contains this date. For this the {@link DetailedWeekView} uses the
* {@link #getFirstDayOfWeek()} method that looks up its value from the week
* fields stored in the {@link #weekFieldsProperty()}. The
* {@link #todayProperty()} is mainly used for highlighting today's date in the
* view (e.g. a red background).
* <p>
* <h2>Creating Sources, Calendars, Entries</h2> The date control uses various
* factories to create new sources, calendars, and entries. Each factory has to
* implement the {@link Callback} interface. The factories will be invoked when
* the application calls {@link #createCalendarSource()} or
* {@link #createEntryAt(ZonedDateTime)}.
* <p>
* <h2>Context Menu</h2> Date controls can either set a context menu explicitly
* via {@link #setContextMenu(ContextMenu)} or by providing a callback that gets
* invoked every time the context menu event is received (see
* {@link #setContextMenuCallback(Callback)}). If a context menu has been set
* explicitly then the callback will never be called again.
* <p>
* <h2>Details for Entries and Dates</h2> When clicking on an entry or a date
* the user wants to see details regarding the entry or the date. Callbacks for
* this can be registered via {@link #setEntryDetailsCallback(Callback)} and
* {@link #setDateDetailsCallback(Callback)}. The callbacks can decide which
* kind of user interface they want to show to the user. The default
* implementation for both callbacks is a {@link PopOver} control from the
* <a href="http://controlsfx.org">ControlsFX</a> project.
* <p>
* <h2>Selection Handling</h2> Date controls use a very simple selection
* concept. All selected entries are stored inside an observable list (see
* {@link #getSelections()}). The controls support single and multiple
* selections (see {@link #setSelectionMode(SelectionMode)}). Due to the binding
* approach it does not matter in which child date control an entry gets
* selected. All controls will always know which entries are selected.
* <p>
* <h2>Virtual Grid</h2> A virtual grid is used for editing. It allows the start
* and end times of entries to snap to "virtual" grid lines. The grid can be
* used to make the times always snap to 5, 10, 15, 30 minutes for example. This
* makes it easier to align entries to each other and covers the most common use
* cases. More precise times can always be set in the details.
*/
public abstract class DateControl extends CalendarFXControl {
private int entryCounter = 1;
private Boolean usesOwnContextMenu;
private final InvalidationListener updateCalendarListListener = (Observable it) -> updateCalendarList();
private final WeakInvalidationListener weakUpdateCalendarListListener = new WeakInvalidationListener(updateCalendarListListener);
/**
* Constructs a new date control and initializes all factories and callbacks
* with default implementations.
*/
protected DateControl() {
setFocusTraversable(false);
setUsagePolicy(count -> {
if (count < 0) {
throw new IllegalArgumentException("usage count can not be smaller than zero, but was " + count);
}
switch (count) {
case 0:
return Usage.NONE;
case 1:
return Usage.VERY_LOW;
case 2:
return Usage.LOW;
case 3:
return Usage.MEDIUM;
case 4:
return Usage.HIGH;
case 5:
default:
return Usage.VERY_HIGH;
}
});
getWeekendDays().add(SATURDAY);
getWeekendDays().add(SUNDAY);
/*
* Every date control is initially populated with a default source and
* calendar.
*/
CalendarSource defaultCalendarSource = new CalendarSource(Messages.getString("DateControl.DEFAULT_CALENDAR_SOURCE_NAME")); //$NON-NLS-1$
Calendar defaultCalendar = new Calendar(Messages.getString("DateControl.DEFAULT_CALENDAR_NAME")); //$NON-NLS-1$
defaultCalendarSource.getCalendars().add(defaultCalendar);
getCalendarSources().add(defaultCalendarSource);
InvalidationListener hidePopOverListener = it -> maybeHidePopOvers();
sceneProperty().addListener(hidePopOverListener);
visibleProperty().addListener(hidePopOverListener);
getCalendarSources().addListener(weakUpdateCalendarListListener);
/*
* The popover content callback creates a content node that will make
* out the content of the popover used to display entry details.
*/
setEntryDetailsPopOverContentCallback(param -> new EntryPopOverContentPane(param.getPopOver(), param.getDateControl(), param.getEntry()));
/*
* The default calendar provider returns the first calendar from the
* first source.
*/
setDefaultCalendarProvider(control -> {
List<CalendarSource> sources = getCalendarSources();
if (sources != null && !sources.isEmpty()) {
CalendarSource s = sources.get(0);
List<? extends Calendar> calendars = s.getCalendars();
if (calendars != null && !calendars.isEmpty()) {
for (Calendar c : calendars) {
if (!c.isReadOnly() && isCalendarVisible(c)) {
return c;
}
}
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle(Messages.getString("DateControl.TITLE_CALENDAR_PROBLEM")); //$NON-NLS-1$
alert.setHeaderText(Messages.getString("DateControl.HEADER_TEXT_UNABLE_TO_CREATE_NEW_ENTRY")); //$NON-NLS-1$
String newLine = System.getProperty("line.separator"); //$NON-NLS-1$
alert.setContentText(MessageFormat.format(Messages.getString("DateControl.CONTENT_TEXT_UNABLE_TO_CREATE_NEW_ENTRY"), //$NON-NLS-1$
newLine));
alert.show();
} else {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle(Messages.getString("DateControl.TITLE_CALENDAR_PROBLEM")); //$NON-NLS-1$
alert.setHeaderText(Messages.getString("DateControl.HEADER_TEXT_NO_CALENDARS_DEFINED")); //$NON-NLS-1$
alert.setContentText(Messages.getString("DateControl.CONTENT_TEXT_NO_CALENDARS_DEFINED")); //$NON-NLS-1$
alert.show();
}
}
return null;
});
setEntryFactory(param -> {
DateControl control = param.getDateControl();
VirtualGrid grid = control.getVirtualGrid();
ZonedDateTime time = param.getZonedDateTime();
DayOfWeek firstDayOfWeek = getFirstDayOfWeek();
ZonedDateTime lowerTime = grid.adjustTime(time, false, firstDayOfWeek);
ZonedDateTime upperTime = grid.adjustTime(time, true, firstDayOfWeek);
if (Duration.between(time, lowerTime).abs().minus(Duration.between(time, upperTime).abs()).isNegative()) {
time = lowerTime;
} else {
time = upperTime;
}
Entry<Object> entry = new Entry<>(MessageFormat.format(Messages.getString("DateControl.DEFAULT_ENTRY_TITLE"), entryCounter++)); //$NON-NLS-1$
Interval interval = new Interval(time.toLocalDateTime(), time.toLocalDateTime().plusHours(1));
entry.setInterval(interval);
if (control instanceof AllDayView) {
entry.setFullDay(true);
}
return entry;
});
setEntryDetailsCallback(param -> {
InputEvent evt = param.getInputEvent();
if (evt instanceof MouseEvent) {
MouseEvent mouseEvent = (MouseEvent) evt;
if (mouseEvent.getClickCount() == 2) {
showEntryDetails(param.getEntry(), param.getOwner(), param.getScreenY());
return true;
}
} else {
showEntryDetails(param.getEntry(), param.getOwner(), param.getScreenY());
return true;
}
return false;
});
setDateDetailsCallback(param -> {
InputEvent evt = param.getInputEvent();
if (evt == null) {
showDateDetails(param.getOwner(), param.getLocalDate());
return true;
} else if (evt instanceof MouseEvent) {
MouseEvent mouseEvent = (MouseEvent) evt;
if (mouseEvent.getClickCount() == 1) {
showDateDetails(param.getOwner(), param.getLocalDate());
return true;
}
}
return false;
});
setContextMenuCallback(new ContextMenuProvider());
setEntryContextMenuCallback(param -> {
EntryViewBase<?> entryView = param.getEntryView();
Entry<?> entry = entryView.getEntry();
ContextMenu contextMenu = new ContextMenu();
/*
* Show dialog / popover with entry details.
*/
MenuItem informationItem = new MenuItem(Messages.getString("DateControl.MENU_ITEM_INFORMATION")); //$NON-NLS-1$
informationItem.setOnAction(evt -> {
Callback<EntryDetailsParameter, Boolean> detailsCallback = getEntryDetailsCallback();
if (detailsCallback != null) {
ContextMenuEvent ctxEvent = param.getContextMenuEvent();
EntryDetailsParameter entryDetailsParam = new EntryDetailsParameter(ctxEvent, DateControl.this, entryView.getEntry(), this, ctxEvent.getScreenX(), ctxEvent.getScreenY());
detailsCallback.call(entryDetailsParam);
}
});
contextMenu.getItems().add(informationItem);
String stylesheet = CalendarView.class.getResource("calendar.css") //$NON-NLS-1$
.toExternalForm();
/*
* Assign entry to different calendars.
*/
Menu calendarMenu = new Menu(Messages.getString("DateControl.MENU_CALENDAR")); //$NON-NLS-1$
for (Calendar calendar : getCalendars()) {
RadioMenuItem calendarItem = new RadioMenuItem(calendar.getName());
calendarItem.setOnAction(evt -> entry.setCalendar(calendar));
calendarItem.setDisable(calendar.isReadOnly());
calendarItem.setSelected(calendar.equals(param.getCalendar()));
calendarMenu.getItems().add(calendarItem);
StackPane graphic = new StackPane();
graphic.getStylesheets().add(stylesheet);
/*
* Icon has to be wrapped in a stackpane so that a stylesheet
* can be added to it.
*/
Rectangle icon = new Rectangle(10, 10);
icon.setArcHeight(2);
icon.setArcWidth(2);
icon.getStyleClass().setAll(calendar.getStyle() + "-icon"); //$NON-NLS-1$
graphic.getChildren().add(icon);
calendarItem.setGraphic(graphic);
}
calendarMenu.setDisable(param.getCalendar().isReadOnly());
contextMenu.getItems().add(calendarMenu);
if (getEntryEditPolicy().call(new EntryEditParameter(this, entry, EditOperation.DELETE))) {
/*
* Delete calendar entry.
*/
MenuItem delete = new MenuItem(Messages.getString("DateControl.MENU_ITEM_DELETE")); //$NON-NLS-1$
contextMenu.getItems().add(delete);
delete.setDisable(param.getCalendar().isReadOnly());
delete.setOnAction(evt -> {
Calendar calendar = entry.getCalendar();
if (!calendar.isReadOnly()) {
if (entry.isRecurrence()) {
entry.getRecurrenceSourceEntry().removeFromCalendar();
} else {
entry.removeFromCalendar();
}
}
});
}
return contextMenu;
});
setCalendarSourceFactory(param -> {
CalendarSource source = new CalendarSource(Messages.getString("DateControl.DEFAULT_NEW_CALENDAR_SOURCE")); //$NON-NLS-1$
Calendar calendar = new Calendar(Messages.getString("DateControl.DEFAULT_NEW_CALENDAR")); //$NON-NLS-1$
calendar.setShortName(Messages.getString("DateControl.DEFAULT_NEW_CALENDAR").substring(0, 1));
source.getCalendars().add(calendar);
return source;
});
addEventHandler(CONTEXT_MENU_REQUESTED, evt -> {
/*
* If a context menu was specified by calling setContextMenu() then
* we will not use the callback to produce one.
*/
if (null == usesOwnContextMenu) {
usesOwnContextMenu = getContextMenu() != null;
}
if (!usesOwnContextMenu) {
evt.consume();
Callback<ContextMenuParameter, ContextMenu> callback = getContextMenuCallback();
if (callback != null) {
Callback<DateControl, Calendar> calendarProvider = getDefaultCalendarProvider();
Calendar calendar = calendarProvider.call(DateControl.this);
ZonedDateTime time = ZonedDateTime.now();
if (DateControl.this instanceof ZonedDateTimeProvider) {
ZonedDateTimeProvider provider = (ZonedDateTimeProvider) DateControl.this;
time = provider.getZonedDateTimeAt(evt.getX(), evt.getY());
}
ContextMenuParameter param = new ContextMenuParameter(evt, DateControl.this, calendar, time);
ContextMenu menu = callback.call(param);
if (menu != null) {
setContextMenu(menu);
menu.show(DateControl.this, evt.getScreenX(), evt.getScreenY());
}
}
}
});
addEventFilter(MouseEvent.MOUSE_PRESSED, evt -> {
maybeHidePopOvers();
performSelection(evt);
});
}
private final ObservableMap<Calendar, BooleanProperty> calendarVisibilityMap = FXCollections.observableHashMap();
public final ObservableMap<Calendar, BooleanProperty> getCalendarVisibilityMap() {
return calendarVisibilityMap;
}
public final BooleanProperty getCalendarVisibilityProperty(Calendar calendar) {
return calendarVisibilityMap.computeIfAbsent(calendar, cal -> new SimpleBooleanProperty(DateControl.this, "visible", true));
}
public final boolean isCalendarVisible(Calendar calendar) {
BooleanProperty prop = getCalendarVisibilityProperty(calendar);
return prop.get();
}
public final void setCalendarVisibility(Calendar calendar, boolean visible) {
BooleanProperty prop = getCalendarVisibilityProperty(calendar);
prop.set(visible);
}
/**
* Requests that the date control should reload its data and recreate its
* entry views. Normally applications do not have to call this method. It is
* more like a backdoor for client / server applications where the server is
* unable to push changes to the client. In this case the client must
* frequently trigger an explicit refresh.
*/
public final void refreshData() {
getProperties().put("refresh.data", true); //$NON-NLS-1$
getBoundDateControls().forEach(DateControl::refreshData);
}
private void performSelection(MouseEvent evt) {
if ((evt.getButton().equals(PRIMARY) || evt.isPopupTrigger()) && evt.getClickCount() == 1) {
Entry<?> entry;
EntryViewBase<?> view = null;
if (evt.getTarget() instanceof EntryViewBase) {
view = (EntryViewBase<?>) evt.getTarget();
}
if (view == null) {
return;
}
String disableFocusHandlingKey = "disable-focus-handling"; //$NON-NLS-1$
view.getProperties().put(disableFocusHandlingKey, true);
view.requestFocus();
entry = view.getEntry();
if (entry != null) {
if (!isMultiSelect(evt) && !getSelections().contains(entry)) {
clearSelection();
}
if (isMultiSelect(evt) && getSelections().contains(entry)) {
getSelections().remove(entry);
} else if (!getSelections().contains(entry)) {
getSelections().add(entry);
}
}
view.getProperties().remove(disableFocusHandlingKey);
}
}
private boolean isMultiSelect(MouseEvent evt) {
return (evt.isShiftDown() || evt.isShortcutDown()) && getSelectionMode().equals(MULTIPLE);
}
/**
* Creates a new calendar source that will be added to the list of calendar
* sources of this date control. The method delegates the actual creation of
* the calendar source to a factory, which can be specified by calling
* {@link #setCalendarSourceFactory(Callback)}.
*
* @see #setCalendarSourceFactory(Callback)
*/
public final void createCalendarSource() {
Callback<CreateCalendarSourceParameter, CalendarSource> factory = getCalendarSourceFactory();
if (factory != null) {
CreateCalendarSourceParameter param = new CreateCalendarSourceParameter(this);
CalendarSource calendarSource = factory.call(param);
if (calendarSource != null && !getCalendarSources().contains(calendarSource)) {
getCalendarSources().add(calendarSource);
}
}
}
// dragged entry support
private final ObjectProperty<DraggedEntry> draggedEntry = new SimpleObjectProperty<>(this, "draggedEntry"); //$NON-NLS-1$
/**
* Stores a {@link DraggedEntry} instance, which serves as a wrapper around
* the actual entry that is currently being edited by the user. The
* framework creates this wrapper when the user starts a drag and adds it to
* the date control. This allows the framework to show the entry at its old
* and new location at the same time. It also ensures that the calendar does
* not fire any events before the user has committed the entry to a new
* location.
*
* @return the dragged entry
*/
public final ObjectProperty<DraggedEntry> draggedEntryProperty() {
return draggedEntry;
}
/**
* Returns the value of {@link #draggedEntryProperty()}.
*
* @return the dragged entry
*/
public final DraggedEntry getDraggedEntry() {
return draggedEntry.get();
}
/**
* Sets the value of {@link #draggedEntryProperty()}.
*
* @param entry the dragged entry
*/
public final void setDraggedEntry(DraggedEntry entry) {
draggedEntryProperty().set(entry);
}
/**
* Creates a new entry at the given time. The method delegates the actual
* instance creation to the entry factory (see
* {@link #entryFactoryProperty()}). The factory receives a parameter object
* that contains the default calendar where the entry can be added, however
* the factory can choose to add the entry to any calendar it likes. Please
* note that the time passed to the factory will be adjusted based on the
* current virtual grid settings (see {@link #virtualGridProperty()}).
*
* @param time the time where the entry will be created (the entry start
* time)
* @return the new calendar entry
* @see #setEntryFactory(Callback)
* @see #setVirtualGrid(VirtualGrid)
*/
public final Entry<?> createEntryAt(ZonedDateTime time) {
return createEntryAt(time, null);
}
/**
* Creates a new entry at the given time. The method delegates the actual
* instance creation to the entry factory (see
* {@link #entryFactoryProperty()}). The factory receives a parameter object
* that contains the calendar where the entry can be added, however the
* factory can choose to add the entry to any calendar it likes. Please note
* that the time passed to the factory will be adjusted based on the current
* virtual grid settings (see {@link #virtualGridProperty()}).
*
* @param time the time where the entry will be created (the entry start
* time)
* @param calendar the calendar to which the new entry will be added (if null the
* default calendar provider will be invoked)
* @return the new calendar entry
* @see #setEntryFactory(Callback)
* @see #setVirtualGrid(VirtualGrid)
*/
public final Entry<?> createEntryAt(ZonedDateTime time, Calendar calendar) {
requireNonNull(time);
VirtualGrid grid = getVirtualGrid();
if (grid != null) {
ZonedDateTime timeA = grid.adjustTime(time, false, getFirstDayOfWeek());
ZonedDateTime timeB = grid.adjustTime(time, true, getFirstDayOfWeek());
if (Duration.between(time, timeA).abs().minus(Duration.between(time, timeB).abs()).isNegative()) {
time = timeA;
} else {
time = timeB;
}
}
if (calendar == null) {
Callback<DateControl, Calendar> defaultCalendarProvider = getDefaultCalendarProvider();
calendar = defaultCalendarProvider.call(this);
}
if (calendar != null) {
/*
* We have to ensure that the calendar is visible, otherwise the new
* entry would not be shown to the user.
*/
setCalendarVisibility(calendar, true);
CreateEntryParameter param = new CreateEntryParameter(this, calendar, time);
Callback<CreateEntryParameter, Entry<?>> factory = getEntryFactory();
Entry<?> entry = factory.call(param);
if (entry != null) {
/*
* This is OK. The factory can return NULL. In this case we
* assume that the application does not allow to create an entry
* at the given location.
*/
entry.setCalendar(calendar);
}
return entry;
} else {
LoggingDomain.EDITING.warning("No calendar found for adding a new entry."); //$NON-NLS-1$
}
return null;
}
/**
* Returns the calendar shown at the given location. This method returns an
* optional value. Calling this method might or might not make sense,
* depending on the type of control and the current layout (see
* {@link #layoutProperty()}).
*
* @param x the x-coordinate to check
* @param y the y-coordinate to check
* @return the calendar at the given location
*/
public Optional<Calendar> getCalendarAt(double x, double y) {
return Optional.empty();
}
/**
* Adjusts the current view / page in such a way that the given entry
* becomes visible.
*
* @param entry the entry to show
*/
public final void showEntry(Entry<?> entry) {
requireNonNull(entry);
doShowEntry(entry, false);
}
/**
* Adjusts the current view / page in such a way that the given entry
* becomes visible and brings up the details editor / UI for the entry
* (default is a popover).
*
* @param entry the entry to show
*/
public final void editEntry(Entry<?> entry) {
requireNonNull(entry);
doShowEntry(entry, true);
}
private void doShowEntry(Entry<?> entry, boolean startEditing) {
setDate(entry.getStartDate());
if (!entry.isFullDay()) {
setRequestedTime(entry.getStartTime());
}
if (startEditing) {
/*
* The UI first needs to update itself so that the matching entry
* view can be found.
*/
Platform.runLater(() -> doEditEntry(entry));
} else {
Platform.runLater(() -> doBounceEntry(entry));
}
}
private void doEditEntry(Entry<?> entry) {
EntryViewBase<?> entryView = findEntryView(entry);
if (entryView != null) {
entryView.bounce();
Point2D localToScreen = entryView.localToScreen(0, 0);
Callback<EntryDetailsParameter, Boolean> callback = getEntryDetailsCallback();
EntryDetailsParameter param = new EntryDetailsParameter(null, this, entry, entryView, localToScreen.getX(), localToScreen.getY());
callback.call(param);
}
}
private void doBounceEntry(Entry<?> entry) {
EntryViewBase<?> entryView = findEntryView(entry);
if (entryView != null) {
entryView.bounce();
}
}
private static PopOver entryPopOver;
private void showEntryDetails(Entry<?> entry, Node owner, double screenY) {
maybeHidePopOvers();
Callback<EntryDetailsPopOverContentParameter, Node> contentCallback = getEntryDetailsPopOverContentCallback();
if (contentCallback == null) {
throw new IllegalStateException("No content callback found for entry popover"); //$NON-NLS-1$
}
entryPopOver = new PopOver();
EntryDetailsPopOverContentParameter param = new EntryDetailsPopOverContentParameter(entryPopOver, this, owner, entry);
Node content = contentCallback.call(param);
if (content == null) {
content = new Label(Messages.getString("DateControl.NO_CONTENT")); //$NON-NLS-1$
}
entryPopOver.setContentNode(content);
ArrowLocation location = ViewHelper.findPopOverArrowLocation(owner);
entryPopOver.setArrowLocation(location);
Point position = ViewHelper.findPopOverArrowPosition(owner, screenY, entryPopOver.getArrowSize(), location);
entryPopOver.show(owner, position.getX(), position.getY());
}
private static DatePopOver datePopOver;
/**
* Creates a new {@link DatePopOver} and shows it attached to the given
* owner node.
*
* @param owner the owner node
* @param date the date for which to display more detail
*/
public void showDateDetails(Node owner, LocalDate date) {
maybeHidePopOvers();
datePopOver = new DatePopOver(this, date);
datePopOver.show(owner);
}
private void maybeHidePopOvers() {
if (entryPopOver != null && entryPopOver.isShowing() && !entryPopOver.isDetached()) {
entryPopOver.hide();
}
if (datePopOver != null && datePopOver.isShowing() && !datePopOver.isDetached()) {
datePopOver.hide();
}
}
private abstract static class ContextMenuParameterBase {
private DateControl dateControl;
private ContextMenuEvent contextMenuEvent;
public ContextMenuParameterBase(ContextMenuEvent contextMenuEvent, DateControl dateControl) {
this.contextMenuEvent = requireNonNull(contextMenuEvent);
this.dateControl = requireNonNull(dateControl);
}
public ContextMenuEvent getContextMenuEvent() {
return contextMenuEvent;
}
public DateControl getDateControl() {
return dateControl;
}
}
/**
* The parameter object passed to the entry factory. It contains the most
* important parameters for creating a new entry: the requesting date
* control, the time where the user performed a double click and the default
* calendar.
*
* @see DateControl#entryFactoryProperty()
* @see DateControl#defaultCalendarProviderProperty()
* @see DateControl#createEntryAt(ZonedDateTime)
*/
public static final class CreateEntryParameter {
private final Calendar calendar;
private final ZonedDateTime zonedDateTime;
private final DateControl control;
/**
* Constructs a new parameter object.
*
* @param control the control where the user / the application wants to
* create a new entry
* @param calendar the default calendar
* @param time the time selected by the user in the date control
*/
public CreateEntryParameter(DateControl control, Calendar calendar, ZonedDateTime time) {
this.control = requireNonNull(control);
this.calendar = requireNonNull(calendar);
this.zonedDateTime = requireNonNull(time);
}
/**
* Returns the default calendar. Applications can add the new entry to
* this calendar by calling {@link Entry#setCalendar(Calendar)} or the
* can choose any other calendar.
*
* @return the default calendar
*/
public Calendar getDefaultCalendar() {
return calendar;
}
/**
* The time selected by the user.
*
* @return the start time for the new entry
*/
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
/**
* The date control where the user performed the double click.
*
* @return the date control where the event happened
*/
public DateControl getDateControl() {
return control;
}
@Override
public String toString() {
return "CreateEntryParameter [calendar=" + calendar //$NON-NLS-1$
+ ", zonedDateTime=" + zonedDateTime + "]"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
private final ObjectProperty<Callback<CreateEntryParameter, Entry<?>>> entryFactory = new SimpleObjectProperty<>(this, "entryFactory"); //$NON-NLS-1$
/**
* A factory for creating new entries when the user double clicks inside the
* date control or when the application calls
* {@link #createEntryAt(ZonedDateTime)}. The factory can return NULL to
* indicate that no entry can be created at the given location.
* <p>
* <h2>Code Example</h2>
* <p>
* The code below shows the default entry factory that is set on every date
* control.
* <p>
* <p>
* <pre>
* setEntryFactory(param -> {
* DateControl control = param.getControl();
* VirtualGrid grid = control.getVirtualGrid();
* ZonedDateTime time = param.getZonedDateTime();
* DayOfWeek firstDayOfWeek = getFirstDayOfWeek();
*
* ZonedDateTime lowerTime = grid.adjustTime(time, false, firstDayOfWeek);
* ZonedDateTime upperTime = grid.adjustTime(time, true, firstDayOfWeek);
*
* if (Duration.between(time, lowerTime).abs().minus(Duration.between(time, upperTime).abs()).isNegative()) {
* time = lowerTime;
* } else {
* time = upperTime;
* }
*
* Entry<Object> entry = new Entry<>("New Entry");
* entry.changeStartDate(time.toLocalDate());
* entry.changeStartTime(time.toLocalTime());
* entry.changeEndDate(entry.getStartDate());
* entry.changeEndTime(entry.getStartTime().plusHours(1));
*
* if (control instanceof AllDayView) {
* entry.setFullDay(true);
* }
*
* return entry;
* });
* </pre>
*
* @return the entry factory callback
*/
public final ObjectProperty<Callback<CreateEntryParameter, Entry<?>>> entryFactoryProperty() {
return entryFactory;
}
/**
* Returns the value of {@link #entryFactoryProperty()}.
*
* @return the factory used for creating a new entry
*/
public final Callback<CreateEntryParameter, Entry<?>> getEntryFactory() {
return entryFactoryProperty().get();
}
/**
* Sets the value of {@link #entryFactoryProperty()}.
*
* @param factory the factory used for creating a new entry
*/
public final void setEntryFactory(Callback<CreateEntryParameter, Entry<?>> factory) {
Objects.requireNonNull(factory);
entryFactoryProperty().set(factory);
}
/*
* Calendar source callback.
*/
/**
* The parameter object passed to the calendar source factory.
*
* @see DateControl#setCalendarSourceFactory(Callback)
*/
public static final class CreateCalendarSourceParameter {
private DateControl dateControl;
/**
* Constructs a new parameter object.
*
* @param dateControl the control where the source will be added
*/
public CreateCalendarSourceParameter(DateControl dateControl) {
this.dateControl = requireNonNull(dateControl);
}
/**
* The control where the source will be added.
*
* @return the date control
*/
public DateControl getDateControl() {
return dateControl;
}
}
private final ObjectProperty<Callback<CreateCalendarSourceParameter, CalendarSource>> calendarSourceFactory = new SimpleObjectProperty<>(this, "calendarSourceFactory"); //$NON-NLS-1$
/**
* A factory for creating a new calendar source, e.g. a new Google calendar
* account.
* <p>
* <h2>Code Example</h2> The code below shows the default implementation of
* this factory. Applications can choose to bring up a full featured user
* interface / dialog to specify the exact location of the source (either
* locally or over a network). A local calendar source might read its data
* from an XML file while a remote source could load data from a web
* service.
* <p>
* <pre>
* setCalendarSourceFactory(param -> {
* CalendarSource source = new CalendarSource("Calendar Source");
* Calendar calendar = new Calendar("Calendar");
* source.getCalendars().add(calendar);
* return source;
* });
* </pre>
* <p>
* The factory can be invoked by calling {@link #createCalendarSource()}.
*
* @return the calendar source factory
* @see #createCalendarSource()
*/
public final ObjectProperty<Callback<CreateCalendarSourceParameter, CalendarSource>> calendarSourceFactoryProperty() {
return calendarSourceFactory;
}
/**
* Returns the value of {@link #calendarSourceFactoryProperty()}.
*
* @return the calendar source factory
*/
public final Callback<CreateCalendarSourceParameter, CalendarSource> getCalendarSourceFactory() {
return calendarSourceFactoryProperty().get();
}
/**
* Sets the value of {@link #calendarSourceFactoryProperty()}.
*
* @param callback the callback used for creating a new calendar source
*/
public final void setCalendarSourceFactory(Callback<CreateCalendarSourceParameter, CalendarSource> callback) {
calendarSourceFactoryProperty().set(callback);
}
/*
* Context menu callback for entries.
*/
/**
* The parameter object passed to the context menu callback for entries.
*
* @see DateControl#entryContextMenuCallbackProperty()
*/
public static final class EntryContextMenuParameter extends ContextMenuParameterBase {
private EntryViewBase<?> entryView;
/**
* Constructs a new context menu parameter object.
*
* @param evt the event that triggered the context menu
* @param control the date control where the event occurred
* @param entryView the entry view for which the context menu will be created
*/
public EntryContextMenuParameter(ContextMenuEvent evt, DateControl control, EntryViewBase<?> entryView) {
super(evt, control);
this.entryView = requireNonNull(entryView);
}
/**
* The entry view for which the context menu will be shown.
*
* @return the entry view
*/
public EntryViewBase<?> getEntryView() {
return entryView;
}
/**
* Convenience method to easily lookup the entry for which the view was
* created.
*
* @return the calendar entry
*/
public Entry<?> getEntry() {
return entryView.getEntry();
}
/**
* Convenience method to easily lookup the calendar of the entry for
* which the view was created.
*
* @return the calendar
*/
public Calendar getCalendar() {
return getEntry().getCalendar();
}
@Override
public String toString() {
return "EntryContextMenuParameter [entry=" + entryView //$NON-NLS-1$
+ ", dateControl =" + getDateControl() + "]"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
// entry edit support
/**
* Possible edit operations on an entry. This enum will be used as parameter of the
* callback set with {@link DateControl#setEntryEditPolicy}.
*
* @see #setEntryEditPolicy(Callback)
*/
public enum EditOperation {
/**
* Checked if the start of an entry can be changed.
*/
CHANGE_START,
/**
* Checked if the end of an entry can be changed.
*/
CHANGE_END,
/**
* Checked if entry can be moved around, hence changing start and end time at
* the same time.
*/
MOVE,
/**
* Checked if an entry can be deleted.
*/
DELETE
}
/**
* Class used for parameter of {@link DateControl#entryEditPolicy}
* functional interface.
*/
public static final class EntryEditParameter {
/**
* The date control the entity is associated with.
*/
private final DateControl dateControl;
/**
* The entity the operation is operated on.
*/
private final Entry<?> entry;
/**
* The operation.
*/
private final DateControl.EditOperation editOperation;
public EntryEditParameter(DateControl dateControl, Entry<?> entry, EditOperation editOperation) {
this.dateControl = Objects.requireNonNull(dateControl);
this.entry = Objects.requireNonNull(entry);
this.editOperation = Objects.requireNonNull(editOperation);
}
/**
* The {@link DateControl} which is asking for a specific {@link DateControl.EditOperation} permission.
* @return The date control.
*/
public DateControl getDateControl() {
return dateControl;
}
/**
* The entry where the {@link com.calendarfx.view.DateControl.EditOperation} should be applied.
*
* @return The entry.
*/
public Entry<?> getEntry() {
return entry;
}
/**
* The actual edit operation.
*
* @return The edit operation.
*/
public EditOperation getEditOperation() {
return editOperation;
}
@Override
public String toString() {
return "EntryEditParameter{" +
"dateControl=" + dateControl +
", entry=" + entry +
", editOperation=" + editOperation +
'}';
}
}
private final ObjectProperty<Callback<EntryEditParameter, Boolean>> entryEditPolicy = new SimpleObjectProperty<>(action -> false);
/**
* A property that stores a callback used for editing entries. If an edit operation will be executed
* on an entry then the callback will be invoked to determine if the operation is allowed. By default
* all operations listed inside {@link EditOperation} are allowed.
*
* @see EditOperation
*/
public final ObjectProperty<Callback<EntryEditParameter, Boolean>> entryEditPolicyProperty() {
return entryEditPolicy;
}
/**
* Returns the value of {@link #entryEditPolicy}.
*
* @return The entry edit policy callback
*
* @see EditOperation
*/
public final Callback<EntryEditParameter, Boolean> getEntryEditPolicy() {
return entryEditPolicy.get();
}
/**
* Sets the value of {@link #entryEditPolicy}.
*
* @param policy the entry edit policy callback
*
* @see EditOperation
*/
public final void setEntryEditPolicy(Callback<EntryEditParameter, Boolean> policy) {
Objects.requireNonNull(policy, "The edit entry policy can not be null");
this.entryEditPolicy.set(policy);
}
private final ObjectProperty<Callback<EntryContextMenuParameter, ContextMenu>> entryContextMenuCallback = new SimpleObjectProperty<>(this, "entryFactory"); //$NON-NLS-1$
/**
* A callback used for dynamically creating a context menu for a given
* entry view.
* <p>
* <h2>Code Example</h2> The code below shows the default implementation of
* this callback.
* <p>
* <p>
* <pre>
* setEntryContextMenuCallback(param -> {
* EntryViewBase<?> entryView = param.getEntryView();
* Entry<?> entry = entryView.getEntry();
*
* ContextMenu contextMenu = new ContextMenu();
*
* MenuItem informationItem = new MenuItem("Information");
* informationItem.setOnAction(evt -> {
* Callback<EntryDetailsParameter, Boolean> detailsCallback = getEntryDetailsCallback();
* if (detailsCallback != null) {
* ContextMenuEvent ctxEvent = param.getContextMenuEvent();
* EntryDetailsParameter entryDetailsParam = new EntryDetailsParameter(ctxEvent, DateControl.this, entryView, this, ctxEvent.getScreenX(), ctxEvent.getScreenY());
* detailsCallback.call(entryDetailsParam);
* }
* });
* contextMenu.getItems().add(informationItem);
*
* Menu calendarMenu = new Menu("Calendar");
* for (Calendar calendar : getCalendars()) {
* MenuItem calendarItem = new MenuItem(calendar.getName());
* calendarItem.setOnAction(evt -> entry.setCalendar(calendar));
* calendarMenu.getItems().add(calendarItem);
* }
* contextMenu.getItems().add(calendarMenu);
*
* return contextMenu;
* });
* </pre>
*
* @return the property used for storing the callback
*/
public final ObjectProperty<Callback<EntryContextMenuParameter, ContextMenu>> entryContextMenuCallbackProperty() {
return entryContextMenuCallback;
}
/**
* Returns the value of {@link #entryContextMenuCallbackProperty()}.
*
* @return the callback for creating a context menu for a given calendar
* entry
*/
public final Callback<EntryContextMenuParameter, ContextMenu> getEntryContextMenuCallback() {
return entryContextMenuCallbackProperty().get();
}
/**
* Sets the value of {@link #entryContextMenuCallbackProperty()}.
*
* @param callback the callback used for creating a context menu for a calendar
* entry
*/
public final void setEntryContextMenuCallback(Callback<EntryContextMenuParameter, ContextMenu> callback) {
entryContextMenuCallbackProperty().set(callback);
}
/*
* Context menu callback.
*/
/**
* The parameter object passed to the context menu callback.
*
* @see DateControl#contextMenuCallbackProperty()
*/
public static final class ContextMenuParameter extends ContextMenuParameterBase {
private Calendar calendar;
private ZonedDateTime zonedDateTime;
/**
* Constructs a new parameter object.
*
* @param evt the event that triggered the context menu
* @param dateControl the date control where the event occurred
* @param calendar the (default) calendar where newly created entries should
* be added
* @param time the time where the mouse click occurred
*/
public ContextMenuParameter(ContextMenuEvent evt, DateControl dateControl, Calendar calendar, ZonedDateTime time) {
super(evt, dateControl);
this.calendar = requireNonNull(calendar);
this.zonedDateTime = time;
}
/**
* The (default) calendar where newly created entries should be added.
* Only relevant if the context menu is actually used for creating new
* entries. This can be different from application to application.
*
* @return the (default) calendar for adding new entries
*/
public Calendar getCalendar() {
return calendar;
}
/**
* The time where the mouse click occurred.
*
* @return the time shown at the mouse click location
*/
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
@Override
public String toString() {
return "ContextMenuParameter [calendar=" + calendar //$NON-NLS-1$
+ ", zonedDateTime=" + zonedDateTime + "]"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
private final ObjectProperty<Callback<ContextMenuParameter, ContextMenu>> contextMenuCallback = new SimpleObjectProperty<>(this, "contextMenuCallback"); //$NON-NLS-1$
/**
* The context menu callback that will be invoked when the user triggers the
* context menu by clicking in an area without an entry view. Using a
* callback allows the application to create context menus with different
* content, depending on the current state of the application and the
* location of the click.
* <p>
* <h2>Code Example</h2>
* <p>
* The code below shows a part of the default implementation:
* <p>
* <p>
* <pre>
* setContextMenuCallback(param -> {
* ContextMenu menu = new ContextMenu();
* MenuItem newEntryItem = new MenuItem("Add New Event");
* newEntryItem.setOnAction(evt -> {
* createEntryAt(param.getZonedDateTime());
* });
* menu.getItems().add(newEntry);
* return menu;
* });
* </pre>
*
* @return the context menu callback
*/
public final ObjectProperty<Callback<ContextMenuParameter, ContextMenu>> contextMenuCallbackProperty() {
return contextMenuCallback;
}
/**
* Returns the value of {@link #contextMenuCallbackProperty()}.
*
* @return the context menu callback
*/
public final Callback<ContextMenuParameter, ContextMenu> getContextMenuCallback() {
return contextMenuCallbackProperty().get();
}
/**
* Sets the value of {@link #contextMenuCallbackProperty()}.
*
* @param callback the context menu callback
*/
public final void setContextMenuCallback(Callback<ContextMenuParameter, ContextMenu> callback) {
contextMenuCallbackProperty().set(callback);
}
/*
* Default calendar provider callback.
*/
private final ObjectProperty<Callback<DateControl, Calendar>> defaultCalendarProvider = new SimpleObjectProperty<>(this, "defaultCalendarProvider"); //$NON-NLS-1$
/**
* The default calendar provider is responsible for returning a calendar
* that can be used to add a new entry. This way the user can add new
* entries by simply double clicking inside the view without the need of
* first showing a calendar selection UI. This can be changed by setting a
* callback that prompts the user with a dialog.
* <p>
* <h2>Code Example</h2>
* <p>
* The code shown below is the default implementation of this provider. It
* returns the first calendar of the first source. If no source is available
* it will return null.
* <p>
* <p>
* <pre>
* setDefaultCalendarProvider(control -> {
* List<CalendarSource> sources = getCalendarSources();
* if (sources != null && !sources.isEmpty()) {
* CalendarSource s = sources.get(0);
* List<? extends Calendar> calendars = s.getCalendars();
* if (calendars != null && !calendars.isEmpty()) {
* return calendars.get(0);
* }
* }
*
* return null;
* });
* </pre>
*
* @return the default calendar provider callback
*/
public final ObjectProperty<Callback<DateControl, Calendar>> defaultCalendarProviderProperty() {
return defaultCalendarProvider;
}
/**
* Returns the value of {@link #defaultCalendarProviderProperty()}.
*
* @return the default calendar provider
*/
public final Callback<DateControl, Calendar> getDefaultCalendarProvider() {
return defaultCalendarProviderProperty().get();
}
/**
* Sets the value of {@link #defaultCalendarProviderProperty()}.
*
* @param provider the default calendar provider
*/
public final void setDefaultCalendarProvider(Callback<DateControl, Calendar> provider) {
requireNonNull(provider);
defaultCalendarProviderProperty().set(provider);
}
private void updateCalendarList() {
List<Calendar> removedCalendars = new ArrayList<>(calendars);
List<Calendar> newCalendars = new ArrayList<>();
for (CalendarSource source : getCalendarSources()) {
for (Calendar calendar : source.getCalendars()) {
if (calendars.contains(calendar)) {
removedCalendars.remove(calendar);
} else {
newCalendars.add(calendar);
}
}
source.getCalendars().removeListener(weakUpdateCalendarListListener);
source.getCalendars().addListener(weakUpdateCalendarListListener);
}
calendars.addAll(newCalendars);
calendars.removeAll(removedCalendars);
}
private abstract static class DetailsParameter {
private InputEvent inputEvent;
private DateControl dateControl;
private Node owner;
private double screenX;
private double screenY;
/**
* Constructs a new parameter object.
*
* @param inputEvent the input event that triggered the need for showing entry
* details (e.g. a mouse double click, or a context menu item
* selection)
* @param control the control where the event occurred
* @param owner a node that can be used as an owner for the dialog or
* popover
* @param screenX the screen location where the event occurred
* @param screenY the screen location where the event occurred
*/
public DetailsParameter(InputEvent inputEvent, DateControl control, Node owner, double screenX, double screenY) {
this.inputEvent = inputEvent;
this.dateControl = requireNonNull(control);
this.owner = requireNonNull(owner);
this.screenX = screenX;
this.screenY = screenY;
}
/**
* Returns the node that should be used as the owner of a dialog /
* popover. We should not use the entry view as the owner of a dialog /
* popover because views come and go. We need something that lives
* longer.
*
* @return an owner node for the details dialog / popover
*/
public Node getOwner() {
return owner;
}
/**
* The screen X location where the event occurred.
*
* @return the screen x location of the event
*/
public double getScreenX() {
return screenX;
}
/**
* The screen Y location where the event occurred.
*
* @return the screen y location of the event
*/
public double getScreenY() {
return screenY;
}
/**
* The input event that triggered the need for showing entry details
* (e.g. a mouse double click or a context menu item selection).
*
* @return the input event
*/
public InputEvent getInputEvent() {
return inputEvent;
}
/**
* The date control where the event occurred.
*
* @return the date control
*/
public DateControl getDateControl() {
return dateControl;
}
}
/**
* The parameter object passed to the entry details callback.
*
* @see DateControl#entryDetailsCallbackProperty()
*/
public final static class EntryDetailsParameter extends DetailsParameter {
private Entry<?> entry;
/**
* Constructs a new parameter object.
*
* @param inputEvent the input event that triggered the need for showing entry
* details (e.g. a mouse double click, or a context menu item
* selection)
* @param control the control where the event occurred
* @param entry the entry for which details are requested
* @param owner a node that can be used as an owner for the dialog or
* popover
* @param screenX the screen location where the event occurred
* @param screenY the screen location where the event occurred
*/
public EntryDetailsParameter(InputEvent inputEvent, DateControl control, Entry<?> entry, Node owner, double screenX, double screenY) {
super(inputEvent, control, owner, screenX, screenY);
this.entry = entry;
}
/**
* The entry for which details are requested.
*
* @return the entry view
*/
public Entry<?> getEntry() {
return entry;
}
}
/**
* The parameter object passed to the date details callback.
*
* @see DateControl#dateDetailsCallbackProperty()
*/
public final static class DateDetailsParameter extends DetailsParameter {
private LocalDate localDate;
/**
* Constructs a new parameter object.
*
* @param inputEvent the input event that triggered the need for showing entry
* details (e.g. a mouse double click, or a context menu item
* selection)
* @param control the control where the event occurred
* @param date the date for which details are required
* @param owner a node that can be used as an owner for the dialog or
* popover
* @param screenX the screen location where the event occurred
* @param screenY the screen location where the event occurred
*/
public DateDetailsParameter(InputEvent inputEvent, DateControl control, Node owner, LocalDate date, double screenX, double screenY) {
super(inputEvent, control, owner, screenX, screenY);
this.localDate = requireNonNull(date);
}
/**
* The date for which details are required.
*
* @return the date
*/
public LocalDate getLocalDate() {
return localDate;
}
}
private final ObjectProperty<Callback<DateDetailsParameter, Boolean>> dateDetailsCallback = new SimpleObjectProperty<>(this, "dateDetailsCallback"); //$NON-NLS-1$
/**
* A callback used for showing the details of a given date. The default
* implementation of this callback displays a small {@link PopOver} but
* applications might as well display a large dialog where the user can
* freely edit the date.
* <p>
* <h2>Code Example</h2> The code below shows the default implementation
* used by all date controls. It delegates to a private method that shows
* the popover.
* <p>
* <pre>
* setDateDetailsCallback(param -> {
* InputEvent evt = param.getInputEvent();
* if (evt instanceof MouseEvent) {
* MouseEvent mouseEvent = (MouseEvent) evt;
* if (mouseEvent.getClickCount() == 1) {
* showDateDetails(param.getOwner(), param.getLocalDate());
* return true;
* }
* }
*
* return false;
* });
* </pre>
*
* @return the callback for showing details for a given date
*/
public final ObjectProperty<Callback<DateDetailsParameter, Boolean>> dateDetailsCallbackProperty() {
return dateDetailsCallback;
}
/**
* Sets the value of {@link #dateDetailsCallbackProperty()}.
*
* @param callback the date details callback
*/
public final void setDateDetailsCallback(Callback<DateDetailsParameter, Boolean> callback) {
requireNonNull(callback);
dateDetailsCallbackProperty().set(callback);
}
/**
* Returns the value of {@link #dateDetailsCallbackProperty()}.
*
* @return the date details callback
*/
public final Callback<DateDetailsParameter, Boolean> getDateDetailsCallback() {
return dateDetailsCallbackProperty().get();
}
private final ObjectProperty<Callback<EntryDetailsParameter, Boolean>> entryDetailsCallback = new SimpleObjectProperty<>(this, "entryDetailsCallback"); //$NON-NLS-1$
/**
* A callback used for showing the details of a given entry. The default
* implementation of this callback displays a small {@link PopOver} but
* applications might as well display a large dialog where the user can
* freely edit the entry.
* <p>
* <h2>Code Example</h2> The code below shows the default implementation
* used by all date controls. It delegates to a private method that shows
* the popover.
* <p>
* <pre>
* setEntryDetailsCallback(param -> {
* InputEvent evt = param.getInputEvent();
* if (evt instanceof MouseEvent) {
* MouseEvent mouseEvent = (MouseEvent) evt;
* if (mouseEvent.getClickCount() == 2) {
* showEntryDetails(param.getEntryView(), param.getOwner(), param.getScreenX(), param.getScreenY());
* return true;
* }
* } else {
* showEntryDetails(param.getEntryView(), param.getOwner(), param.getScreenX(), param.getScreenY());
* return true;
* }
*
* return false;
* });
* </pre>
*
* @return the callback used for showing details for a given entry
*/
public final ObjectProperty<Callback<EntryDetailsParameter, Boolean>> entryDetailsCallbackProperty() {
return entryDetailsCallback;
}
/**
* Sets the value of {@link #entryDetailsCallbackProperty()}.
*
* @param callback the entry details callback
*/
public final void setEntryDetailsCallback(Callback<EntryDetailsParameter, Boolean> callback) {
requireNonNull(callback);
entryDetailsCallbackProperty().set(callback);
}
/**
* Returns the value of {@link #entryDetailsCallbackProperty()}.
*
* @return the entry details callback
*/
public final Callback<EntryDetailsParameter, Boolean> getEntryDetailsCallback() {
return entryDetailsCallbackProperty().get();
}
////////////
/**
* The parameter object passed to the entry details popover content
* callback.
*
* @see DateControl#entryDetailsPopOverContentCallbackProperty()
*/
public final static class EntryDetailsPopOverContentParameter {
private DateControl dateControl;
private Node node;
private Entry<?> entry;
private PopOver popOver;
/**
* Constructs a new parameter object.
*
* @param popOver the pop over for which details will be created
* @param control the control where the event occurred
* @param node the node where the event occurred
* @param entry the entry for which details will be shown
*/
public EntryDetailsPopOverContentParameter(PopOver popOver, DateControl control, Node node, Entry<?> entry) {
this.popOver = requireNonNull(popOver);
this.dateControl = requireNonNull(control);
this.node = requireNonNull(node);
this.entry = requireNonNull(entry);
}
/**
* Returns the popover in which the content will be shown.
*
* @return the popover
*/
public PopOver getPopOver() {
return popOver;
}
/**
* The date control where the popover was requested.
*
* @return the date control
*/
public DateControl getDateControl() {
return dateControl;
}
/**
* The node for which the popover was requested.
*
* @return the node
*/
public Node getNode() {
return node;
}
/**
* The entry for which the popover was requested.
*
* @return the entry
*/
public Entry<?> getEntry() {
return entry;
}
}
private final ObjectProperty<Callback<EntryDetailsPopOverContentParameter, Node>> entryDetailsPopoverContentCallback = new SimpleObjectProperty<>(this, "entryDetailsPopoverContentCallback"); //$NON-NLS-1$
/**
* Stores a callback for creating the content of the popover.
*
* @return the popover content callback
*/
public final ObjectProperty<Callback<EntryDetailsPopOverContentParameter, Node>> entryDetailsPopOverContentCallbackProperty() {
return entryDetailsPopoverContentCallback;
}
/**
* Sets the value of {@link #entryDetailsPopOverContentCallbackProperty()}.
*
* @param callback the entry details popover content callback
*/
public final void setEntryDetailsPopOverContentCallback(Callback<EntryDetailsPopOverContentParameter, Node> callback) {
requireNonNull(callback);
entryDetailsPopOverContentCallbackProperty().set(callback);
}
/**
* Returns the value of
* {@link #entryDetailsPopOverContentCallbackProperty()}.
*
* @return the entry details popover content callback
*/
public final Callback<EntryDetailsPopOverContentParameter, Node> getEntryDetailsPopOverContentCallback() {
return entryDetailsPopOverContentCallbackProperty().get();
}
///////////
private final ObjectProperty<LocalDate> today = new SimpleObjectProperty<>(this, "today", LocalDate.now()); //$NON-NLS-1$
/**
* Stores the date that is considered to represent "today". This property is
* initialized with {@link LocalDate#now()} but can be any date.
*
* @return the date representing "today"
*/
public final ObjectProperty<LocalDate> todayProperty() {
return today;
}
/**
* Sets the value of {@link #todayProperty()}.
*
* @param date the date representing "today"
*/
public final void setToday(LocalDate date) {
requireNonNull(date);
todayProperty().set(date);
}
/**
* Returns the value of {@link #todayProperty()}.
*
* @return the date representing "today"
*/
public final LocalDate getToday() {
return todayProperty().get();
}
private final BooleanProperty showToday = new SimpleBooleanProperty(
this, "showToday", true); //$NON-NLS-1$
/**
* A flag used to indicate that the view will mark the area that represents
* the value of {@link #todayProperty()}. By default this area will be
* filled with a different color (red) than the rest (white).
* <p/>
* <center><img src="doc-files/all-day-view-today.png"></center>
*
* @return true if today will be shown differently
*/
public final BooleanProperty showTodayProperty() {
return showToday;
}
/**
* Returns the value of {@link #showTodayProperty()}.
*
* @return true if today will be highlighted visually
*/
public final boolean isShowToday() {
return showTodayProperty().get();
}
/**
* Sets the value of {@link #showTodayProperty()}.
*
* @param show if true today will be highlighted visually
*/
public final void setShowToday(boolean show) {
showTodayProperty().set(show);
}
private final ObjectProperty<LocalDate> date = new SimpleObjectProperty<>(this, "date", LocalDate.now()); //$NON-NLS-1$
/**
* The date that needs to be shown by the date control. This property is
* initialized with {@link LocalDate#now()}.
*
* @return the date shown by the control
*/
public final ObjectProperty<LocalDate> dateProperty() {
return date;
}
/**
* Sets the value of {@link #dateProperty()}.
*
* @param date the date shown by the control
*/
public final void setDate(LocalDate date) {
requireNonNull(date);
dateProperty().set(date);
}
/**
* Returns the value of {@link #dateProperty()}.
*
* @return the date shown by the control
*/
public final LocalDate getDate() {
return dateProperty().get();
}
private final ObjectProperty<ZoneId> zoneId = new SimpleObjectProperty<>(this, "zoneId", ZoneId.systemDefault()); //$NON-NLS-1$
/**
* The time zone used by the date control. Entries and date controls might
* use different time zones resulting in different layout of entry views.
* <p>
* #see {@link Entry#zoneIdProperty()}
*
* @return the time zone used by the date control for calculating entry view
* layouts
*/
public final ObjectProperty<ZoneId> zoneIdProperty() {
return zoneId;
}
/**
* Sets the value of {@link #zoneIdProperty()}.
*
* @param zoneId the time zone
*/
public final void setZoneId(ZoneId zoneId) {
requireNonNull(zoneId);
zoneIdProperty().set(zoneId);
}
/**
* Returns the value of {@link #zoneIdProperty()}.
*
* @return the time zone
*/
public final ZoneId getZoneId() {
return zoneIdProperty().get();
}
private final ObjectProperty<LocalTime> time = new SimpleObjectProperty<>(this, "time", LocalTime.now()); //$NON-NLS-1$
/**
* Stores a time that can be visualized, e.g. the thin line in
* {@link DayView} representing the current time.
*
* @return the current time
*/
public final ObjectProperty<LocalTime> timeProperty() {
return time;
}
/**
* Sets the value of {@link #timeProperty()}.
*
* @param time the current time
*/
public final void setTime(LocalTime time) {
requireNonNull(time);
timeProperty().set(time);
}
/**
* Returns the value of {@link #timeProperty()}.
*
* @return the current time
*/
public final LocalTime getTime() {
return timeProperty().get();
}
private final ObjectProperty<LocalTime> startTime = new SimpleObjectProperty<>(this, "startTime", LocalTime.of(6, 0)); //$NON-NLS-1$
/**
* A start time used to limit the time interval shown by the control. The
* {@link DayView} uses this property and the {@link #endTimeProperty()} to
* support the concept of "early" and "late" hours. These hours can be
* hidden if required.
*
* @return the start time
*/
public final ObjectProperty<LocalTime> startTimeProperty() {
return startTime;
}
/**
* Returns the value of {@link #startTimeProperty()}.
*
* @return the start time
*/
public final LocalTime getStartTime() {
return startTimeProperty().get();
}
/**
* Sets the value of {@link #startTimeProperty()}.
*
* @param time the start time
*/
public final void setStartTime(LocalTime time) {
startTimeProperty().set(time);
}
private final ObjectProperty<LocalTime> endTime = new SimpleObjectProperty<>(this, "endTime", LocalTime.of(22, 0)); //$NON-NLS-1$
/**
* An end time used to limit the time interval shown by the control. The
* {@link DayView} uses this property and the {@link #startTimeProperty()}
* to support the concept of "early" and "late" hours. These hours can be
* hidden if required.
*
* @return the end time
*/
public final ObjectProperty<LocalTime> endTimeProperty() {
return endTime;
}
/**
* Returns the value of {@link #endTimeProperty()}.
*
* @return the end time
*/
public final LocalTime getEndTime() {
return endTimeProperty().get();
}
/**
* Sets the value of {@link #endTimeProperty()}.
*
* @param time the end time
*/
public final void setEndTime(LocalTime time) {
endTimeProperty().set(time);
}
private final ObjectProperty<WeekFields> weekFields = new SimpleObjectProperty<>(this, "weekFields", WeekFields.of(Locale.getDefault())); //$NON-NLS-1$
/**
* Week fields are used to determine the first day of a week (e.g. "Monday"
* in Germany or "Sunday" in the US). It is also used to calculate the week
* number as the week fields determine how many days are needed in the first
* week of a year. This property is initialized with {@link WeekFields#ISO}.
*
* @return the week fields
*/
public final ObjectProperty<WeekFields> weekFieldsProperty() {
return weekFields;
}
/**
* Sets the value of {@link #weekFieldsProperty()}.
*
* @param weekFields the new week fields
*/
public final void setWeekFields(WeekFields weekFields) {
requireNonNull(weekFields);
weekFieldsProperty().set(weekFields);
}
/**
* Returns the value of {@link #weekFieldsProperty()}.
*
* @return the week fields
*/
public final WeekFields getWeekFields() {
return weekFieldsProperty().get();
}
/**
* A convenience method to lookup the first day of the week ("Monday" in
* Germany, "Sunday" in the US). This method delegates to
* {@link WeekFields#getFirstDayOfWeek()}.
*
* @return the first day of the week
* @see #weekFieldsProperty()
*/
public final DayOfWeek getFirstDayOfWeek() {
return getWeekFields().getFirstDayOfWeek();
}
private final ReadOnlyListWrapper<Calendar> calendars = new ReadOnlyListWrapper<>(FXCollections.observableArrayList());
/**
* A list that contains all calendars found in all calendar sources
* currently attached to this date control. This is a convenience list that
* "flattens" the two level structure of sources and their calendars. It is
* a read-only list because calendars can not be added directly to a date
* control. Instead they are added to calendar sources and those sources are
* then added to the control.
*
* @return the list of all calendars shown by this control
* @see #getCalendarSources()
*/
public final ReadOnlyListProperty<Calendar> calendarsProperty() {
return calendars.getReadOnlyProperty();
}
private final ObservableList<Calendar> unmodifiableCalendars = FXCollections.unmodifiableObservableList(calendars.get());
/**
* Returns the value of {@link #calendarsProperty()}.
*
* @return the list of all calendars shown by this control
*/
public final ObservableList<Calendar> getCalendars() {
return unmodifiableCalendars;
}
private final ObservableList<CalendarSource> calendarSources = FXCollections.observableArrayList();
/**
* The list of all calendar sources attached to this control. The calendars
* found in all sources are also added to the read-only list that can be
* retrieved by calling {@link #getCalendars()}.
*
* @return the calendar sources
* @see #calendarSourceFactoryProperty()
*/
public final ObservableList<CalendarSource> getCalendarSources() {
return calendarSources;
}
private final ObjectProperty<SelectionMode> selectionMode = new SimpleObjectProperty<>(this, "selectionMode", SelectionMode.MULTIPLE); //$NON-NLS-1$
/**
* Stores the selection mode. All date controls support single and multiple
* selections.
*
* @return the selection mode
* @see SelectionMode
*/
public final ObjectProperty<SelectionMode> selectionModeProperty() {
return selectionMode;
}
/**
* Sets the value of {@link #selectionModeProperty()}.
*
* @param mode the selection mode (single, multiple)
*/
public final void setSelectionMode(SelectionMode mode) {
requireNonNull(mode);
selectionModeProperty().set(mode);
}
/**
* Returns the value of {@link #selectionModeProperty()}.
*
* @return the selection mode (single, multiple)
*/
public final SelectionMode getSelectionMode() {
return selectionModeProperty().get();
}
private final ObservableSet<Entry<?>> selections = FXCollections.observableSet();
/**
* Stores the currently selected entries.
*
* @return the set of currently selected entries
*/
public final ObservableSet<Entry<?>> getSelections() {
return selections;
}
/**
* Adds the given entry to the set of currently selected entries.
*
* @param entry the selected entries
* @see #deselect(Entry)
* @see #getSelections()
*/
public final void select(Entry<?> entry) {
requireNonNull(entry);
selections.add(entry);
}
/**
* Removes the given entry from the set of currently selected entries.
*
* @param entry the selected entries
* @see #select(Entry)
* @see #getSelections()
*/
public final void deselect(Entry<?> entry) {
requireNonNull(entry);
selections.remove(entry);
}
/**
* Clears the current selection of entries.
*/
public final void clearSelection() {
getSelections().clear();
}
private final ObjectProperty<VirtualGrid> virtualGrid = new SimpleObjectProperty<>(this, "virtualGrid", //$NON-NLS-1$
new VirtualGrid(Messages.getString("DateControl.DEFAULT_VIRTUAL_GRID_NAME"), Messages.getString("DateControl.DEFAULT_VIRTUAL_GRID_SHORT_NAME"), ChronoUnit.MINUTES, 15)); //$NON-NLS-1$ //$NON-NLS-2$
/**
* A virtual grid used for snapping to invisible grid lines while editing
* calendar entries. Using a virtual grid makes it easier to edit entries so
* that they all start at exactly the same time. The default grid is set to
* "5 Minutes". {@link VirtualGrid#OFF} can be used to completely disable
* the grid.
*
* @return the virtual grid
*/
public final ObjectProperty<VirtualGrid> virtualGridProperty() {
return virtualGrid;
}
/**
* Returns the value of {@link #virtualGridProperty()}.
*
* @return the currently active grid
*/
public final VirtualGrid getVirtualGrid() {
return virtualGridProperty().get();
}
/**
* Sets the value of {@link #virtualGridProperty()}.
*
* @param grid the grid
*/
public final void setVirtualGrid(VirtualGrid grid) {
requireNonNull(grid);
virtualGridProperty().set(grid);
}
private final ObjectProperty<LocalTime> requestedTime = new SimpleObjectProperty<>(this, "requestedTime", LocalTime.now()); //$NON-NLS-1$
/**
* Stores the time that the application wants to show in its date controls
* when the UI opens up. Most applications will normally set this time to
* {@link LocalTime#now()}.
*
* @return the requested time
*/
public final ObjectProperty<LocalTime> requestedTimeProperty() {
return requestedTime;
}
/**
* Sets the value of {@link #requestedTimeProperty()}.
*
* @param time the requested time
*/
public final void setRequestedTime(LocalTime time) {
requestedTimeProperty().set(time);
}
/**
* Returns the value of {@link #requestedTimeProperty()}.
*
* @return the requested time
*/
public final LocalTime getRequestedTime() {
return requestedTimeProperty().get();
}
/**
* Supported layout strategies by the {@link DayView}.
*/
public enum Layout {
/**
* The standard layout lays out calendar entries in the most efficient
* way without distinguishing between different calendars. This is the
* layout found in most calendar software.
*/
STANDARD,
/**
* The swimlane layout creates virtual columns, one for each calendar.
* The entries of the calendars are shown in their own column. This
* layout strategy is often found in resource booking systems (e.g. one
* calendar per room / per person / per truck).
*/
SWIMLANE
}
private final ObjectProperty<Layout> layout = new SimpleObjectProperty<>(this, "layout", Layout.STANDARD); //$NON-NLS-1$
/**
* Stores the strategy used by the view to layout the entries of several
* calendars at once. The standard layout ignores the source calendar of an
* entry and finds the next available place in the UI that satisfies the
* time bounds of the entry. The {@link Layout#SWIMLANE} strategy allocates
* a separate column for each calendar and resolves overlapping entry
* conflicts within that column. Swim lanes are especially useful for
* resource booking systems (rooms, people, trucks).
*
* @return the layout strategy of the view
*/
public final ObjectProperty<Layout> layoutProperty() {
return layout;
}
/**
* Sets the value of {@link #layoutProperty()}.
*
* @param layout the layout
*/
public final void setLayout(Layout layout) {
requireNonNull(layout);
layoutProperty().set(layout);
}
/**
* Returns the value of {@link #layoutProperty()}.
*
* @return the layout strategy
*/
public final Layout getLayout() {
return layoutProperty().get();
}
private ObservableSet<DayOfWeek> weekendDays = FXCollections.observableSet();
/**
* Returns the days of the week that are considered to be weekend days, for
* example Saturday and Sunday, or Friday and Saturday.
*
* @return the weekend days
*/
public ObservableSet<DayOfWeek> getWeekendDays() {
return weekendDays;
}
/**
* Makes the control go forward in time by adding one or more days to the
* current date. Subclasses override this method to adjust it to their
* needs, e.g. the {@link DetailedWeekView} adds the number of days found in
* {@link DetailedWeekView#getNumberOfDays()}.
*
* @see #dateProperty()
*/
public void goForward() {
setDate(getDate().plusDays(1));
}
/**
* Makes the control go forward in time by removing one or more days from
* the current date. Subclasses override this method to adjust it to their
* needs, e.g. the {@link DetailedWeekView} removes the number of days found in
* {@link DetailedWeekView#getNumberOfDays()}.
*
* @see #dateProperty()
*/
public void goBack() {
setDate(getDate().minusDays(1));
}
/**
* Makes the control go to "today".
*
* @see #dateProperty()
* @see #todayProperty()
*/
public void goToday() {
setDate(getToday());
}
/**
* Finds the first view that represents the given entry.
*
* @param entry the entry
* @return the view
*/
public final EntryViewBase<?> findEntryView(Entry<?> entry) {
requireNonNull(entry);
return doFindEntryView(this, entry);
}
private EntryViewBase<?> doFindEntryView(Parent parent, Entry<?> entry) {
EntryViewBase<?> result = null;
for (Node node : parent.getChildrenUnmodifiable()) {
if (node instanceof EntryViewBase) {
EntryViewBase<?> base = (EntryViewBase<?>) node;
if (base.getEntry().equals(entry)) {
result = base;
break;
}
} else if (node instanceof Parent) {
result = doFindEntryView((Parent) node, entry);
if (result != null) {
break;
}
}
}
return result;
}
private List<DateControl> boundDateControls = FXCollections.observableArrayList();
/**
* Returns all data controls that are bound to this control.
*
* @return the bound date controls / sub controls / children controls
*/
public final List<DateControl> getBoundDateControls() {
return boundDateControls;
}
// hyperlink support
private final BooleanProperty enableHyperlinks = new SimpleBooleanProperty(this, "enableHyperlinks", true);
/**
* A property used to control whether the control allows the user to click on it or an element
* inside of it in order to "jump" to another screen with more detail. Example: in the {@link CalendarView}
* the user can click on the "day of month" label of a cell inside the {@link MonthSheetView} in
* order to switch to the {@link DayPage} where the user will see all entries scheduled for that day.
*
* @return true if the support for hyperlinks is enabled
*/
public final BooleanProperty enableHyperlinksProperty() {
return enableHyperlinks;
}
/**
* Sets the value of the {@link #enableHyperlinksProperty()}.
*
* @param enable if true the hyperlink support will be enabled
*/
public final void setEnableHyperlinks(boolean enable) {
this.enableHyperlinks.set(enable);
}
/**
* Returns the value of the {@link #enableHyperlinksProperty()}.
*
* @return true if the hyperlink support is enabled
*/
public final boolean isEnableHyperlinks() {
return enableHyperlinks.get();
}
/**
* Binds several properties of the given date control to the same properties
* of this control. This kind of binding is needed to create UIs with nested
* date controls. The {@link CalendarView} for example consists of several
* pages. Each page is a date control that consists of several other date
* controls. The {@link DayPage} consists of the {@link AgendaView}, a
* single {@link DayView}, and a {@link YearMonthView} . All of these
* controls are bound to each other so that the application can simply
* change properties on the {@link CalendarView} without worrying about the
* nested controls.
*
* @param otherControl the control that will be bound to this control
* @param bindDate determines if the date property will also be bound
*/
public final void bind(DateControl otherControl, boolean bindDate) {
requireNonNull(otherControl);
boundDateControls.add(otherControl);
// bind maps
Bindings.bindContentBidirectional(otherControl.getCalendarVisibilityMap(), getCalendarVisibilityMap());
// bind lists
Bindings.bindContentBidirectional(otherControl.getCalendarSources(), getCalendarSources());
Bindings.bindContentBidirectional(otherControl.getSelections(), getSelections());
Bindings.bindContentBidirectional(otherControl.getWeekendDays(), getWeekendDays());
// bind properties
Bindings.bindBidirectional(otherControl.suspendUpdatesProperty(), suspendUpdatesProperty());
Bindings.bindBidirectional(otherControl.entryFactoryProperty(), entryFactoryProperty());
Bindings.bindBidirectional(otherControl.defaultCalendarProviderProperty(), defaultCalendarProviderProperty());
Bindings.bindBidirectional(otherControl.virtualGridProperty(), virtualGridProperty());
Bindings.bindBidirectional(otherControl.draggedEntryProperty(), draggedEntryProperty());
Bindings.bindBidirectional(otherControl.requestedTimeProperty(), requestedTimeProperty());
Bindings.bindBidirectional(otherControl.selectionModeProperty(), selectionModeProperty());
Bindings.bindBidirectional(otherControl.selectionModeProperty(), selectionModeProperty());
Bindings.bindBidirectional(otherControl.weekFieldsProperty(), weekFieldsProperty());
Bindings.bindBidirectional(otherControl.layoutProperty(), layoutProperty());
Bindings.bindBidirectional(otherControl.startTimeProperty(), startTimeProperty());
Bindings.bindBidirectional(otherControl.endTimeProperty(), endTimeProperty());
Bindings.bindBidirectional(otherControl.timeProperty(), timeProperty());
Bindings.bindBidirectional(otherControl.usagePolicyProperty(), usagePolicyProperty());
if (bindDate) {
Bindings.bindBidirectional(otherControl.dateProperty(), dateProperty());
}
Bindings.bindBidirectional(otherControl.todayProperty(), todayProperty());
Bindings.bindBidirectional(otherControl.zoneIdProperty(), zoneIdProperty());
// edit callbacks
Bindings.bindBidirectional(otherControl.entryDetailsCallbackProperty(), entryDetailsCallbackProperty());
Bindings.bindBidirectional(otherControl.dateDetailsCallbackProperty(), dateDetailsCallbackProperty());
Bindings.bindBidirectional(otherControl.contextMenuCallbackProperty(), contextMenuCallbackProperty());
Bindings.bindBidirectional(otherControl.entryContextMenuCallbackProperty(), entryContextMenuCallbackProperty());
Bindings.bindBidirectional(otherControl.calendarSourceFactoryProperty(), calendarSourceFactoryProperty());
Bindings.bindBidirectional(otherControl.entryDetailsPopOverContentCallbackProperty(), entryDetailsPopOverContentCallbackProperty());
Bindings.bindBidirectional(otherControl.entryEditPolicyProperty(), entryEditPolicyProperty());
}
/**
* Unbinds the given control from this control. Unbinding is done for all
* properties and observable lists that have previously been bound by the
* {@link #bind(DateControl, boolean)} method.
*
* @param otherControl the control to unbind
*/
public final void unbind(DateControl otherControl) {
requireNonNull(otherControl);
boundDateControls.remove(otherControl);
// unbind maps
Bindings.unbindContentBidirectional(otherControl.getCalendarVisibilityMap(), getCalendarVisibilityMap());
// unbind lists
Bindings.unbindContentBidirectional(otherControl.getCalendarSources(), getCalendarSources());
Bindings.unbindContentBidirectional(otherControl.getSelections(), getSelections());
// unbind properties
Bindings.unbindBidirectional(otherControl.suspendUpdatesProperty(), suspendUpdatesProperty());
Bindings.unbindBidirectional(otherControl.entryFactoryProperty(), entryFactoryProperty());
Bindings.unbindBidirectional(otherControl.defaultCalendarProviderProperty(), defaultCalendarProviderProperty());
Bindings.unbindBidirectional(otherControl.virtualGridProperty(), virtualGridProperty());
Bindings.unbindBidirectional(otherControl.draggedEntryProperty(), draggedEntryProperty());
Bindings.unbindBidirectional(otherControl.requestedTimeProperty(), requestedTimeProperty());
Bindings.unbindBidirectional(otherControl.selectionModeProperty(), selectionModeProperty());
Bindings.unbindBidirectional(otherControl.selectionModeProperty(), selectionModeProperty());
Bindings.unbindBidirectional(otherControl.weekFieldsProperty(), weekFieldsProperty());
Bindings.unbindBidirectional(otherControl.dateProperty(), dateProperty());
Bindings.unbindBidirectional(otherControl.todayProperty(), todayProperty());
Bindings.unbindBidirectional(otherControl.zoneIdProperty(), zoneIdProperty());
Bindings.unbindBidirectional(otherControl.layoutProperty(), layoutProperty());
Bindings.unbindBidirectional(otherControl.startTimeProperty(), startTimeProperty());
Bindings.unbindBidirectional(otherControl.endTimeProperty(), endTimeProperty());
Bindings.unbindBidirectional(otherControl.timeProperty(), timeProperty());
Bindings.unbindBidirectional(otherControl.usagePolicyProperty(), usagePolicyProperty());
// unbind callbacks
Bindings.unbindBidirectional(otherControl.entryDetailsCallbackProperty(), entryDetailsCallbackProperty());
Bindings.unbindBidirectional(otherControl.dateDetailsCallbackProperty(), dateDetailsCallbackProperty());
Bindings.unbindBidirectional(otherControl.contextMenuCallbackProperty(), contextMenuCallbackProperty());
Bindings.unbindBidirectional(otherControl.entryContextMenuCallbackProperty(), entryContextMenuCallbackProperty());
Bindings.unbindBidirectional(otherControl.calendarSourceFactoryProperty(), calendarSourceFactoryProperty());
Bindings.unbindBidirectional(otherControl.entryEditPolicyProperty(), entryEditPolicyProperty());
}
private final BooleanProperty suspendUpdates = new SimpleBooleanProperty(this, "suspendUpdates", false);
/**
* A property that will suspend all updates to the view based on model changes. This feature
* comes in handy when performing large batch updates with many adds and / or removes of calendar
* entries. When this property is set to true the view will not add / remove / update any entry
* views. Once it is set back to false a single refresh will be executed.
*
* @return true if updates are suspended
*/
public final BooleanProperty suspendUpdatesProperty() {
return suspendUpdates;
}
/**
* Returns the value of {@link #suspendUpdatesProperty()}.
*
* @return true if updates are suspended
*/
public final boolean isSuspendUpdates() {
return suspendUpdates.get();
}
/**
* Sets the value of {@link #suspendUpdatesProperty()}.
*
* @param suspend if true updates are suspended
*/
public final void setSuspendUpdates(boolean suspend) {
this.suspendUpdates.set(suspend);
}
// usage policy support
public enum Usage {
NONE,
VERY_LOW,
LOW,
MEDIUM,
HIGH,
VERY_HIGH
}
public final ObjectProperty<Callback<Integer, Usage>> usagePolicy = new SimpleObjectProperty<>(this, "usagePolicy");
/**
* A property used to store a policy that will be used to determine if a given number of entries
* indicates a low or high usage of that day. This policy is used by the {@link YearMonthView} to color
* the background of each day based on the "usage" of that day. The default implementation of this policy
* returns "none" for 0 entries, "very low" for 1 entry, "low" for 2 entries, "medium" for 3 entries,
* "high" for 4 entries, and "very high" for 5 entries or more.
*
* @return the usage policy
*/
public final ObjectProperty<Callback<Integer, Usage>> usagePolicyProperty() {
return usagePolicy;
}
/**
* Sets the value of {@link #usagePolicyProperty()}.
*
* @param policy the new usage policy
*/
public final void setUsagePolicy(Callback<Integer, Usage> policy) {
Objects.requireNonNull(policy);
this.usagePolicy.set(policy);
}
/**
* Returns the value of {@link #usagePolicyProperty()}.
*
* @return the new usage policy
*/
public final Callback<Integer, Usage> getUsagePolicy() {
return usagePolicy.get();
}
private static final String DATE_CONTROL_CATEGORY = "Date Control"; //$NON-NLS-1$
@Override
public ObservableList<Item> getPropertySheetItems() {
ObservableList<Item> items = super.getPropertySheetItems();
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(dateProperty());
}
@Override
public void setValue(Object value) {
setDate((LocalDate) value);
}
@Override
public Object getValue() {
return getDate();
}
@Override
public Class<?> getType() {
return LocalDate.class;
}
@Override
public String getName() {
return "Date"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Date"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(layoutProperty());
}
@Override
public void setValue(Object value) {
setLayout((Layout) value);
}
@Override
public Object getValue() {
return getLayout();
}
@Override
public Class<?> getType() {
return Layout.class;
}
@Override
public String getName() {
return "Layout"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Layout"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(selectionModeProperty());
}
@Override
public void setValue(Object value) {
setSelectionMode((SelectionMode) value);
}
@Override
public Object getValue() {
return getSelectionMode();
}
@Override
public Class<?> getType() {
return SelectionMode.class;
}
@Override
public String getName() {
return "Selection Mode"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Selection Mode"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(todayProperty());
}
@Override
public void setValue(Object value) {
setToday((LocalDate) value);
}
@Override
public Object getValue() {
return getToday();
}
@Override
public Class<?> getType() {
return LocalDate.class;
}
@Override
public String getName() {
return "Today"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Today"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(showTodayProperty());
}
@Override
public void setValue(Object value) {
setShowToday((boolean) value);
}
@Override
public Object getValue() {
return isShowToday();
}
@Override
public Class<?> getType() {
return Boolean.class;
}
@Override
public String getName() {
return "Show Today"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Highlight today"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(zoneIdProperty());
}
@Override
public void setValue(Object value) {
setZoneId((ZoneId) value);
}
@Override
public Object getValue() {
return getZoneId();
}
@Override
public Class<?> getType() {
return ZoneId.class;
}
@Override
public String getName() {
return "Timezone"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Timezone"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(weekFieldsProperty());
}
@Override
public void setValue(Object value) {
setWeekFields((WeekFields) value);
}
@Override
public Object getValue() {
return getWeekFields();
}
@Override
public Class<?> getType() {
return WeekFields.class;
}
@Override
public String getName() {
return "Week Fields"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Week Fields (calendar standard)"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(timeProperty());
}
@Override
public void setValue(Object value) {
setTime((LocalTime) value);
}
@Override
public Object getValue() {
return getTime();
}
@Override
public Class<?> getType() {
return LocalTime.class;
}
@Override
public String getName() {
return "Time"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Time"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(startTimeProperty());
}
@Override
public void setValue(Object value) {
setStartTime((LocalTime) value);
}
@Override
public Object getValue() {
return getStartTime();
}
@Override
public Class<?> getType() {
return LocalTime.class;
}
@Override
public String getName() {
return "Start Time"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "The first visible time at the top."; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(endTimeProperty());
}
@Override
public void setValue(Object value) {
setEndTime((LocalTime) value);
}
@Override
public Object getValue() {
return getEndTime();
}
@Override
public Class<?> getType() {
return LocalTime.class;
}
@Override
public String getName() {
return "End Time"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "The last visible time at the bottom."; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(enableHyperlinksProperty());
}
@Override
public void setValue(Object value) {
setEnableHyperlinks((boolean) value);
}
@Override
public Object getValue() {
return isEnableHyperlinks();
}
@Override
public Class<?> getType() {
return Boolean.class;
}
@Override
public String getName() {
return "Hyperlinks"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Hyperlinks enabled / disabled"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
return items;
}
}
| CalendarFXView/src/main/java/com/calendarfx/view/DateControl.java | /**
* Copyright (C) 2015, 2016 Dirk Lemmermann Software & Consulting (dlsc.com)
*
* This file is part of CalendarFX.
*/
package com.calendarfx.view;
import com.calendarfx.model.*;
import com.calendarfx.util.LoggingDomain;
import com.calendarfx.view.page.DayPage;
import com.calendarfx.view.popover.DatePopOver;
import com.calendarfx.view.popover.EntryPopOverContentPane;
import impl.com.calendarfx.view.ViewHelper;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.WeakInvalidationListener;
import javafx.beans.binding.Bindings;
import javafx.beans.property.*;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.collections.ObservableSet;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.effect.Light.Point;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.InputEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.util.Callback;
import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;
import org.controlsfx.control.PropertySheet.Item;
import java.text.MessageFormat;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import static java.time.DayOfWeek.SATURDAY;
import static java.time.DayOfWeek.SUNDAY;
import static java.util.Objects.requireNonNull;
import static javafx.scene.control.SelectionMode.MULTIPLE;
import static javafx.scene.input.ContextMenuEvent.CONTEXT_MENU_REQUESTED;
import static javafx.scene.input.MouseButton.PRIMARY;
/**
* The superclass for all controls that are showing calendar information. This
* class is responsible for:
* <p>
* <ul>
* <li>Binding to other date controls</li>
* <li>Providing the current date, "today", first day of week</li>
* <li>Creating sources, calendars, entries</li>
* <li>Context menu</li>
* <li>Showing details for a given date or entry</li>
* <li>Providing a virtual grid for editing</li>
* <li>Selection handling</li>
* <li>Printing</li>
* </ul>
* <h2>Binding</h2> Date controls are bound to each other to create complex date
* controls like the {@link CalendarView}. When date controls are bound to each
* other via the {@link #bind(DateControl, boolean)} method then most of their
* properties will be bound to each other. This not only includes date and time
* zone properties but also all the factory and detail callbacks. This allows an
* application to create a complex calendar control and to configure only that
* control without worrying about the date controls that are nested inside of
* it. The children will all "inherit" their settings from the parent control.
* <p>
* <h2>Current Date, Today, First Day of Week</h2> The {@link #dateProperty()}
* is used to store the date that the control has to display. For the
* {@link DayView} this would mean that it has to show exactly that date. The
* {@link DetailedWeekView} would only have to guarantee that it shows the week that
* contains this date. For this the {@link DetailedWeekView} uses the
* {@link #getFirstDayOfWeek()} method that looks up its value from the week
* fields stored in the {@link #weekFieldsProperty()}. The
* {@link #todayProperty()} is mainly used for highlighting today's date in the
* view (e.g. a red background).
* <p>
* <h2>Creating Sources, Calendars, Entries</h2> The date control uses various
* factories to create new sources, calendars, and entries. Each factory has to
* implement the {@link Callback} interface. The factories will be invoked when
* the application calls {@link #createCalendarSource()} or
* {@link #createEntryAt(ZonedDateTime)}.
* <p>
* <h2>Context Menu</h2> Date controls can either set a context menu explicitly
* via {@link #setContextMenu(ContextMenu)} or by providing a callback that gets
* invoked every time the context menu event is received (see
* {@link #setContextMenuCallback(Callback)}). If a context menu has been set
* explicitly then the callback will never be called again.
* <p>
* <h2>Details for Entries and Dates</h2> When clicking on an entry or a date
* the user wants to see details regarding the entry or the date. Callbacks for
* this can be registered via {@link #setEntryDetailsCallback(Callback)} and
* {@link #setDateDetailsCallback(Callback)}. The callbacks can decide which
* kind of user interface they want to show to the user. The default
* implementation for both callbacks is a {@link PopOver} control from the
* <a href="http://controlsfx.org">ControlsFX</a> project.
* <p>
* <h2>Selection Handling</h2> Date controls use a very simple selection
* concept. All selected entries are stored inside an observable list (see
* {@link #getSelections()}). The controls support single and multiple
* selections (see {@link #setSelectionMode(SelectionMode)}). Due to the binding
* approach it does not matter in which child date control an entry gets
* selected. All controls will always know which entries are selected.
* <p>
* <h2>Virtual Grid</h2> A virtual grid is used for editing. It allows the start
* and end times of entries to snap to "virtual" grid lines. The grid can be
* used to make the times always snap to 5, 10, 15, 30 minutes for example. This
* makes it easier to align entries to each other and covers the most common use
* cases. More precise times can always be set in the details.
*/
public abstract class DateControl extends CalendarFXControl {
private int entryCounter = 1;
private Boolean usesOwnContextMenu;
private final InvalidationListener updateCalendarListListener = (Observable it) -> updateCalendarList();
private final WeakInvalidationListener weakUpdateCalendarListListener = new WeakInvalidationListener(updateCalendarListListener);
/**
* Constructs a new date control and initializes all factories and callbacks
* with default implementations.
*/
protected DateControl() {
setFocusTraversable(false);
setUsagePolicy(count -> {
if (count < 0) {
throw new IllegalArgumentException("usage count can not be smaller than zero, but was " + count);
}
switch (count) {
case 0:
return Usage.NONE;
case 1:
return Usage.VERY_LOW;
case 2:
return Usage.LOW;
case 3:
return Usage.MEDIUM;
case 4:
return Usage.HIGH;
case 5:
default:
return Usage.VERY_HIGH;
}
});
getWeekendDays().add(SATURDAY);
getWeekendDays().add(SUNDAY);
/*
* Every date control is initially populated with a default source and
* calendar.
*/
CalendarSource defaultCalendarSource = new CalendarSource(Messages.getString("DateControl.DEFAULT_CALENDAR_SOURCE_NAME")); //$NON-NLS-1$
Calendar defaultCalendar = new Calendar(Messages.getString("DateControl.DEFAULT_CALENDAR_NAME")); //$NON-NLS-1$
defaultCalendarSource.getCalendars().add(defaultCalendar);
getCalendarSources().add(defaultCalendarSource);
InvalidationListener hidePopOverListener = it -> maybeHidePopOvers();
sceneProperty().addListener(hidePopOverListener);
visibleProperty().addListener(hidePopOverListener);
getCalendarSources().addListener(weakUpdateCalendarListListener);
/*
* The popover content callback creates a content node that will make
* out the content of the popover used to display entry details.
*/
setEntryDetailsPopOverContentCallback(param -> new EntryPopOverContentPane(param.getPopOver(), param.getDateControl(), param.getEntry()));
/*
* The default calendar provider returns the first calendar from the
* first source.
*/
setDefaultCalendarProvider(control -> {
List<CalendarSource> sources = getCalendarSources();
if (sources != null && !sources.isEmpty()) {
CalendarSource s = sources.get(0);
List<? extends Calendar> calendars = s.getCalendars();
if (calendars != null && !calendars.isEmpty()) {
for (Calendar c : calendars) {
if (!c.isReadOnly() && isCalendarVisible(c)) {
return c;
}
}
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle(Messages.getString("DateControl.TITLE_CALENDAR_PROBLEM")); //$NON-NLS-1$
alert.setHeaderText(Messages.getString("DateControl.HEADER_TEXT_UNABLE_TO_CREATE_NEW_ENTRY")); //$NON-NLS-1$
String newLine = System.getProperty("line.separator"); //$NON-NLS-1$
alert.setContentText(MessageFormat.format(Messages.getString("DateControl.CONTENT_TEXT_UNABLE_TO_CREATE_NEW_ENTRY"), //$NON-NLS-1$
newLine));
alert.show();
} else {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle(Messages.getString("DateControl.TITLE_CALENDAR_PROBLEM")); //$NON-NLS-1$
alert.setHeaderText(Messages.getString("DateControl.HEADER_TEXT_NO_CALENDARS_DEFINED")); //$NON-NLS-1$
alert.setContentText(Messages.getString("DateControl.CONTENT_TEXT_NO_CALENDARS_DEFINED")); //$NON-NLS-1$
alert.show();
}
}
return null;
});
setEntryFactory(param -> {
DateControl control = param.getDateControl();
VirtualGrid grid = control.getVirtualGrid();
ZonedDateTime time = param.getZonedDateTime();
DayOfWeek firstDayOfWeek = getFirstDayOfWeek();
ZonedDateTime lowerTime = grid.adjustTime(time, false, firstDayOfWeek);
ZonedDateTime upperTime = grid.adjustTime(time, true, firstDayOfWeek);
if (Duration.between(time, lowerTime).abs().minus(Duration.between(time, upperTime).abs()).isNegative()) {
time = lowerTime;
} else {
time = upperTime;
}
Entry<Object> entry = new Entry<>(MessageFormat.format(Messages.getString("DateControl.DEFAULT_ENTRY_TITLE"), entryCounter++)); //$NON-NLS-1$
Interval interval = new Interval(time.toLocalDateTime(), time.toLocalDateTime().plusHours(1));
entry.setInterval(interval);
if (control instanceof AllDayView) {
entry.setFullDay(true);
}
return entry;
});
setEntryDetailsCallback(param -> {
InputEvent evt = param.getInputEvent();
if (evt instanceof MouseEvent) {
MouseEvent mouseEvent = (MouseEvent) evt;
if (mouseEvent.getClickCount() == 2) {
showEntryDetails(param.getEntry(), param.getOwner(), param.getScreenY());
return true;
}
} else {
showEntryDetails(param.getEntry(), param.getOwner(), param.getScreenY());
return true;
}
return false;
});
setDateDetailsCallback(param -> {
InputEvent evt = param.getInputEvent();
if (evt == null) {
showDateDetails(param.getOwner(), param.getLocalDate());
return true;
} else if (evt instanceof MouseEvent) {
MouseEvent mouseEvent = (MouseEvent) evt;
if (mouseEvent.getClickCount() == 1) {
showDateDetails(param.getOwner(), param.getLocalDate());
return true;
}
}
return false;
});
setContextMenuCallback(new ContextMenuProvider());
setEntryContextMenuCallback(param -> {
EntryViewBase<?> entryView = param.getEntryView();
Entry<?> entry = entryView.getEntry();
ContextMenu contextMenu = new ContextMenu();
/*
* Show dialog / popover with entry details.
*/
MenuItem informationItem = new MenuItem(Messages.getString("DateControl.MENU_ITEM_INFORMATION")); //$NON-NLS-1$
informationItem.setOnAction(evt -> {
Callback<EntryDetailsParameter, Boolean> detailsCallback = getEntryDetailsCallback();
if (detailsCallback != null) {
ContextMenuEvent ctxEvent = param.getContextMenuEvent();
EntryDetailsParameter entryDetailsParam = new EntryDetailsParameter(ctxEvent, DateControl.this, entryView.getEntry(), this, ctxEvent.getScreenX(), ctxEvent.getScreenY());
detailsCallback.call(entryDetailsParam);
}
});
contextMenu.getItems().add(informationItem);
String stylesheet = CalendarView.class.getResource("calendar.css") //$NON-NLS-1$
.toExternalForm();
/*
* Assign entry to different calendars.
*/
Menu calendarMenu = new Menu(Messages.getString("DateControl.MENU_CALENDAR")); //$NON-NLS-1$
for (Calendar calendar : getCalendars()) {
RadioMenuItem calendarItem = new RadioMenuItem(calendar.getName());
calendarItem.setOnAction(evt -> entry.setCalendar(calendar));
calendarItem.setDisable(calendar.isReadOnly());
calendarItem.setSelected(calendar.equals(param.getCalendar()));
calendarMenu.getItems().add(calendarItem);
StackPane graphic = new StackPane();
graphic.getStylesheets().add(stylesheet);
/*
* Icon has to be wrapped in a stackpane so that a stylesheet
* can be added to it.
*/
Rectangle icon = new Rectangle(10, 10);
icon.setArcHeight(2);
icon.setArcWidth(2);
icon.getStyleClass().setAll(calendar.getStyle() + "-icon"); //$NON-NLS-1$
graphic.getChildren().add(icon);
calendarItem.setGraphic(graphic);
}
calendarMenu.setDisable(param.getCalendar().isReadOnly());
contextMenu.getItems().add(calendarMenu);
if (getEntryEditPolicy().call(new EntryEditParameter(this, entry, EditOperation.DELETE))) {
/*
* Delete calendar entry.
*/
MenuItem delete = new MenuItem(Messages.getString("DateControl.MENU_ITEM_DELETE")); //$NON-NLS-1$
contextMenu.getItems().add(delete);
delete.setDisable(param.getCalendar().isReadOnly());
delete.setOnAction(evt -> {
Calendar calendar = entry.getCalendar();
if (!calendar.isReadOnly()) {
if (entry.isRecurrence()) {
entry.getRecurrenceSourceEntry().removeFromCalendar();
} else {
entry.removeFromCalendar();
}
}
});
}
return contextMenu;
});
setCalendarSourceFactory(param -> {
CalendarSource source = new CalendarSource(Messages.getString("DateControl.DEFAULT_NEW_CALENDAR_SOURCE")); //$NON-NLS-1$
Calendar calendar = new Calendar(Messages.getString("DateControl.DEFAULT_NEW_CALENDAR")); //$NON-NLS-1$
calendar.setShortName(Messages.getString("DateControl.DEFAULT_NEW_CALENDAR").substring(0, 1));
source.getCalendars().add(calendar);
return source;
});
addEventHandler(CONTEXT_MENU_REQUESTED, evt -> {
/*
* If a context menu was specified by calling setContextMenu() then
* we will not use the callback to produce one.
*/
if (null == usesOwnContextMenu) {
usesOwnContextMenu = getContextMenu() != null;
}
if (!usesOwnContextMenu) {
evt.consume();
Callback<ContextMenuParameter, ContextMenu> callback = getContextMenuCallback();
if (callback != null) {
Callback<DateControl, Calendar> calendarProvider = getDefaultCalendarProvider();
Calendar calendar = calendarProvider.call(DateControl.this);
ZonedDateTime time = ZonedDateTime.now();
if (DateControl.this instanceof ZonedDateTimeProvider) {
ZonedDateTimeProvider provider = (ZonedDateTimeProvider) DateControl.this;
time = provider.getZonedDateTimeAt(evt.getX(), evt.getY());
}
ContextMenuParameter param = new ContextMenuParameter(evt, DateControl.this, calendar, time);
ContextMenu menu = callback.call(param);
if (menu != null) {
setContextMenu(menu);
menu.show(DateControl.this, evt.getScreenX(), evt.getScreenY());
}
}
}
});
addEventFilter(MouseEvent.MOUSE_PRESSED, evt -> {
maybeHidePopOvers();
performSelection(evt);
});
}
private final ObservableMap<Calendar, BooleanProperty> calendarVisibilityMap = FXCollections.observableHashMap();
public final ObservableMap<Calendar, BooleanProperty> getCalendarVisibilityMap() {
return calendarVisibilityMap;
}
public final BooleanProperty getCalendarVisibilityProperty(Calendar calendar) {
return calendarVisibilityMap.computeIfAbsent(calendar, cal -> new SimpleBooleanProperty(DateControl.this, "visible", true));
}
public final boolean isCalendarVisible(Calendar calendar) {
BooleanProperty prop = getCalendarVisibilityProperty(calendar);
return prop.get();
}
public final void setCalendarVisibility(Calendar calendar, boolean visible) {
BooleanProperty prop = getCalendarVisibilityProperty(calendar);
prop.set(visible);
}
/**
* Requests that the date control should reload its data and recreate its
* entry views. Normally applications do not have to call this method. It is
* more like a backdoor for client / server applications where the server is
* unable to push changes to the client. In this case the client must
* frequently trigger an explicit refresh.
*/
public final void refreshData() {
getProperties().put("refresh.data", true); //$NON-NLS-1$
getBoundDateControls().forEach(DateControl::refreshData);
}
private void performSelection(MouseEvent evt) {
if ((evt.getButton().equals(PRIMARY) || evt.isPopupTrigger()) && evt.getClickCount() == 1) {
Entry<?> entry;
EntryViewBase<?> view = null;
if (evt.getTarget() instanceof EntryViewBase) {
view = (EntryViewBase<?>) evt.getTarget();
}
if (view == null) {
return;
}
String disableFocusHandlingKey = "disable-focus-handling"; //$NON-NLS-1$
view.getProperties().put(disableFocusHandlingKey, true);
view.requestFocus();
entry = view.getEntry();
if (entry != null) {
if (!isMultiSelect(evt) && !getSelections().contains(entry)) {
clearSelection();
}
if (isMultiSelect(evt) && getSelections().contains(entry)) {
getSelections().remove(entry);
} else if (!getSelections().contains(entry)) {
getSelections().add(entry);
}
}
view.getProperties().remove(disableFocusHandlingKey);
}
}
private boolean isMultiSelect(MouseEvent evt) {
return (evt.isShiftDown() || evt.isShortcutDown()) && getSelectionMode().equals(MULTIPLE);
}
/**
* Creates a new calendar source that will be added to the list of calendar
* sources of this date control. The method delegates the actual creation of
* the calendar source to a factory, which can be specified by calling
* {@link #setCalendarSourceFactory(Callback)}.
*
* @see #setCalendarSourceFactory(Callback)
*/
public final void createCalendarSource() {
Callback<CreateCalendarSourceParameter, CalendarSource> factory = getCalendarSourceFactory();
if (factory != null) {
CreateCalendarSourceParameter param = new CreateCalendarSourceParameter(this);
CalendarSource calendarSource = factory.call(param);
if (calendarSource != null && !getCalendarSources().contains(calendarSource)) {
getCalendarSources().add(calendarSource);
}
}
}
// dragged entry support
private final ObjectProperty<DraggedEntry> draggedEntry = new SimpleObjectProperty<>(this, "draggedEntry"); //$NON-NLS-1$
/**
* Stores a {@link DraggedEntry} instance, which serves as a wrapper around
* the actual entry that is currently being edited by the user. The
* framework creates this wrapper when the user starts a drag and adds it to
* the date control. This allows the framework to show the entry at its old
* and new location at the same time. It also ensures that the calendar does
* not fire any events before the user has committed the entry to a new
* location.
*
* @return the dragged entry
*/
public final ObjectProperty<DraggedEntry> draggedEntryProperty() {
return draggedEntry;
}
/**
* Returns the value of {@link #draggedEntryProperty()}.
*
* @return the dragged entry
*/
public final DraggedEntry getDraggedEntry() {
return draggedEntry.get();
}
/**
* Sets the value of {@link #draggedEntryProperty()}.
*
* @param entry the dragged entry
*/
public final void setDraggedEntry(DraggedEntry entry) {
draggedEntryProperty().set(entry);
}
/**
* Creates a new entry at the given time. The method delegates the actual
* instance creation to the entry factory (see
* {@link #entryFactoryProperty()}). The factory receives a parameter object
* that contains the default calendar where the entry can be added, however
* the factory can choose to add the entry to any calendar it likes. Please
* note that the time passed to the factory will be adjusted based on the
* current virtual grid settings (see {@link #virtualGridProperty()}).
*
* @param time the time where the entry will be created (the entry start
* time)
* @return the new calendar entry
* @see #setEntryFactory(Callback)
* @see #setVirtualGrid(VirtualGrid)
*/
public final Entry<?> createEntryAt(ZonedDateTime time) {
return createEntryAt(time, null);
}
/**
* Creates a new entry at the given time. The method delegates the actual
* instance creation to the entry factory (see
* {@link #entryFactoryProperty()}). The factory receives a parameter object
* that contains the calendar where the entry can be added, however the
* factory can choose to add the entry to any calendar it likes. Please note
* that the time passed to the factory will be adjusted based on the current
* virtual grid settings (see {@link #virtualGridProperty()}).
*
* @param time the time where the entry will be created (the entry start
* time)
* @param calendar the calendar to which the new entry will be added (if null the
* default calendar provider will be invoked)
* @return the new calendar entry
* @see #setEntryFactory(Callback)
* @see #setVirtualGrid(VirtualGrid)
*/
public final Entry<?> createEntryAt(ZonedDateTime time, Calendar calendar) {
requireNonNull(time);
VirtualGrid grid = getVirtualGrid();
if (grid != null) {
ZonedDateTime timeA = grid.adjustTime(time, false, getFirstDayOfWeek());
ZonedDateTime timeB = grid.adjustTime(time, true, getFirstDayOfWeek());
if (Duration.between(time, timeA).abs().minus(Duration.between(time, timeB).abs()).isNegative()) {
time = timeA;
} else {
time = timeB;
}
}
if (calendar == null) {
Callback<DateControl, Calendar> defaultCalendarProvider = getDefaultCalendarProvider();
calendar = defaultCalendarProvider.call(this);
}
if (calendar != null) {
/*
* We have to ensure that the calendar is visible, otherwise the new
* entry would not be shown to the user.
*/
setCalendarVisibility(calendar, true);
CreateEntryParameter param = new CreateEntryParameter(this, calendar, time);
Callback<CreateEntryParameter, Entry<?>> factory = getEntryFactory();
Entry<?> entry = factory.call(param);
if (entry != null) {
/*
* This is OK. The factory can return NULL. In this case we
* assume that the application does not allow to create an entry
* at the given location.
*/
entry.setCalendar(calendar);
}
return entry;
} else {
LoggingDomain.EDITING.warning("No calendar found for adding a new entry."); //$NON-NLS-1$
}
return null;
}
/**
* Returns the calendar shown at the given location. This method returns an
* optional value. Calling this method might or might not make sense,
* depending on the type of control and the current layout (see
* {@link #layoutProperty()}).
*
* @param x the x-coordinate to check
* @param y the y-coordinate to check
* @return the calendar at the given location
*/
public Optional<Calendar> getCalendarAt(double x, double y) {
return Optional.empty();
}
/**
* Adjusts the current view / page in such a way that the given entry
* becomes visible.
*
* @param entry the entry to show
*/
public final void showEntry(Entry<?> entry) {
requireNonNull(entry);
doShowEntry(entry, false);
}
/**
* Adjusts the current view / page in such a way that the given entry
* becomes visible and brings up the details editor / UI for the entry
* (default is a popover).
*
* @param entry the entry to show
*/
public final void editEntry(Entry<?> entry) {
requireNonNull(entry);
doShowEntry(entry, true);
}
private void doShowEntry(Entry<?> entry, boolean startEditing) {
setDate(entry.getStartDate());
if (!entry.isFullDay()) {
setRequestedTime(entry.getStartTime());
}
if (startEditing) {
/*
* The UI first needs to update itself so that the matching entry
* view can be found.
*/
Platform.runLater(() -> doEditEntry(entry));
} else {
Platform.runLater(() -> doBounceEntry(entry));
}
}
private void doEditEntry(Entry<?> entry) {
EntryViewBase<?> entryView = findEntryView(entry);
if (entryView != null) {
entryView.bounce();
Point2D localToScreen = entryView.localToScreen(0, 0);
Callback<EntryDetailsParameter, Boolean> callback = getEntryDetailsCallback();
EntryDetailsParameter param = new EntryDetailsParameter(null, this, entry, entryView, localToScreen.getX(), localToScreen.getY());
callback.call(param);
}
}
private void doBounceEntry(Entry<?> entry) {
EntryViewBase<?> entryView = findEntryView(entry);
if (entryView != null) {
entryView.bounce();
}
}
private static PopOver entryPopOver;
private void showEntryDetails(Entry<?> entry, Node owner, double screenY) {
maybeHidePopOvers();
Callback<EntryDetailsPopOverContentParameter, Node> contentCallback = getEntryDetailsPopOverContentCallback();
if (contentCallback == null) {
throw new IllegalStateException("No content callback found for entry popover"); //$NON-NLS-1$
}
entryPopOver = new PopOver();
EntryDetailsPopOverContentParameter param = new EntryDetailsPopOverContentParameter(entryPopOver, this, owner, entry);
Node content = contentCallback.call(param);
if (content == null) {
content = new Label(Messages.getString("DateControl.NO_CONTENT")); //$NON-NLS-1$
}
entryPopOver.setContentNode(content);
ArrowLocation location = ViewHelper.findPopOverArrowLocation(owner);
entryPopOver.setArrowLocation(location);
Point position = ViewHelper.findPopOverArrowPosition(owner, screenY, entryPopOver.getArrowSize(), location);
entryPopOver.show(owner, position.getX(), position.getY());
}
private static DatePopOver datePopOver;
/**
* Creates a new {@link DatePopOver} and shows it attached to the given
* owner node.
*
* @param owner the owner node
* @param date the date for which to display more detail
*/
public void showDateDetails(Node owner, LocalDate date) {
maybeHidePopOvers();
datePopOver = new DatePopOver(this, date);
datePopOver.show(owner);
}
private void maybeHidePopOvers() {
if (entryPopOver != null && entryPopOver.isShowing() && !entryPopOver.isDetached()) {
entryPopOver.hide();
}
if (datePopOver != null && datePopOver.isShowing() && !datePopOver.isDetached()) {
datePopOver.hide();
}
}
private abstract static class ContextMenuParameterBase {
private DateControl dateControl;
private ContextMenuEvent contextMenuEvent;
public ContextMenuParameterBase(ContextMenuEvent contextMenuEvent, DateControl dateControl) {
this.contextMenuEvent = requireNonNull(contextMenuEvent);
this.dateControl = requireNonNull(dateControl);
}
public ContextMenuEvent getContextMenuEvent() {
return contextMenuEvent;
}
public DateControl getDateControl() {
return dateControl;
}
}
/**
* The parameter object passed to the entry factory. It contains the most
* important parameters for creating a new entry: the requesting date
* control, the time where the user performed a double click and the default
* calendar.
*
* @see DateControl#entryFactoryProperty()
* @see DateControl#defaultCalendarProviderProperty()
* @see DateControl#createEntryAt(ZonedDateTime)
*/
public static final class CreateEntryParameter {
private final Calendar calendar;
private final ZonedDateTime zonedDateTime;
private final DateControl control;
/**
* Constructs a new parameter object.
*
* @param control the control where the user / the application wants to
* create a new entry
* @param calendar the default calendar
* @param time the time selected by the user in the date control
*/
public CreateEntryParameter(DateControl control, Calendar calendar, ZonedDateTime time) {
this.control = requireNonNull(control);
this.calendar = requireNonNull(calendar);
this.zonedDateTime = requireNonNull(time);
}
/**
* Returns the default calendar. Applications can add the new entry to
* this calendar by calling {@link Entry#setCalendar(Calendar)} or the
* can choose any other calendar.
*
* @return the default calendar
*/
public Calendar getDefaultCalendar() {
return calendar;
}
/**
* The time selected by the user.
*
* @return the start time for the new entry
*/
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
/**
* The date control where the user performed the double click.
*
* @return the date control where the event happened
*/
public DateControl getDateControl() {
return control;
}
@Override
public String toString() {
return "CreateEntryParameter [calendar=" + calendar //$NON-NLS-1$
+ ", zonedDateTime=" + zonedDateTime + "]"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
private final ObjectProperty<Callback<CreateEntryParameter, Entry<?>>> entryFactory = new SimpleObjectProperty<>(this, "entryFactory"); //$NON-NLS-1$
/**
* A factory for creating new entries when the user double clicks inside the
* date control or when the application calls
* {@link #createEntryAt(ZonedDateTime)}. The factory can return NULL to
* indicate that no entry can be created at the given location.
* <p>
* <h2>Code Example</h2>
* <p>
* The code below shows the default entry factory that is set on every date
* control.
* <p>
* <p>
* <pre>
* setEntryFactory(param -> {
* DateControl control = param.getControl();
* VirtualGrid grid = control.getVirtualGrid();
* ZonedDateTime time = param.getZonedDateTime();
* DayOfWeek firstDayOfWeek = getFirstDayOfWeek();
*
* ZonedDateTime lowerTime = grid.adjustTime(time, false, firstDayOfWeek);
* ZonedDateTime upperTime = grid.adjustTime(time, true, firstDayOfWeek);
*
* if (Duration.between(time, lowerTime).abs().minus(Duration.between(time, upperTime).abs()).isNegative()) {
* time = lowerTime;
* } else {
* time = upperTime;
* }
*
* Entry<Object> entry = new Entry<>("New Entry");
* entry.changeStartDate(time.toLocalDate());
* entry.changeStartTime(time.toLocalTime());
* entry.changeEndDate(entry.getStartDate());
* entry.changeEndTime(entry.getStartTime().plusHours(1));
*
* if (control instanceof AllDayView) {
* entry.setFullDay(true);
* }
*
* return entry;
* });
* </pre>
*
* @return the entry factory callback
*/
public final ObjectProperty<Callback<CreateEntryParameter, Entry<?>>> entryFactoryProperty() {
return entryFactory;
}
/**
* Returns the value of {@link #entryFactoryProperty()}.
*
* @return the factory used for creating a new entry
*/
public final Callback<CreateEntryParameter, Entry<?>> getEntryFactory() {
return entryFactoryProperty().get();
}
/**
* Sets the value of {@link #entryFactoryProperty()}.
*
* @param factory the factory used for creating a new entry
*/
public final void setEntryFactory(Callback<CreateEntryParameter, Entry<?>> factory) {
Objects.requireNonNull(factory);
entryFactoryProperty().set(factory);
}
/*
* Calendar source callback.
*/
/**
* The parameter object passed to the calendar source factory.
*
* @see DateControl#setCalendarSourceFactory(Callback)
*/
public static final class CreateCalendarSourceParameter {
private DateControl dateControl;
/**
* Constructs a new parameter object.
*
* @param dateControl the control where the source will be added
*/
public CreateCalendarSourceParameter(DateControl dateControl) {
this.dateControl = requireNonNull(dateControl);
}
/**
* The control where the source will be added.
*
* @return the date control
*/
public DateControl getDateControl() {
return dateControl;
}
}
private final ObjectProperty<Callback<CreateCalendarSourceParameter, CalendarSource>> calendarSourceFactory = new SimpleObjectProperty<>(this, "calendarSourceFactory"); //$NON-NLS-1$
/**
* A factory for creating a new calendar source, e.g. a new Google calendar
* account.
* <p>
* <h2>Code Example</h2> The code below shows the default implementation of
* this factory. Applications can choose to bring up a full featured user
* interface / dialog to specify the exact location of the source (either
* locally or over a network). A local calendar source might read its data
* from an XML file while a remote source could load data from a web
* service.
* <p>
* <pre>
* setCalendarSourceFactory(param -> {
* CalendarSource source = new CalendarSource("Calendar Source");
* Calendar calendar = new Calendar("Calendar");
* source.getCalendars().add(calendar);
* return source;
* });
* </pre>
* <p>
* The factory can be invoked by calling {@link #createCalendarSource()}.
*
* @return the calendar source factory
* @see #createCalendarSource()
*/
public final ObjectProperty<Callback<CreateCalendarSourceParameter, CalendarSource>> calendarSourceFactoryProperty() {
return calendarSourceFactory;
}
/**
* Returns the value of {@link #calendarSourceFactoryProperty()}.
*
* @return the calendar source factory
*/
public final Callback<CreateCalendarSourceParameter, CalendarSource> getCalendarSourceFactory() {
return calendarSourceFactoryProperty().get();
}
/**
* Sets the value of {@link #calendarSourceFactoryProperty()}.
*
* @param callback the callback used for creating a new calendar source
*/
public final void setCalendarSourceFactory(Callback<CreateCalendarSourceParameter, CalendarSource> callback) {
calendarSourceFactoryProperty().set(callback);
}
/*
* Context menu callback for entries.
*/
/**
* The parameter object passed to the context menu callback for entries.
*
* @see DateControl#entryContextMenuCallbackProperty()
*/
public static final class EntryContextMenuParameter extends ContextMenuParameterBase {
private EntryViewBase<?> entryView;
/**
* Constructs a new context menu parameter object.
*
* @param evt the event that triggered the context menu
* @param control the date control where the event occurred
* @param entryView the entry view for which the context menu will be created
*/
public EntryContextMenuParameter(ContextMenuEvent evt, DateControl control, EntryViewBase<?> entryView) {
super(evt, control);
this.entryView = requireNonNull(entryView);
}
/**
* The entry view for which the context menu will be shown.
*
* @return the entry view
*/
public EntryViewBase<?> getEntryView() {
return entryView;
}
/**
* Convenience method to easily lookup the entry for which the view was
* created.
*
* @return the calendar entry
*/
public Entry<?> getEntry() {
return entryView.getEntry();
}
/**
* Convenience method to easily lookup the calendar of the entry for
* which the view was created.
*
* @return the calendar
*/
public Calendar getCalendar() {
return getEntry().getCalendar();
}
@Override
public String toString() {
return "EntryContextMenuParameter [entry=" + entryView //$NON-NLS-1$
+ ", dateControl =" + getDateControl() + "]"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Possible edit operations on an entry.
* This enum will be used as parameter of the callback set with {@link DateControl#setEntryEditPolicy}.
*/
public enum EditOperation {
/**
* Checked if the start of an entry can be changed (e.g. using drag/drop).
*/
CHANGE_START,
/**
* Checked if the end of an entry can be changed (e.g. using drag/drop).
*/
CHANGE_END,
/**
* Checked if entry can be moved using drag/drop.
*/
MOVE,
/**
* Checked if an entry can be deleted.
*/
DELETE
}
/**
* Class used for parameter of {@link com.calendarfx.view.DateControl#entryEditPolicy} functional interface.
*/
public static final class EntryEditParameter {
/**
* The date control the entity is associated with.
*/
private final DateControl dateControl;
/**
* The entity the operation is operated on.
*/
private final Entry<?> entry;
/**
* The operation.
*/
private final DateControl.EditOperation editOperation;
public EntryEditParameter(DateControl dateControl, Entry<?> entry, DateControl.EditOperation editOperation) {
this.dateControl = dateControl;
this.entry = entry;
this.editOperation = editOperation;
}
/**
* The {@link DateControl} which is asking for a specific {@link com.calendarfx.view.DateControl.EditOperation} permission.
* @returns The date control.
*/
public DateControl getDateControl() {
return dateControl;
}
/**
* The entry where the {@link com.calendarfx.view.DateControl.EditOperation} should be applied.
* @returns The entry.
*/
public Entry<?> getEntry() {
return entry;
}
/**
* The actual edit operation.
* @returns The edit operation.
*/
public DateControl.EditOperation getEditOperation() {
return editOperation;
}
}
/**
* If an action will be issued on an item the given instance will be asked if the action is allowed.
*
* @see EditOperation
*/
private final ObjectProperty<Callback<EntryEditParameter, Boolean>> entryEditPolicy = new SimpleObjectProperty<>(action -> true);
/**
* If an action will be issued on an item the given instance will be asked if the action is allowed.
*
* @returns The entry edit policy callback
*
* @see EditOperation
*/
public final Callback<EntryEditParameter, Boolean> getEntryEditPolicy() {
return entryEditPolicy.get();
}
/**
* If an action will be issued on an item the given instance will be asked if the action is allowed.
*
* @returns The entry edit policy callback property
*
* @see EditOperation
*/
public final ObjectProperty<Callback<EntryEditParameter, Boolean>> entryEditPolicyProperty() {
return entryEditPolicy;
}
/**
* If an action will be issued on an item the given instance will be asked if the action is allowed.
*/
public final void setEntryEditPolicy(Callback<EntryEditParameter, Boolean> entryEditPolicy) {
this.entryEditPolicy.set(entryEditPolicy);
}
private final ObjectProperty<Callback<EntryContextMenuParameter, ContextMenu>> entryContextMenuCallback = new SimpleObjectProperty<>(this, "entryFactory"); //$NON-NLS-1$
/**
* A callback used for dynamically creating a context menu for a given
* entry view.
* <p>
* <h2>Code Example</h2> The code below shows the default implementation of
* this callback.
* <p>
* <p>
* <pre>
* setEntryContextMenuCallback(param -> {
* EntryViewBase<?> entryView = param.getEntryView();
* Entry<?> entry = entryView.getEntry();
*
* ContextMenu contextMenu = new ContextMenu();
*
* MenuItem informationItem = new MenuItem("Information");
* informationItem.setOnAction(evt -> {
* Callback<EntryDetailsParameter, Boolean> detailsCallback = getEntryDetailsCallback();
* if (detailsCallback != null) {
* ContextMenuEvent ctxEvent = param.getContextMenuEvent();
* EntryDetailsParameter entryDetailsParam = new EntryDetailsParameter(ctxEvent, DateControl.this, entryView, this, ctxEvent.getScreenX(), ctxEvent.getScreenY());
* detailsCallback.call(entryDetailsParam);
* }
* });
* contextMenu.getItems().add(informationItem);
*
* Menu calendarMenu = new Menu("Calendar");
* for (Calendar calendar : getCalendars()) {
* MenuItem calendarItem = new MenuItem(calendar.getName());
* calendarItem.setOnAction(evt -> entry.setCalendar(calendar));
* calendarMenu.getItems().add(calendarItem);
* }
* contextMenu.getItems().add(calendarMenu);
*
* return contextMenu;
* });
* </pre>
*
* @return the property used for storing the callback
*/
public final ObjectProperty<Callback<EntryContextMenuParameter, ContextMenu>> entryContextMenuCallbackProperty() {
return entryContextMenuCallback;
}
/**
* Returns the value of {@link #entryContextMenuCallbackProperty()}.
*
* @return the callback for creating a context menu for a given calendar
* entry
*/
public final Callback<EntryContextMenuParameter, ContextMenu> getEntryContextMenuCallback() {
return entryContextMenuCallbackProperty().get();
}
/**
* Sets the value of {@link #entryContextMenuCallbackProperty()}.
*
* @param callback the callback used for creating a context menu for a calendar
* entry
*/
public final void setEntryContextMenuCallback(Callback<EntryContextMenuParameter, ContextMenu> callback) {
entryContextMenuCallbackProperty().set(callback);
}
/*
* Context menu callback.
*/
/**
* The parameter object passed to the context menu callback.
*
* @see DateControl#contextMenuCallbackProperty()
*/
public static final class ContextMenuParameter extends ContextMenuParameterBase {
private Calendar calendar;
private ZonedDateTime zonedDateTime;
/**
* Constructs a new parameter object.
*
* @param evt the event that triggered the context menu
* @param dateControl the date control where the event occurred
* @param calendar the (default) calendar where newly created entries should
* be added
* @param time the time where the mouse click occurred
*/
public ContextMenuParameter(ContextMenuEvent evt, DateControl dateControl, Calendar calendar, ZonedDateTime time) {
super(evt, dateControl);
this.calendar = requireNonNull(calendar);
this.zonedDateTime = time;
}
/**
* The (default) calendar where newly created entries should be added.
* Only relevant if the context menu is actually used for creating new
* entries. This can be different from application to application.
*
* @return the (default) calendar for adding new entries
*/
public Calendar getCalendar() {
return calendar;
}
/**
* The time where the mouse click occurred.
*
* @return the time shown at the mouse click location
*/
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
@Override
public String toString() {
return "ContextMenuParameter [calendar=" + calendar //$NON-NLS-1$
+ ", zonedDateTime=" + zonedDateTime + "]"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
private final ObjectProperty<Callback<ContextMenuParameter, ContextMenu>> contextMenuCallback = new SimpleObjectProperty<>(this, "contextMenuCallback"); //$NON-NLS-1$
/**
* The context menu callback that will be invoked when the user triggers the
* context menu by clicking in an area without an entry view. Using a
* callback allows the application to create context menus with different
* content, depending on the current state of the application and the
* location of the click.
* <p>
* <h2>Code Example</h2>
* <p>
* The code below shows a part of the default implementation:
* <p>
* <p>
* <pre>
* setContextMenuCallback(param -> {
* ContextMenu menu = new ContextMenu();
* MenuItem newEntryItem = new MenuItem("Add New Event");
* newEntryItem.setOnAction(evt -> {
* createEntryAt(param.getZonedDateTime());
* });
* menu.getItems().add(newEntry);
* return menu;
* });
* </pre>
*
* @return the context menu callback
*/
public final ObjectProperty<Callback<ContextMenuParameter, ContextMenu>> contextMenuCallbackProperty() {
return contextMenuCallback;
}
/**
* Returns the value of {@link #contextMenuCallbackProperty()}.
*
* @return the context menu callback
*/
public final Callback<ContextMenuParameter, ContextMenu> getContextMenuCallback() {
return contextMenuCallbackProperty().get();
}
/**
* Sets the value of {@link #contextMenuCallbackProperty()}.
*
* @param callback the context menu callback
*/
public final void setContextMenuCallback(Callback<ContextMenuParameter, ContextMenu> callback) {
contextMenuCallbackProperty().set(callback);
}
/*
* Default calendar provider callback.
*/
private final ObjectProperty<Callback<DateControl, Calendar>> defaultCalendarProvider = new SimpleObjectProperty<>(this, "defaultCalendarProvider"); //$NON-NLS-1$
/**
* The default calendar provider is responsible for returning a calendar
* that can be used to add a new entry. This way the user can add new
* entries by simply double clicking inside the view without the need of
* first showing a calendar selection UI. This can be changed by setting a
* callback that prompts the user with a dialog.
* <p>
* <h2>Code Example</h2>
* <p>
* The code shown below is the default implementation of this provider. It
* returns the first calendar of the first source. If no source is available
* it will return null.
* <p>
* <p>
* <pre>
* setDefaultCalendarProvider(control -> {
* List<CalendarSource> sources = getCalendarSources();
* if (sources != null && !sources.isEmpty()) {
* CalendarSource s = sources.get(0);
* List<? extends Calendar> calendars = s.getCalendars();
* if (calendars != null && !calendars.isEmpty()) {
* return calendars.get(0);
* }
* }
*
* return null;
* });
* </pre>
*
* @return the default calendar provider callback
*/
public final ObjectProperty<Callback<DateControl, Calendar>> defaultCalendarProviderProperty() {
return defaultCalendarProvider;
}
/**
* Returns the value of {@link #defaultCalendarProviderProperty()}.
*
* @return the default calendar provider
*/
public final Callback<DateControl, Calendar> getDefaultCalendarProvider() {
return defaultCalendarProviderProperty().get();
}
/**
* Sets the value of {@link #defaultCalendarProviderProperty()}.
*
* @param provider the default calendar provider
*/
public final void setDefaultCalendarProvider(Callback<DateControl, Calendar> provider) {
requireNonNull(provider);
defaultCalendarProviderProperty().set(provider);
}
private void updateCalendarList() {
List<Calendar> removedCalendars = new ArrayList<>(calendars);
List<Calendar> newCalendars = new ArrayList<>();
for (CalendarSource source : getCalendarSources()) {
for (Calendar calendar : source.getCalendars()) {
if (calendars.contains(calendar)) {
removedCalendars.remove(calendar);
} else {
newCalendars.add(calendar);
}
}
source.getCalendars().removeListener(weakUpdateCalendarListListener);
source.getCalendars().addListener(weakUpdateCalendarListListener);
}
calendars.addAll(newCalendars);
calendars.removeAll(removedCalendars);
}
private abstract static class DetailsParameter {
private InputEvent inputEvent;
private DateControl dateControl;
private Node owner;
private double screenX;
private double screenY;
/**
* Constructs a new parameter object.
*
* @param inputEvent the input event that triggered the need for showing entry
* details (e.g. a mouse double click, or a context menu item
* selection)
* @param control the control where the event occurred
* @param owner a node that can be used as an owner for the dialog or
* popover
* @param screenX the screen location where the event occurred
* @param screenY the screen location where the event occurred
*/
public DetailsParameter(InputEvent inputEvent, DateControl control, Node owner, double screenX, double screenY) {
this.inputEvent = inputEvent;
this.dateControl = requireNonNull(control);
this.owner = requireNonNull(owner);
this.screenX = screenX;
this.screenY = screenY;
}
/**
* Returns the node that should be used as the owner of a dialog /
* popover. We should not use the entry view as the owner of a dialog /
* popover because views come and go. We need something that lives
* longer.
*
* @return an owner node for the details dialog / popover
*/
public Node getOwner() {
return owner;
}
/**
* The screen X location where the event occurred.
*
* @return the screen x location of the event
*/
public double getScreenX() {
return screenX;
}
/**
* The screen Y location where the event occurred.
*
* @return the screen y location of the event
*/
public double getScreenY() {
return screenY;
}
/**
* The input event that triggered the need for showing entry details
* (e.g. a mouse double click or a context menu item selection).
*
* @return the input event
*/
public InputEvent getInputEvent() {
return inputEvent;
}
/**
* The date control where the event occurred.
*
* @return the date control
*/
public DateControl getDateControl() {
return dateControl;
}
}
/**
* The parameter object passed to the entry details callback.
*
* @see DateControl#entryDetailsCallbackProperty()
*/
public final static class EntryDetailsParameter extends DetailsParameter {
private Entry<?> entry;
/**
* Constructs a new parameter object.
*
* @param inputEvent the input event that triggered the need for showing entry
* details (e.g. a mouse double click, or a context menu item
* selection)
* @param control the control where the event occurred
* @param entry the entry for which details are requested
* @param owner a node that can be used as an owner for the dialog or
* popover
* @param screenX the screen location where the event occurred
* @param screenY the screen location where the event occurred
*/
public EntryDetailsParameter(InputEvent inputEvent, DateControl control, Entry<?> entry, Node owner, double screenX, double screenY) {
super(inputEvent, control, owner, screenX, screenY);
this.entry = entry;
}
/**
* The entry for which details are requested.
*
* @return the entry view
*/
public Entry<?> getEntry() {
return entry;
}
}
/**
* The parameter object passed to the date details callback.
*
* @see DateControl#dateDetailsCallbackProperty()
*/
public final static class DateDetailsParameter extends DetailsParameter {
private LocalDate localDate;
/**
* Constructs a new parameter object.
*
* @param inputEvent the input event that triggered the need for showing entry
* details (e.g. a mouse double click, or a context menu item
* selection)
* @param control the control where the event occurred
* @param date the date for which details are required
* @param owner a node that can be used as an owner for the dialog or
* popover
* @param screenX the screen location where the event occurred
* @param screenY the screen location where the event occurred
*/
public DateDetailsParameter(InputEvent inputEvent, DateControl control, Node owner, LocalDate date, double screenX, double screenY) {
super(inputEvent, control, owner, screenX, screenY);
this.localDate = requireNonNull(date);
}
/**
* The date for which details are required.
*
* @return the date
*/
public LocalDate getLocalDate() {
return localDate;
}
}
private final ObjectProperty<Callback<DateDetailsParameter, Boolean>> dateDetailsCallback = new SimpleObjectProperty<>(this, "dateDetailsCallback"); //$NON-NLS-1$
/**
* A callback used for showing the details of a given date. The default
* implementation of this callback displays a small {@link PopOver} but
* applications might as well display a large dialog where the user can
* freely edit the date.
* <p>
* <h2>Code Example</h2> The code below shows the default implementation
* used by all date controls. It delegates to a private method that shows
* the popover.
* <p>
* <pre>
* setDateDetailsCallback(param -> {
* InputEvent evt = param.getInputEvent();
* if (evt instanceof MouseEvent) {
* MouseEvent mouseEvent = (MouseEvent) evt;
* if (mouseEvent.getClickCount() == 1) {
* showDateDetails(param.getOwner(), param.getLocalDate());
* return true;
* }
* }
*
* return false;
* });
* </pre>
*
* @return the callback for showing details for a given date
*/
public final ObjectProperty<Callback<DateDetailsParameter, Boolean>> dateDetailsCallbackProperty() {
return dateDetailsCallback;
}
/**
* Sets the value of {@link #dateDetailsCallbackProperty()}.
*
* @param callback the date details callback
*/
public final void setDateDetailsCallback(Callback<DateDetailsParameter, Boolean> callback) {
requireNonNull(callback);
dateDetailsCallbackProperty().set(callback);
}
/**
* Returns the value of {@link #dateDetailsCallbackProperty()}.
*
* @return the date details callback
*/
public final Callback<DateDetailsParameter, Boolean> getDateDetailsCallback() {
return dateDetailsCallbackProperty().get();
}
private final ObjectProperty<Callback<EntryDetailsParameter, Boolean>> entryDetailsCallback = new SimpleObjectProperty<>(this, "entryDetailsCallback"); //$NON-NLS-1$
/**
* A callback used for showing the details of a given entry. The default
* implementation of this callback displays a small {@link PopOver} but
* applications might as well display a large dialog where the user can
* freely edit the entry.
* <p>
* <h2>Code Example</h2> The code below shows the default implementation
* used by all date controls. It delegates to a private method that shows
* the popover.
* <p>
* <pre>
* setEntryDetailsCallback(param -> {
* InputEvent evt = param.getInputEvent();
* if (evt instanceof MouseEvent) {
* MouseEvent mouseEvent = (MouseEvent) evt;
* if (mouseEvent.getClickCount() == 2) {
* showEntryDetails(param.getEntryView(), param.getOwner(), param.getScreenX(), param.getScreenY());
* return true;
* }
* } else {
* showEntryDetails(param.getEntryView(), param.getOwner(), param.getScreenX(), param.getScreenY());
* return true;
* }
*
* return false;
* });
* </pre>
*
* @return the callback used for showing details for a given entry
*/
public final ObjectProperty<Callback<EntryDetailsParameter, Boolean>> entryDetailsCallbackProperty() {
return entryDetailsCallback;
}
/**
* Sets the value of {@link #entryDetailsCallbackProperty()}.
*
* @param callback the entry details callback
*/
public final void setEntryDetailsCallback(Callback<EntryDetailsParameter, Boolean> callback) {
requireNonNull(callback);
entryDetailsCallbackProperty().set(callback);
}
/**
* Returns the value of {@link #entryDetailsCallbackProperty()}.
*
* @return the entry details callback
*/
public final Callback<EntryDetailsParameter, Boolean> getEntryDetailsCallback() {
return entryDetailsCallbackProperty().get();
}
////////////
/**
* The parameter object passed to the entry details popover content
* callback.
*
* @see DateControl#entryDetailsPopOverContentCallbackProperty()
*/
public final static class EntryDetailsPopOverContentParameter {
private DateControl dateControl;
private Node node;
private Entry<?> entry;
private PopOver popOver;
/**
* Constructs a new parameter object.
*
* @param popOver the pop over for which details will be created
* @param control the control where the event occurred
* @param node the node where the event occurred
* @param entry the entry for which details will be shown
*/
public EntryDetailsPopOverContentParameter(PopOver popOver, DateControl control, Node node, Entry<?> entry) {
this.popOver = requireNonNull(popOver);
this.dateControl = requireNonNull(control);
this.node = requireNonNull(node);
this.entry = requireNonNull(entry);
}
/**
* Returns the popover in which the content will be shown.
*
* @return the popover
*/
public PopOver getPopOver() {
return popOver;
}
/**
* The date control where the popover was requested.
*
* @return the date control
*/
public DateControl getDateControl() {
return dateControl;
}
/**
* The node for which the popover was requested.
*
* @return the node
*/
public Node getNode() {
return node;
}
/**
* The entry for which the popover was requested.
*
* @return the entry
*/
public Entry<?> getEntry() {
return entry;
}
}
private final ObjectProperty<Callback<EntryDetailsPopOverContentParameter, Node>> entryDetailsPopoverContentCallback = new SimpleObjectProperty<>(this, "entryDetailsPopoverContentCallback"); //$NON-NLS-1$
/**
* Stores a callback for creating the content of the popover.
*
* @return the popover content callback
*/
public final ObjectProperty<Callback<EntryDetailsPopOverContentParameter, Node>> entryDetailsPopOverContentCallbackProperty() {
return entryDetailsPopoverContentCallback;
}
/**
* Sets the value of {@link #entryDetailsPopOverContentCallbackProperty()}.
*
* @param callback the entry details popover content callback
*/
public final void setEntryDetailsPopOverContentCallback(Callback<EntryDetailsPopOverContentParameter, Node> callback) {
requireNonNull(callback);
entryDetailsPopOverContentCallbackProperty().set(callback);
}
/**
* Returns the value of
* {@link #entryDetailsPopOverContentCallbackProperty()}.
*
* @return the entry details popover content callback
*/
public final Callback<EntryDetailsPopOverContentParameter, Node> getEntryDetailsPopOverContentCallback() {
return entryDetailsPopOverContentCallbackProperty().get();
}
///////////
private final ObjectProperty<LocalDate> today = new SimpleObjectProperty<>(this, "today", LocalDate.now()); //$NON-NLS-1$
/**
* Stores the date that is considered to represent "today". This property is
* initialized with {@link LocalDate#now()} but can be any date.
*
* @return the date representing "today"
*/
public final ObjectProperty<LocalDate> todayProperty() {
return today;
}
/**
* Sets the value of {@link #todayProperty()}.
*
* @param date the date representing "today"
*/
public final void setToday(LocalDate date) {
requireNonNull(date);
todayProperty().set(date);
}
/**
* Returns the value of {@link #todayProperty()}.
*
* @return the date representing "today"
*/
public final LocalDate getToday() {
return todayProperty().get();
}
private final BooleanProperty showToday = new SimpleBooleanProperty(
this, "showToday", true); //$NON-NLS-1$
/**
* A flag used to indicate that the view will mark the area that represents
* the value of {@link #todayProperty()}. By default this area will be
* filled with a different color (red) than the rest (white).
* <p/>
* <center><img src="doc-files/all-day-view-today.png"></center>
*
* @return true if today will be shown differently
*/
public final BooleanProperty showTodayProperty() {
return showToday;
}
/**
* Returns the value of {@link #showTodayProperty()}.
*
* @return true if today will be highlighted visually
*/
public final boolean isShowToday() {
return showTodayProperty().get();
}
/**
* Sets the value of {@link #showTodayProperty()}.
*
* @param show if true today will be highlighted visually
*/
public final void setShowToday(boolean show) {
showTodayProperty().set(show);
}
private final ObjectProperty<LocalDate> date = new SimpleObjectProperty<>(this, "date", LocalDate.now()); //$NON-NLS-1$
/**
* The date that needs to be shown by the date control. This property is
* initialized with {@link LocalDate#now()}.
*
* @return the date shown by the control
*/
public final ObjectProperty<LocalDate> dateProperty() {
return date;
}
/**
* Sets the value of {@link #dateProperty()}.
*
* @param date the date shown by the control
*/
public final void setDate(LocalDate date) {
requireNonNull(date);
dateProperty().set(date);
}
/**
* Returns the value of {@link #dateProperty()}.
*
* @return the date shown by the control
*/
public final LocalDate getDate() {
return dateProperty().get();
}
private final ObjectProperty<ZoneId> zoneId = new SimpleObjectProperty<>(this, "zoneId", ZoneId.systemDefault()); //$NON-NLS-1$
/**
* The time zone used by the date control. Entries and date controls might
* use different time zones resulting in different layout of entry views.
* <p>
* #see {@link Entry#zoneIdProperty()}
*
* @return the time zone used by the date control for calculating entry view
* layouts
*/
public final ObjectProperty<ZoneId> zoneIdProperty() {
return zoneId;
}
/**
* Sets the value of {@link #zoneIdProperty()}.
*
* @param zoneId the time zone
*/
public final void setZoneId(ZoneId zoneId) {
requireNonNull(zoneId);
zoneIdProperty().set(zoneId);
}
/**
* Returns the value of {@link #zoneIdProperty()}.
*
* @return the time zone
*/
public final ZoneId getZoneId() {
return zoneIdProperty().get();
}
private final ObjectProperty<LocalTime> time = new SimpleObjectProperty<>(this, "time", LocalTime.now()); //$NON-NLS-1$
/**
* Stores a time that can be visualized, e.g. the thin line in
* {@link DayView} representing the current time.
*
* @return the current time
*/
public final ObjectProperty<LocalTime> timeProperty() {
return time;
}
/**
* Sets the value of {@link #timeProperty()}.
*
* @param time the current time
*/
public final void setTime(LocalTime time) {
requireNonNull(time);
timeProperty().set(time);
}
/**
* Returns the value of {@link #timeProperty()}.
*
* @return the current time
*/
public final LocalTime getTime() {
return timeProperty().get();
}
private final ObjectProperty<LocalTime> startTime = new SimpleObjectProperty<>(this, "startTime", LocalTime.of(6, 0)); //$NON-NLS-1$
/**
* A start time used to limit the time interval shown by the control. The
* {@link DayView} uses this property and the {@link #endTimeProperty()} to
* support the concept of "early" and "late" hours. These hours can be
* hidden if required.
*
* @return the start time
*/
public final ObjectProperty<LocalTime> startTimeProperty() {
return startTime;
}
/**
* Returns the value of {@link #startTimeProperty()}.
*
* @return the start time
*/
public final LocalTime getStartTime() {
return startTimeProperty().get();
}
/**
* Sets the value of {@link #startTimeProperty()}.
*
* @param time the start time
*/
public final void setStartTime(LocalTime time) {
startTimeProperty().set(time);
}
private final ObjectProperty<LocalTime> endTime = new SimpleObjectProperty<>(this, "endTime", LocalTime.of(22, 0)); //$NON-NLS-1$
/**
* An end time used to limit the time interval shown by the control. The
* {@link DayView} uses this property and the {@link #startTimeProperty()}
* to support the concept of "early" and "late" hours. These hours can be
* hidden if required.
*
* @return the end time
*/
public final ObjectProperty<LocalTime> endTimeProperty() {
return endTime;
}
/**
* Returns the value of {@link #endTimeProperty()}.
*
* @return the end time
*/
public final LocalTime getEndTime() {
return endTimeProperty().get();
}
/**
* Sets the value of {@link #endTimeProperty()}.
*
* @param time the end time
*/
public final void setEndTime(LocalTime time) {
endTimeProperty().set(time);
}
private final ObjectProperty<WeekFields> weekFields = new SimpleObjectProperty<>(this, "weekFields", WeekFields.of(Locale.getDefault())); //$NON-NLS-1$
/**
* Week fields are used to determine the first day of a week (e.g. "Monday"
* in Germany or "Sunday" in the US). It is also used to calculate the week
* number as the week fields determine how many days are needed in the first
* week of a year. This property is initialized with {@link WeekFields#ISO}.
*
* @return the week fields
*/
public final ObjectProperty<WeekFields> weekFieldsProperty() {
return weekFields;
}
/**
* Sets the value of {@link #weekFieldsProperty()}.
*
* @param weekFields the new week fields
*/
public final void setWeekFields(WeekFields weekFields) {
requireNonNull(weekFields);
weekFieldsProperty().set(weekFields);
}
/**
* Returns the value of {@link #weekFieldsProperty()}.
*
* @return the week fields
*/
public final WeekFields getWeekFields() {
return weekFieldsProperty().get();
}
/**
* A convenience method to lookup the first day of the week ("Monday" in
* Germany, "Sunday" in the US). This method delegates to
* {@link WeekFields#getFirstDayOfWeek()}.
*
* @return the first day of the week
* @see #weekFieldsProperty()
*/
public final DayOfWeek getFirstDayOfWeek() {
return getWeekFields().getFirstDayOfWeek();
}
private final ReadOnlyListWrapper<Calendar> calendars = new ReadOnlyListWrapper<>(FXCollections.observableArrayList());
/**
* A list that contains all calendars found in all calendar sources
* currently attached to this date control. This is a convenience list that
* "flattens" the two level structure of sources and their calendars. It is
* a read-only list because calendars can not be added directly to a date
* control. Instead they are added to calendar sources and those sources are
* then added to the control.
*
* @return the list of all calendars shown by this control
* @see #getCalendarSources()
*/
public final ReadOnlyListProperty<Calendar> calendarsProperty() {
return calendars.getReadOnlyProperty();
}
private final ObservableList<Calendar> unmodifiableCalendars = FXCollections.unmodifiableObservableList(calendars.get());
/**
* Returns the value of {@link #calendarsProperty()}.
*
* @return the list of all calendars shown by this control
*/
public final ObservableList<Calendar> getCalendars() {
return unmodifiableCalendars;
}
private final ObservableList<CalendarSource> calendarSources = FXCollections.observableArrayList();
/**
* The list of all calendar sources attached to this control. The calendars
* found in all sources are also added to the read-only list that can be
* retrieved by calling {@link #getCalendars()}.
*
* @return the calendar sources
* @see #calendarSourceFactoryProperty()
*/
public final ObservableList<CalendarSource> getCalendarSources() {
return calendarSources;
}
private final ObjectProperty<SelectionMode> selectionMode = new SimpleObjectProperty<>(this, "selectionMode", SelectionMode.MULTIPLE); //$NON-NLS-1$
/**
* Stores the selection mode. All date controls support single and multiple
* selections.
*
* @return the selection mode
* @see SelectionMode
*/
public final ObjectProperty<SelectionMode> selectionModeProperty() {
return selectionMode;
}
/**
* Sets the value of {@link #selectionModeProperty()}.
*
* @param mode the selection mode (single, multiple)
*/
public final void setSelectionMode(SelectionMode mode) {
requireNonNull(mode);
selectionModeProperty().set(mode);
}
/**
* Returns the value of {@link #selectionModeProperty()}.
*
* @return the selection mode (single, multiple)
*/
public final SelectionMode getSelectionMode() {
return selectionModeProperty().get();
}
private final ObservableSet<Entry<?>> selections = FXCollections.observableSet();
/**
* Stores the currently selected entries.
*
* @return the set of currently selected entries
*/
public final ObservableSet<Entry<?>> getSelections() {
return selections;
}
/**
* Adds the given entry to the set of currently selected entries.
*
* @param entry the selected entries
* @see #deselect(Entry)
* @see #getSelections()
*/
public final void select(Entry<?> entry) {
requireNonNull(entry);
selections.add(entry);
}
/**
* Removes the given entry from the set of currently selected entries.
*
* @param entry the selected entries
* @see #select(Entry)
* @see #getSelections()
*/
public final void deselect(Entry<?> entry) {
requireNonNull(entry);
selections.remove(entry);
}
/**
* Clears the current selection of entries.
*/
public final void clearSelection() {
getSelections().clear();
}
private final ObjectProperty<VirtualGrid> virtualGrid = new SimpleObjectProperty<>(this, "virtualGrid", //$NON-NLS-1$
new VirtualGrid(Messages.getString("DateControl.DEFAULT_VIRTUAL_GRID_NAME"), Messages.getString("DateControl.DEFAULT_VIRTUAL_GRID_SHORT_NAME"), ChronoUnit.MINUTES, 15)); //$NON-NLS-1$ //$NON-NLS-2$
/**
* A virtual grid used for snapping to invisible grid lines while editing
* calendar entries. Using a virtual grid makes it easier to edit entries so
* that they all start at exactly the same time. The default grid is set to
* "5 Minutes". {@link VirtualGrid#OFF} can be used to completely disable
* the grid.
*
* @return the virtual grid
*/
public final ObjectProperty<VirtualGrid> virtualGridProperty() {
return virtualGrid;
}
/**
* Returns the value of {@link #virtualGridProperty()}.
*
* @return the currently active grid
*/
public final VirtualGrid getVirtualGrid() {
return virtualGridProperty().get();
}
/**
* Sets the value of {@link #virtualGridProperty()}.
*
* @param grid the grid
*/
public final void setVirtualGrid(VirtualGrid grid) {
requireNonNull(grid);
virtualGridProperty().set(grid);
}
private final ObjectProperty<LocalTime> requestedTime = new SimpleObjectProperty<>(this, "requestedTime", LocalTime.now()); //$NON-NLS-1$
/**
* Stores the time that the application wants to show in its date controls
* when the UI opens up. Most applications will normally set this time to
* {@link LocalTime#now()}.
*
* @return the requested time
*/
public final ObjectProperty<LocalTime> requestedTimeProperty() {
return requestedTime;
}
/**
* Sets the value of {@link #requestedTimeProperty()}.
*
* @param time the requested time
*/
public final void setRequestedTime(LocalTime time) {
requestedTimeProperty().set(time);
}
/**
* Returns the value of {@link #requestedTimeProperty()}.
*
* @return the requested time
*/
public final LocalTime getRequestedTime() {
return requestedTimeProperty().get();
}
/**
* Supported layout strategies by the {@link DayView}.
*/
public enum Layout {
/**
* The standard layout lays out calendar entries in the most efficient
* way without distinguishing between different calendars. This is the
* layout found in most calendar software.
*/
STANDARD,
/**
* The swimlane layout creates virtual columns, one for each calendar.
* The entries of the calendars are shown in their own column. This
* layout strategy is often found in resource booking systems (e.g. one
* calendar per room / per person / per truck).
*/
SWIMLANE
}
private final ObjectProperty<Layout> layout = new SimpleObjectProperty<>(this, "layout", Layout.STANDARD); //$NON-NLS-1$
/**
* Stores the strategy used by the view to layout the entries of several
* calendars at once. The standard layout ignores the source calendar of an
* entry and finds the next available place in the UI that satisfies the
* time bounds of the entry. The {@link Layout#SWIMLANE} strategy allocates
* a separate column for each calendar and resolves overlapping entry
* conflicts within that column. Swim lanes are especially useful for
* resource booking systems (rooms, people, trucks).
*
* @return the layout strategy of the view
*/
public final ObjectProperty<Layout> layoutProperty() {
return layout;
}
/**
* Sets the value of {@link #layoutProperty()}.
*
* @param layout the layout
*/
public final void setLayout(Layout layout) {
requireNonNull(layout);
layoutProperty().set(layout);
}
/**
* Returns the value of {@link #layoutProperty()}.
*
* @return the layout strategy
*/
public final Layout getLayout() {
return layoutProperty().get();
}
private ObservableSet<DayOfWeek> weekendDays = FXCollections.observableSet();
/**
* Returns the days of the week that are considered to be weekend days, for
* example Saturday and Sunday, or Friday and Saturday.
*
* @return the weekend days
*/
public ObservableSet<DayOfWeek> getWeekendDays() {
return weekendDays;
}
/**
* Makes the control go forward in time by adding one or more days to the
* current date. Subclasses override this method to adjust it to their
* needs, e.g. the {@link DetailedWeekView} adds the number of days found in
* {@link DetailedWeekView#getNumberOfDays()}.
*
* @see #dateProperty()
*/
public void goForward() {
setDate(getDate().plusDays(1));
}
/**
* Makes the control go forward in time by removing one or more days from
* the current date. Subclasses override this method to adjust it to their
* needs, e.g. the {@link DetailedWeekView} removes the number of days found in
* {@link DetailedWeekView#getNumberOfDays()}.
*
* @see #dateProperty()
*/
public void goBack() {
setDate(getDate().minusDays(1));
}
/**
* Makes the control go to "today".
*
* @see #dateProperty()
* @see #todayProperty()
*/
public void goToday() {
setDate(getToday());
}
/**
* Finds the first view that represents the given entry.
*
* @param entry the entry
* @return the view
*/
public final EntryViewBase<?> findEntryView(Entry<?> entry) {
requireNonNull(entry);
return doFindEntryView(this, entry);
}
private EntryViewBase<?> doFindEntryView(Parent parent, Entry<?> entry) {
EntryViewBase<?> result = null;
for (Node node : parent.getChildrenUnmodifiable()) {
if (node instanceof EntryViewBase) {
EntryViewBase<?> base = (EntryViewBase<?>) node;
if (base.getEntry().equals(entry)) {
result = base;
break;
}
} else if (node instanceof Parent) {
result = doFindEntryView((Parent) node, entry);
if (result != null) {
break;
}
}
}
return result;
}
private List<DateControl> boundDateControls = FXCollections.observableArrayList();
/**
* Returns all data controls that are bound to this control.
*
* @return the bound date controls / sub controls / children controls
*/
public final List<DateControl> getBoundDateControls() {
return boundDateControls;
}
// hyperlink support
private final BooleanProperty enableHyperlinks = new SimpleBooleanProperty(this, "enableHyperlinks", true);
/**
* A property used to control whether the control allows the user to click on it or an element
* inside of it in order to "jump" to another screen with more detail. Example: in the {@link CalendarView}
* the user can click on the "day of month" label of a cell inside the {@link MonthSheetView} in
* order to switch to the {@link DayPage} where the user will see all entries scheduled for that day.
*
* @return true if the support for hyperlinks is enabled
*/
public final BooleanProperty enableHyperlinksProperty() {
return enableHyperlinks;
}
/**
* Sets the value of the {@link #enableHyperlinksProperty()}.
*
* @param enable if true the hyperlink support will be enabled
*/
public final void setEnableHyperlinks(boolean enable) {
this.enableHyperlinks.set(enable);
}
/**
* Returns the value of the {@link #enableHyperlinksProperty()}.
*
* @return true if the hyperlink support is enabled
*/
public final boolean isEnableHyperlinks() {
return enableHyperlinks.get();
}
/**
* Binds several properties of the given date control to the same properties
* of this control. This kind of binding is needed to create UIs with nested
* date controls. The {@link CalendarView} for example consists of several
* pages. Each page is a date control that consists of several other date
* controls. The {@link DayPage} consists of the {@link AgendaView}, a
* single {@link DayView}, and a {@link YearMonthView} . All of these
* controls are bound to each other so that the application can simply
* change properties on the {@link CalendarView} without worrying about the
* nested controls.
*
* @param otherControl the control that will be bound to this control
* @param bindDate determines if the date property will also be bound
*/
public final void bind(DateControl otherControl, boolean bindDate) {
requireNonNull(otherControl);
boundDateControls.add(otherControl);
// bind maps
Bindings.bindContentBidirectional(otherControl.getCalendarVisibilityMap(), getCalendarVisibilityMap());
// bind lists
Bindings.bindContentBidirectional(otherControl.getCalendarSources(), getCalendarSources());
Bindings.bindContentBidirectional(otherControl.getSelections(), getSelections());
Bindings.bindContentBidirectional(otherControl.getWeekendDays(), getWeekendDays());
// bind properties
Bindings.bindBidirectional(otherControl.suspendUpdatesProperty(), suspendUpdatesProperty());
Bindings.bindBidirectional(otherControl.entryFactoryProperty(), entryFactoryProperty());
Bindings.bindBidirectional(otherControl.defaultCalendarProviderProperty(), defaultCalendarProviderProperty());
Bindings.bindBidirectional(otherControl.virtualGridProperty(), virtualGridProperty());
Bindings.bindBidirectional(otherControl.draggedEntryProperty(), draggedEntryProperty());
Bindings.bindBidirectional(otherControl.requestedTimeProperty(), requestedTimeProperty());
Bindings.bindBidirectional(otherControl.selectionModeProperty(), selectionModeProperty());
Bindings.bindBidirectional(otherControl.selectionModeProperty(), selectionModeProperty());
Bindings.bindBidirectional(otherControl.weekFieldsProperty(), weekFieldsProperty());
Bindings.bindBidirectional(otherControl.layoutProperty(), layoutProperty());
Bindings.bindBidirectional(otherControl.startTimeProperty(), startTimeProperty());
Bindings.bindBidirectional(otherControl.endTimeProperty(), endTimeProperty());
Bindings.bindBidirectional(otherControl.timeProperty(), timeProperty());
Bindings.bindBidirectional(otherControl.usagePolicyProperty(), usagePolicyProperty());
if (bindDate) {
Bindings.bindBidirectional(otherControl.dateProperty(), dateProperty());
}
Bindings.bindBidirectional(otherControl.todayProperty(), todayProperty());
Bindings.bindBidirectional(otherControl.zoneIdProperty(), zoneIdProperty());
// edit callbacks
Bindings.bindBidirectional(otherControl.entryDetailsCallbackProperty(), entryDetailsCallbackProperty());
Bindings.bindBidirectional(otherControl.dateDetailsCallbackProperty(), dateDetailsCallbackProperty());
Bindings.bindBidirectional(otherControl.contextMenuCallbackProperty(), contextMenuCallbackProperty());
Bindings.bindBidirectional(otherControl.entryContextMenuCallbackProperty(), entryContextMenuCallbackProperty());
Bindings.bindBidirectional(otherControl.calendarSourceFactoryProperty(), calendarSourceFactoryProperty());
Bindings.bindBidirectional(otherControl.entryDetailsPopOverContentCallbackProperty(), entryDetailsPopOverContentCallbackProperty());
Bindings.bindBidirectional(otherControl.entryEditPolicyProperty(), entryEditPolicyProperty());
}
/**
* Unbinds the given control from this control. Unbinding is done for all
* properties and observable lists that have previously been bound by the
* {@link #bind(DateControl, boolean)} method.
*
* @param otherControl the control to unbind
*/
public final void unbind(DateControl otherControl) {
requireNonNull(otherControl);
boundDateControls.remove(otherControl);
// unbind maps
Bindings.unbindContentBidirectional(otherControl.getCalendarVisibilityMap(), getCalendarVisibilityMap());
// unbind lists
Bindings.unbindContentBidirectional(otherControl.getCalendarSources(), getCalendarSources());
Bindings.unbindContentBidirectional(otherControl.getSelections(), getSelections());
// unbind properties
Bindings.unbindBidirectional(otherControl.suspendUpdatesProperty(), suspendUpdatesProperty());
Bindings.unbindBidirectional(otherControl.entryFactoryProperty(), entryFactoryProperty());
Bindings.unbindBidirectional(otherControl.defaultCalendarProviderProperty(), defaultCalendarProviderProperty());
Bindings.unbindBidirectional(otherControl.virtualGridProperty(), virtualGridProperty());
Bindings.unbindBidirectional(otherControl.draggedEntryProperty(), draggedEntryProperty());
Bindings.unbindBidirectional(otherControl.requestedTimeProperty(), requestedTimeProperty());
Bindings.unbindBidirectional(otherControl.selectionModeProperty(), selectionModeProperty());
Bindings.unbindBidirectional(otherControl.selectionModeProperty(), selectionModeProperty());
Bindings.unbindBidirectional(otherControl.weekFieldsProperty(), weekFieldsProperty());
Bindings.unbindBidirectional(otherControl.dateProperty(), dateProperty());
Bindings.unbindBidirectional(otherControl.todayProperty(), todayProperty());
Bindings.unbindBidirectional(otherControl.zoneIdProperty(), zoneIdProperty());
Bindings.unbindBidirectional(otherControl.layoutProperty(), layoutProperty());
Bindings.unbindBidirectional(otherControl.startTimeProperty(), startTimeProperty());
Bindings.unbindBidirectional(otherControl.endTimeProperty(), endTimeProperty());
Bindings.unbindBidirectional(otherControl.timeProperty(), timeProperty());
Bindings.unbindBidirectional(otherControl.usagePolicyProperty(), usagePolicyProperty());
// unbind callbacks
Bindings.unbindBidirectional(otherControl.entryDetailsCallbackProperty(), entryDetailsCallbackProperty());
Bindings.unbindBidirectional(otherControl.dateDetailsCallbackProperty(), dateDetailsCallbackProperty());
Bindings.unbindBidirectional(otherControl.contextMenuCallbackProperty(), contextMenuCallbackProperty());
Bindings.unbindBidirectional(otherControl.entryContextMenuCallbackProperty(), entryContextMenuCallbackProperty());
Bindings.unbindBidirectional(otherControl.calendarSourceFactoryProperty(), calendarSourceFactoryProperty());
Bindings.unbindBidirectional(otherControl.entryEditPolicyProperty(), entryEditPolicyProperty());
}
private final BooleanProperty suspendUpdates = new SimpleBooleanProperty(this, "suspendUpdates", false);
/**
* A property that will suspend all updates to the view based on model changes. This feature
* comes in handy when performing large batch updates with many adds and / or removes of calendar
* entries. When this property is set to true the view will not add / remove / update any entry
* views. Once it is set back to false a single refresh will be executed.
*
* @return true if updates are suspended
*/
public final BooleanProperty suspendUpdatesProperty() {
return suspendUpdates;
}
/**
* Returns the value of {@link #suspendUpdatesProperty()}.
*
* @return true if updates are suspended
*/
public final boolean isSuspendUpdates() {
return suspendUpdates.get();
}
/**
* Sets the value of {@link #suspendUpdatesProperty()}.
*
* @param suspend if true updates are suspended
*/
public final void setSuspendUpdates(boolean suspend) {
this.suspendUpdates.set(suspend);
}
// usage policy support
public enum Usage {
NONE,
VERY_LOW,
LOW,
MEDIUM,
HIGH,
VERY_HIGH
}
public final ObjectProperty<Callback<Integer, Usage>> usagePolicy = new SimpleObjectProperty<>(this, "usagePolicy");
/**
* A property used to store a policy that will be used to determine if a given number of entries
* indicates a low or high usage of that day. This policy is used by the {@link YearMonthView} to color
* the background of each day based on the "usage" of that day. The default implementation of this policy
* returns "none" for 0 entries, "very low" for 1 entry, "low" for 2 entries, "medium" for 3 entries,
* "high" for 4 entries, and "very high" for 5 entries or more.
*
* @return the usage policy
*/
public final ObjectProperty<Callback<Integer, Usage>> usagePolicyProperty() {
return usagePolicy;
}
/**
* Sets the value of {@link #usagePolicyProperty()}.
*
* @param policy the new usage policy
*/
public final void setUsagePolicy(Callback<Integer, Usage> policy) {
Objects.requireNonNull(policy);
this.usagePolicy.set(policy);
}
/**
* Returns the value of {@link #usagePolicyProperty()}.
*
* @return the new usage policy
*/
public final Callback<Integer, Usage> getUsagePolicy() {
return usagePolicy.get();
}
private static final String DATE_CONTROL_CATEGORY = "Date Control"; //$NON-NLS-1$
@Override
public ObservableList<Item> getPropertySheetItems() {
ObservableList<Item> items = super.getPropertySheetItems();
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(dateProperty());
}
@Override
public void setValue(Object value) {
setDate((LocalDate) value);
}
@Override
public Object getValue() {
return getDate();
}
@Override
public Class<?> getType() {
return LocalDate.class;
}
@Override
public String getName() {
return "Date"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Date"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(layoutProperty());
}
@Override
public void setValue(Object value) {
setLayout((Layout) value);
}
@Override
public Object getValue() {
return getLayout();
}
@Override
public Class<?> getType() {
return Layout.class;
}
@Override
public String getName() {
return "Layout"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Layout"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(selectionModeProperty());
}
@Override
public void setValue(Object value) {
setSelectionMode((SelectionMode) value);
}
@Override
public Object getValue() {
return getSelectionMode();
}
@Override
public Class<?> getType() {
return SelectionMode.class;
}
@Override
public String getName() {
return "Selection Mode"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Selection Mode"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(todayProperty());
}
@Override
public void setValue(Object value) {
setToday((LocalDate) value);
}
@Override
public Object getValue() {
return getToday();
}
@Override
public Class<?> getType() {
return LocalDate.class;
}
@Override
public String getName() {
return "Today"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Today"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(showTodayProperty());
}
@Override
public void setValue(Object value) {
setShowToday((boolean) value);
}
@Override
public Object getValue() {
return isShowToday();
}
@Override
public Class<?> getType() {
return Boolean.class;
}
@Override
public String getName() {
return "Show Today"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Highlight today"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(zoneIdProperty());
}
@Override
public void setValue(Object value) {
setZoneId((ZoneId) value);
}
@Override
public Object getValue() {
return getZoneId();
}
@Override
public Class<?> getType() {
return ZoneId.class;
}
@Override
public String getName() {
return "Timezone"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Timezone"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(weekFieldsProperty());
}
@Override
public void setValue(Object value) {
setWeekFields((WeekFields) value);
}
@Override
public Object getValue() {
return getWeekFields();
}
@Override
public Class<?> getType() {
return WeekFields.class;
}
@Override
public String getName() {
return "Week Fields"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Week Fields (calendar standard)"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(timeProperty());
}
@Override
public void setValue(Object value) {
setTime((LocalTime) value);
}
@Override
public Object getValue() {
return getTime();
}
@Override
public Class<?> getType() {
return LocalTime.class;
}
@Override
public String getName() {
return "Time"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Time"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(startTimeProperty());
}
@Override
public void setValue(Object value) {
setStartTime((LocalTime) value);
}
@Override
public Object getValue() {
return getStartTime();
}
@Override
public Class<?> getType() {
return LocalTime.class;
}
@Override
public String getName() {
return "Start Time"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "The first visible time at the top."; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(endTimeProperty());
}
@Override
public void setValue(Object value) {
setEndTime((LocalTime) value);
}
@Override
public Object getValue() {
return getEndTime();
}
@Override
public Class<?> getType() {
return LocalTime.class;
}
@Override
public String getName() {
return "End Time"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "The last visible time at the bottom."; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
items.add(new Item() {
@Override
public Optional<ObservableValue<?>> getObservableValue() {
return Optional.of(enableHyperlinksProperty());
}
@Override
public void setValue(Object value) {
setEnableHyperlinks((boolean) value);
}
@Override
public Object getValue() {
return isEnableHyperlinks();
}
@Override
public Class<?> getType() {
return Boolean.class;
}
@Override
public String getName() {
return "Hyperlinks"; //$NON-NLS-1$
}
@Override
public String getDescription() {
return "Hyperlinks enabled / disabled"; //$NON-NLS-1$
}
@Override
public String getCategory() {
return DATE_CONTROL_CATEGORY;
}
});
return items;
}
}
| Code cleanup.
| CalendarFXView/src/main/java/com/calendarfx/view/DateControl.java | Code cleanup. |
|
Java | apache-2.0 | a7b288ce32657b2d4eac6f8d2930f78c12dd8b66 | 0 | cqjjjzr/BiliLiveLib,cqjjjzr/BiliLiveLib,cqjjjzr/BiliLiveLib | package charlie.bililivelib.danmaku;
import charlie.bililivelib.BiliLiveException;
import charlie.bililivelib.GlobalObjects;
import charlie.bililivelib.danmaku.datamodel.JoinServerJson;
import charlie.bililivelib.danmaku.dispatch.DanmakuPacket;
import charlie.bililivelib.danmaku.dispatch.DanmakuReceivePacket;
import charlie.bililivelib.danmaku.dispatch.DispatchManager;
import charlie.bililivelib.danmaku.event.DanmakuEvent;
import charlie.bililivelib.danmaku.event.DanmakuListener;
import charlie.bililivelib.datamodel.Room;
import charlie.bililivelib.i18n.I18n;
import lombok.Getter;
import lombok.Setter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import static charlie.bililivelib.util.ByteArrayOperation.*;
public class DanmakuReceiver implements Runnable {
public static final Charset UTF8 = Charset.forName("UTF-8");
public static final String[] CMT_SERVERS = {
"livecmt-1.bilibili.com",
"livecmt-2.bilibili.com"
};
public static final int CMT_PORT = 788;
public static final int HEARTBEAT_PERIOD = 30 * 1000;
public static final int RESPONSE_HEADER_SIZE = 16;
@Getter
private Room room;
@Getter
@Setter
private long uid;
@Getter
@Setter
private String commentServer;
private List<DanmakuListener> listeners = new LinkedList<>();
private Thread thread;
private Timer heartbeatTimer;
private volatile Status status = Status.NOT_CONNECTED;
private OutputStream outputStream;
private InputStream inputStream;
private Socket socket;
public DanmakuReceiver(Room room) {
this(room, generateRandomUID(), CMT_SERVERS[0]);
}
public DanmakuReceiver(Room room, long uid) {
this(room, uid, CMT_SERVERS[0]);
}
public DanmakuReceiver(Room room, long uid, String commentServer) {
this.room = room;
this.uid = uid;
this.commentServer = commentServer;
}
public void connect() {
if (status == Status.NOT_CONNECTED) {
thread = new Thread(this);
heartbeatTimer = new Timer("DanmakuReceiver-HeartbeatTimer-" + room.getRoomID());
thread.start();
}
}
public void disconnect() {
heartbeatTimer.cancel();
status = Status.NOT_CONNECTED;
try {
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException ignored) {}
}
@Override
public void run() {
startupThread();
try {
socket = new Socket(commentServer, CMT_PORT);
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
joinServer();
status = Status.CONNECTED;
fireDanmakuEvent(I18n.format("msg.danmaku_joined", room.getRoomID()), DanmakuEvent.Kind.JOINED);
heartbeatTimer.schedule(new TimerTask() {
@Override
@SuppressWarnings("deprecation")
public void run() {
try {
writeHeartbeat();
} catch (IOException e) {
fireDanmakuEvent(I18n.format("msg.danmaku_heartbeat_fail",
e.getClass().getName(), e.getMessage()), DanmakuEvent.Kind.ERROR);
disconnect();
}
}
}, 0, HEARTBEAT_PERIOD);
while (status == Status.CONNECTED) {
byte[] tempBuf = new byte[4];
readArray(inputStream, tempBuf, 4);
int length = byteArrayToInt(tempBuf);
checkValidLength(length);
readArray(inputStream, tempBuf, 2); // Magic Number
byte[] shortBuf = new byte[2];
readArray(inputStream, shortBuf, 2);
short protocolVersion = byteArrayToShort(shortBuf);
//checkValidProtocolVersion(protocolVersion);
readArray(inputStream, tempBuf, 4);
int operationID = byteArrayToInt(tempBuf);
readArray(inputStream, tempBuf, 4); // Magic and params
int bodyLength = length - RESPONSE_HEADER_SIZE;
if (bodyLength == 0) continue;
operationID -= 1; // I don't know what this means...
DanmakuReceivePacket.Operation operation = DanmakuReceivePacket.Operation.forID(operationID);
byte[] bodyBuffer = new byte[bodyLength];
readArray(inputStream, bodyBuffer, bodyLength);
dispatchPacket(operation, bodyBuffer);
}
} catch (Exception e) {
if (status == Status.CONNECTED) {
disconnect();
fireDanmakuEvent(I18n.format("msg.danmaku_exception_down",
e.getClass().getName(), e.getMessage()), DanmakuEvent.Kind.ERROR);
}
}
}
private void dispatchPacket(DanmakuReceivePacket.Operation operation, byte[] bodyBuffer) {
switch (operation) {
case PLAYER_COUNT:
int count = byteArrayToInt(bodyBuffer);
fireDanmakuEvent(count, DanmakuEvent.Kind.WATCHER_COUNT);
break;
case UNKNOWN:
case PLAYER_COMMAND:
DispatchManager.instance().dispatch(listeners, new String(bodyBuffer));
}
}
private void checkValidProtocolVersion(short version) throws BiliLiveException {
if (version != 1)
throw new BiliLiveException(I18n.format("msg.danmaku_protocol_error"));
}
private void checkValidLength(int length) throws BiliLiveException {
if (length < 16)
throw new BiliLiveException(I18n.format("msg.danmaku_protocol_error"));
}
private void startupThread() {
Thread.currentThread().setName("DanmakuReceiver-" + room.getRoomID());
}
private void joinServer() throws IOException {
JoinServerJson json = new JoinServerJson(room.getRoomID(), uid);
writePacket(new DanmakuPacket(DanmakuPacket.Action.JOIN_SERVER,
GlobalObjects.instance().getGson().toJson(json)));
}
private void writeHeartbeat() throws IOException {
writePacket(new DanmakuPacket(DanmakuPacket.Action.HEARTBEAT));
}
private void writePacket(DanmakuPacket packet) throws IOException {
outputStream.write(packet.generate());
}
private int readArray(InputStream stream, byte[] buffer, int length) throws IOException {
if (length > buffer.length)
throw new IOException("offset + length > buffer.length");
int readLength = 0;
while (readLength < length) {
int available = stream.read(buffer, 0, length - readLength);
if (available == 0)
throw new IOException("available == 0");
readLength += available;
}
return readLength;
//return stream.read(buffer, 0, length);
}
private static long generateRandomUID() {
return (long) (1e14 + 2e14 * Math.random());
}
public void addDanmakuListener(DanmakuListener listener) {
listeners.add(listener);
}
public void removeDanmakuListener(DanmakuListener listener) {
listeners.remove(listener);
}
private void fireDanmakuEvent(Object param, DanmakuEvent.Kind kind) {
DanmakuEvent event = new DanmakuEvent(this, param, kind);
switch (kind) {
case ERROR:
for (DanmakuListener listener : listeners) {
listener.errorEvent(event);
}
break;
case WATCHER_COUNT:
for (DanmakuListener listener : listeners) {
listener.watcherCountEvent(event);
}
break;
case JOINED:
for (DanmakuListener listener : listeners) {
listener.statusEvent(event);
}
break;
case START_STOP:
for (DanmakuListener listener : listeners) {
listener.startStopEvent(event);
}
break;
}
}
public enum Status {
CONNECTED, NOT_CONNECTED
}
}
| BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuReceiver.java | package charlie.bililivelib.danmaku;
import charlie.bililivelib.BiliLiveException;
import charlie.bililivelib.GlobalObjects;
import charlie.bililivelib.danmaku.datamodel.JoinServerJson;
import charlie.bililivelib.danmaku.dispatch.DanmakuPacket;
import charlie.bililivelib.danmaku.dispatch.DanmakuReceivePacket;
import charlie.bililivelib.danmaku.dispatch.DispatchManager;
import charlie.bililivelib.danmaku.event.DanmakuEvent;
import charlie.bililivelib.danmaku.event.DanmakuListener;
import charlie.bililivelib.datamodel.Room;
import charlie.bililivelib.i18n.I18n;
import lombok.Getter;
import lombok.Setter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import static charlie.bililivelib.util.ByteArrayOperation.*;
public class DanmakuReceiver implements Runnable {
public static final Charset UTF8 = Charset.forName("UTF-8");
public static final String[] CMT_SERVERS = {
"livecmt-1.bilibili.com",
"livecmt-2.bilibili.com"
};
public static final int CMT_PORT = 788;
public static final int HEARTBEAT_PERIOD = 30 * 1000;
public static final int RESPONSE_HEADER_SIZE = 16;
@Getter
private Room room;
@Getter
@Setter
private long uid;
@Getter
@Setter
private String commentServer;
private List<DanmakuListener> listeners = new LinkedList<>();
private Thread thread;
private Timer heartbeatTimer;
private volatile Status status = Status.NOT_CONNECTED;
private OutputStream outputStream;
private InputStream inputStream;
private Socket socket;
public DanmakuReceiver(Room room) {
this(room, generateRandomUID(), CMT_SERVERS[0]);
}
public DanmakuReceiver(Room room, long uid) {
this(room, uid, CMT_SERVERS[0]);
}
public DanmakuReceiver(Room room, long uid, String commentServer) {
this.room = room;
this.uid = uid;
this.commentServer = commentServer;
}
public void connect() {
if (status == Status.NOT_CONNECTED){
thread = new Thread(this);
heartbeatTimer = new Timer("DanmakuReceiver-HeartbeatTimer-" + room.getRoomID());
thread.start();
}
}
public void disconnect() {
heartbeatTimer.cancel();
try {
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException ignored) {}
status = Status.NOT_CONNECTED;
//TODO Safe disconnect
}
@Override
public void run() {
startupThread();
try {
socket = new Socket(commentServer, CMT_PORT);
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
joinServer();
status = Status.CONNECTED;
fireDanmakuEvent(I18n.format("msg.danmaku_joined", room.getRoomID()), DanmakuEvent.Kind.JOINED);
heartbeatTimer.schedule(new TimerTask() {
@Override
@SuppressWarnings("deprecation")
public void run() {
try {
writeHeartbeat();
} catch (IOException e) {
fireDanmakuEvent(I18n.format("msg.danmaku_heartbeat_fail",
e.getClass().getName(), e.getMessage()), DanmakuEvent.Kind.ERROR);
disconnect();
}
}
}, 0, HEARTBEAT_PERIOD);
while (status == Status.CONNECTED) {
byte[] tempBuf = new byte[4];
readArray(inputStream, tempBuf, 4);
int length = byteArrayToInt(tempBuf);
checkValidLength(length);
readArray(inputStream, tempBuf, 2); // Magic Number
byte[] shortBuf = new byte[2];
readArray(inputStream, shortBuf, 2);
short protocolVersion = byteArrayToShort(shortBuf);
//checkValidProtocolVersion(protocolVersion);
readArray(inputStream, tempBuf, 4);
int operationID = byteArrayToInt(tempBuf);
readArray(inputStream, tempBuf, 4); // Magic and params
int bodyLength = length - RESPONSE_HEADER_SIZE;
if (bodyLength == 0) continue;
operationID -= 1; // I don't know what this means...
DanmakuReceivePacket.Operation operation = DanmakuReceivePacket.Operation.forID(operationID);
byte[] bodyBuffer = new byte[bodyLength];
readArray(inputStream, bodyBuffer, bodyLength);
dispatchPacket(operation, bodyBuffer);
}
} catch (Exception e) {
if (status == Status.CONNECTED) {
disconnect();
fireDanmakuEvent(I18n.format("msg.danmaku_exception_down",
e.getClass().getName(), e.getMessage()), DanmakuEvent.Kind.ERROR);
}
}
}
private void dispatchPacket(DanmakuReceivePacket.Operation operation, byte[] bodyBuffer) {
switch (operation) {
case PLAYER_COUNT:
int count = byteArrayToInt(bodyBuffer);
fireDanmakuEvent(count, DanmakuEvent.Kind.WATCHER_COUNT);
break;
case UNKNOWN:
case PLAYER_COMMAND:
DispatchManager.instance().dispatch(listeners, new String(bodyBuffer));
}
}
private void checkValidProtocolVersion(short version) throws BiliLiveException {
if (version != 1)
throw new BiliLiveException(I18n.format("msg.danmaku_protocol_error"));
}
private void checkValidLength(int length) throws BiliLiveException {
if (length < 16)
throw new BiliLiveException(I18n.format("msg.danmaku_protocol_error"));
}
private void startupThread() {
Thread.currentThread().setName("DanmakuReceiver-" + room.getRoomID());
}
private void joinServer() throws IOException {
JoinServerJson json = new JoinServerJson(room.getRoomID(), uid);
writePacket(new DanmakuPacket(DanmakuPacket.Action.JOIN_SERVER,
GlobalObjects.instance().getGson().toJson(json)));
}
private void writeHeartbeat() throws IOException {
writePacket(new DanmakuPacket(DanmakuPacket.Action.HEARTBEAT));
}
private void writePacket(DanmakuPacket packet) throws IOException {
outputStream.write(packet.generate());
}
private int readArray(InputStream stream, byte[] buffer, int length) throws IOException {
if (length > buffer.length)
throw new IOException("offset + length > buffer.length");
int readLength = 0;
while (readLength < length) {
int available = stream.read(buffer, 0, length - readLength);
if (available == 0)
throw new IOException("available == 0");
readLength += available;
}
return readLength;
//return stream.read(buffer, 0, length);
}
private static long generateRandomUID() {
return (long) (1e14 + 2e14 * Math.random());
}
public void addDanmakuListener(DanmakuListener listener) {
listeners.add(listener);
}
public void removeDanmakuListener(DanmakuListener listener) {
listeners.remove(listener);
}
private void fireDanmakuEvent(Object param, DanmakuEvent.Kind kind) {
DanmakuEvent event = new DanmakuEvent(this, param, kind);
switch (kind) {
case ERROR:
for (DanmakuListener listener : listeners) {
listener.errorEvent(event);
}
break;
case WATCHER_COUNT:
for (DanmakuListener listener : listeners) {
listener.watcherCountEvent(event);
}
break;
case JOINED:
for (DanmakuListener listener : listeners) {
listener.statusEvent(event);
}
break;
case START_STOP:
for (DanmakuListener listener : listeners) {
listener.startStopEvent(event);
}
break;
}
}
public enum Status {
CONNECTED, NOT_CONNECTED
}
}
| Safety disconnect for danmaku.
| BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuReceiver.java | Safety disconnect for danmaku. |
|
Java | apache-2.0 | 67c6c6b20d46a362cad29e3cf7ec6be5f5b52c34 | 0 | ibmkendrick/streamsx.topology,ibmkendrick/streamsx.topology,IBMStreams/streamsx.topology,IBMStreams/streamsx.topology,dlaboss/streamsx.topology,dlaboss/streamsx.topology,IBMStreams/streamsx.topology,ddebrunner/streamsx.topology,ddebrunner/streamsx.topology,wmarshall484/streamsx.topology,IBMStreams/streamsx.topology,ibmkendrick/streamsx.topology,wmarshall484/streamsx.topology,ddebrunner/streamsx.topology,ibmkendrick/streamsx.topology,ddebrunner/streamsx.topology,ddebrunner/streamsx.topology,ibmkendrick/streamsx.topology,wmarshall484/streamsx.topology,wmarshall484/streamsx.topology,IBMStreams/streamsx.topology,ddebrunner/streamsx.topology,wmarshall484/streamsx.topology,wmarshall484/streamsx.topology,ibmkendrick/streamsx.topology,wmarshall484/streamsx.topology,wmarshall484/streamsx.topology,ddebrunner/streamsx.topology,IBMStreams/streamsx.topology,IBMStreams/streamsx.topology,ibmkendrick/streamsx.topology | /*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2015
*/
package com.ibm.streamsx.topology.internal.functional.ops;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ibm.json.java.JSONObject;
import com.ibm.streams.operator.OperatorContext;
import com.ibm.streams.operator.Type.MetaType;
import com.ibm.streamsx.topology.builder.GraphBuilder;
import com.ibm.streamsx.topology.context.ContextProperties;
import com.ibm.streamsx.topology.generator.spl.SubmissionTimeValue;
import static com.ibm.streamsx.topology.internal.core.SubmissionParameter.TYPE_SUBMISSION_PARAMETER;
/**
* A manager for making a submission parameter Supplier usable
* from functional logic.
* <p>
* The manager maintains a collection of values for every submission parameter
* in the graph.
* <p>
* The submission parameter's {@code Supplier.get()} implementation learns
* the actual submission parameter value by calling
* {@link #getValue(String, MetaType)}.
* <p>
* The strategy for the manager learning the submission parameter values
* is as follows.
* <p>
* For DISTRIBUTED and STANDALONE (SPL code) submission parameter
* values are conveyed via a NAME_SUBMISSION_PARAMS functional operator
* parameter. The parameter's value consists of all the submission parameters
* created in the graph. All functional operators have the same
* value for this parameter in their OperatorContext. Functional operators
* call {@link #initialize(OperatorContext)}.
* <p>
* For EMBEDDED the functional operator's operator context does not have
* a NAME_SUBMISSION_PARAMS parameter. Instead the EMBEDDED
* {@code StreamsContext.submit()} calls
* {@link #initializeEmbedded(GraphBuilder, Map)}.
* The collection of all submission parameters, with optional default values,
* are learned from the graph and actual values are learned from the
* submit configuration's {@link ContextProperties#SUBMISSION_PARAMS} value.
*/
public class SubmissionParameterManager {
private static abstract class Factory {
abstract Object valueOf(String s);
}
private static Map<MetaType,Factory> factories = new HashMap<>();
static {
// TODO more
factories.put(MetaType.RSTRING, new Factory() {
Object valueOf(String s) { return s; } });
factories.put(MetaType.USTRING, new Factory() {
Object valueOf(String s) { return s; } });
factories.put(MetaType.INT8, new Factory() {
Object valueOf(String s) { return Byte.valueOf(s); } });
factories.put(MetaType.INT16, new Factory() {
Object valueOf(String s) { return Short.valueOf(s); } });
factories.put(MetaType.INT32, new Factory() {
Object valueOf(String s) { return Integer.valueOf(s); } });
factories.put(MetaType.INT64, new Factory() {
Object valueOf(String s) { return Long.valueOf(s); } });
factories.put(MetaType.UINT8, new Factory() {
Object valueOf(String s) { return Byte.valueOf(s); } });
factories.put(MetaType.UINT16, new Factory() {
Object valueOf(String s) { return Short.valueOf(s); } });
factories.put(MetaType.UINT32, new Factory() {
Object valueOf(String s) { return Integer.valueOf(s); } });
factories.put(MetaType.UINT64, new Factory() {
Object valueOf(String s) { return Long.valueOf(s); } });
factories.put(MetaType.FLOAT32, new Factory() {
Object valueOf(String s) { return Float.valueOf(s); } });
factories.put(MetaType.FLOAT64, new Factory() {
Object valueOf(String s) { return Double.valueOf(s); } });
}
private static final Map<String,String> UNINIT_MAP = Collections.emptyMap();
/** map of topology's <spOpParamName, strVal> */
private static volatile Map<String,String> params = UNINIT_MAP;
/** The name of the functional operator's actual SPL parameter
* for the submission parameters names */
public static final String NAME_SUBMISSION_PARAM_NAMES = "submissionParamNames";
/** The name of the functional operator's actual SPL parameter
* for the submission parameters values */
public static final String NAME_SUBMISSION_PARAM_VALUES = "submissionParamValues";
/**
* Initialize submission parameter value information
* from operator context information.
* @param context the operator context
*/
public synchronized static void initialize(OperatorContext context) {
// The TYPE_SPL_SUBMISSION_PARAMS parameter value is the same for
// all operator contexts.
if (params == UNINIT_MAP) {
List<String> names = context.getParameterValues(NAME_SUBMISSION_PARAM_NAMES);
if (names != null && !names.isEmpty()) {
List<String> values = context.getParameterValues(NAME_SUBMISSION_PARAM_VALUES);
Map<String,String> map = new HashMap<>();
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
String value = values.get(i);
map.put(name, value);
}
params = map;
// System.out.println("SPM.initialize() " + params);
}
}
}
/**
* Initialize EMBEDDED submission parameter value information
* from topology's graph and StreamsContext.submit() config.
* @param builder the topology's builder
* @param config StreamsContext.submit() configuration
*/
public synchronized static void initializeEmbedded(GraphBuilder builder,
Map<String, Object> config) {
// N.B. in an embedded context, within a single JVM/classloader,
// multiple topologies can be executed serially as well as concurrently.
// TODO handle the concurrent case - e.g., with per-topology-submit
// managers.
// create map of all submission params used by the topology
// and the parameter's string value (initially null for no default)
Map<String,String> allsp = new HashMap<>(); // spName, spStrVal
JSONObject graph = builder.json();
JSONObject gparams = (JSONObject) graph.get("parameters");
if (gparams != null) {
for (Object o : gparams.keySet()) {
JSONObject param = (JSONObject) gparams.get((String)o);
if (TYPE_SUBMISSION_PARAMETER.equals(param.get("type"))) {
JSONObject spval = (JSONObject) param.get("value");
Object val = spval.get("defaultValue");
if (val != null)
val = val.toString();
allsp.put((String)spval.get("name"), (String)val);
}
}
}
if (allsp.isEmpty())
return;
// update values from config
@SuppressWarnings("unchecked")
Map<String,Object> spValues =
(Map<String, Object>) config.get(ContextProperties.SUBMISSION_PARAMS);
for (String spName : spValues.keySet()) {
if (allsp.containsKey(spName)) {
Object val = spValues.get(spName);
if (val != null)
val = val.toString();
allsp.put(spName, (String)val);
}
}
// failure if any are still undefined
for (String spName : allsp.keySet()) {
if (allsp.get(spName) == null)
throw new IllegalStateException("Submission parameter \""+spName+"\" requires a value but none has been supplied");
}
// good to go. initialize params
params = new HashMap<>();
for (Map.Entry<String, String> e : allsp.entrySet()) {
params.put(SubmissionTimeValue.mkOpParamName(e.getKey()), e.getValue());
}
// System.out.println("SPM.initializeEmbedded() " + params);
}
/**
* Get the submission parameter's value.
* <p>
* The value will be null while composing the topology. It will be
* the actual submission time value when the topology is running.
* @param spName submission parameter name
* @param metaType parameter's metaType
* @return the parameter's value appropriately typed for metaType.
* may be null.
*/
public static Object getValue(String spName, MetaType metaType) {
String value = params.get(SubmissionTimeValue.mkOpParamName(spName));
if (value == null) {
// System.out.println("SPM.getValue "+spName+" "+metaType+ " params " + params);
throw new IllegalArgumentException("Unexpected submission parameter name " + spName);
}
Factory factory = factories.get(metaType);
if (factory == null)
throw new IllegalArgumentException("Unhandled MetaType " + metaType);
return factory.valueOf(value);
}
}
| java/src/com/ibm/streamsx/topology/internal/functional/ops/SubmissionParameterManager.java | /*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2015
*/
package com.ibm.streamsx.topology.internal.functional.ops;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ibm.json.java.JSONObject;
import com.ibm.streams.operator.OperatorContext;
import com.ibm.streams.operator.Type.MetaType;
import com.ibm.streamsx.topology.builder.GraphBuilder;
import com.ibm.streamsx.topology.context.ContextProperties;
import com.ibm.streamsx.topology.generator.spl.SubmissionTimeValue;
import static com.ibm.streamsx.topology.internal.core.SubmissionParameter.TYPE_SUBMISSION_PARAMETER;
/**
* A manager for making a submission parameter Supplier usable
* from functional logic.
* <p>
* The manager maintains a collection of values for every submission parameter
* in the graph.
* <p>
* The submission parameter's {@code Supplier.get()} implementation learns
* the actual submission parameter value by calling
* {@link #getValue(String, MetaType)}.
* <p>
* The strategy for the manager learning the submission parameter values
* is as follows.
* <p>
* For DISTRIBUTED and STANDALONE (SPL code) submission parameter
* values are conveyed via a NAME_SUBMISSION_PARAMS functional operator
* parameter. The parameter's value consists of all the submission parameters
* created in the graph. All functional operators have the same
* value for this parameter in their OperatorContext. Functional operators
* call {@link #initialize(OperatorContext)}.
* <p>
* For EMBEDDED the functional operator's operator context does not have
* a NAME_SUBMISSION_PARAMS parameter. Instead the EMBEDDED
* {@code StreamsContext.submit()} calls
* {@link #initializeEmbedded(GraphBuilder, Map)}.
* The collection of all submission parameters, with optional default values,
* are learned from the graph and actual values are learned from the
* submit configuration's {@link ContextProperties#SUBMISSION_PARAMS} value.
*/
public class SubmissionParameterManager {
private static abstract class Factory {
abstract Object valueOf(String s);
}
private static Map<MetaType,Factory> factories = new HashMap<>();
static {
// TODO more
factories.put(MetaType.RSTRING, new Factory() {
Object valueOf(String s) { return s; } });
factories.put(MetaType.USTRING, new Factory() {
Object valueOf(String s) { return s; } });
factories.put(MetaType.INT8, new Factory() {
Object valueOf(String s) { return Byte.valueOf(s); } });
factories.put(MetaType.INT16, new Factory() {
Object valueOf(String s) { return Short.valueOf(s); } });
factories.put(MetaType.INT32, new Factory() {
Object valueOf(String s) { return Integer.valueOf(s); } });
factories.put(MetaType.INT64, new Factory() {
Object valueOf(String s) { return Long.valueOf(s); } });
factories.put(MetaType.UINT8, new Factory() {
Object valueOf(String s) { return Byte.valueOf(s); } });
factories.put(MetaType.UINT16, new Factory() {
Object valueOf(String s) { return Short.valueOf(s); } });
factories.put(MetaType.UINT32, new Factory() {
Object valueOf(String s) { return Integer.valueOf(s); } });
factories.put(MetaType.UINT64, new Factory() {
Object valueOf(String s) { return Long.valueOf(s); } });
factories.put(MetaType.FLOAT32, new Factory() {
Object valueOf(String s) { return Float.valueOf(s); } });
factories.put(MetaType.FLOAT64, new Factory() {
Object valueOf(String s) { return Double.valueOf(s); } });
}
private static final Map<String,String> UNINIT_MAP = Collections.emptyMap();
/** map of topology's <spOpParamName, strVal> */
private static volatile Map<String,String> params = UNINIT_MAP;
/** The name of the functional operator's actual SPL parameter
* for the submission parameters names */
public static final String NAME_SUBMISSION_PARAM_NAMES = "submissionParamNames";
/** The name of the functional operator's actual SPL parameter
* for the submission parameters values */
public static final String NAME_SUBMISSION_PARAM_VALUES = "submissionParamValues";
/**
* Initialize submission parameter value information
* from operator context information.
* @param context the operator context
*/
public synchronized static void initialize(OperatorContext context) {
// The TYPE_SPL_SUBMISSION_PARAMS parameter value is the same for
// all operator contexts.
if (params == UNINIT_MAP) {
List<String> names = context.getParameterValues(NAME_SUBMISSION_PARAM_NAMES);
if (names != null && !names.isEmpty()) {
List<String> values = context.getParameterValues(NAME_SUBMISSION_PARAM_VALUES);
Map<String,String> map = new HashMap<>();
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
String value = values.get(i);
map.put(name, value);
}
params = map;
// System.out.println("SPM.initialize() " + params);
}
}
}
/**
* Initialize EMBEDDED submission parameter value information
* from topology's graph and StreamsContext.submit() config.
* @param builder the topology's builder
* @param config StreamsContext.submit() configuration
*/
public synchronized static void initializeEmbedded(GraphBuilder builder,
Map<String, Object> config) {
if (params != UNINIT_MAP)
return;
// create map of all submission params used by the topology
// and the parameter's string value (initially null for no default)
Map<String,String> allsp = new HashMap<>(); // spName, spStrVal
JSONObject graph = builder.json();
JSONObject gparams = (JSONObject) graph.get("parameters");
if (gparams != null) {
for (Object o : gparams.keySet()) {
JSONObject param = (JSONObject) gparams.get((String)o);
if (TYPE_SUBMISSION_PARAMETER.equals(param.get("type"))) {
JSONObject spval = (JSONObject) param.get("value");
Object val = spval.get("defaultValue");
if (val != null)
val = val.toString();
allsp.put((String)spval.get("name"), (String)val);
}
}
}
if (allsp.isEmpty())
return;
// update values from config
@SuppressWarnings("unchecked")
Map<String,Object> spValues =
(Map<String, Object>) config.get(ContextProperties.SUBMISSION_PARAMS);
for (String spName : spValues.keySet()) {
if (allsp.containsKey(spName)) {
Object val = spValues.get(spName);
if (val != null)
val = val.toString();
allsp.put(spName, (String)val);
}
}
// failure if any are still undefined
for (String spName : allsp.keySet()) {
if (allsp.get(spName) == null)
throw new IllegalStateException("Submission parameter \""+spName+"\" requires a value but none has been supplied");
}
// good to go. initialize params
params = new HashMap<>();
for (Map.Entry<String, String> e : allsp.entrySet()) {
params.put(SubmissionTimeValue.mkOpParamName(e.getKey()), e.getValue());
}
// System.out.println("SPM.initializeEmbedded() " + params);
}
/**
* Get the submission parameter's value.
* <p>
* The value will be null while composing the topology. It will be
* the actual submission time value when the topology is running.
* @param spName submission parameter name
* @param metaType parameter's metaType
* @return the parameter's value appropriately typed for metaType.
* may be null.
*/
public static Object getValue(String spName, MetaType metaType) {
String value = params.get(SubmissionTimeValue.mkOpParamName(spName));
if (value == null) {
// System.out.println("SPM.getValue "+spName+" "+metaType+ " params " + params);
throw new IllegalArgumentException("Unexpected submission parameter name " + spName);
}
Factory factory = factories.get(metaType);
if (factory == null)
throw new IllegalArgumentException("Unhandled MetaType " + metaType);
return factory.valueOf(value);
}
}
| woops, broke the embedded serial submits case with prev commit. | java/src/com/ibm/streamsx/topology/internal/functional/ops/SubmissionParameterManager.java | woops, broke the embedded serial submits case with prev commit. |
|
Java | apache-2.0 | 7134271537496e4c140b1e6f47517ca302a97d51 | 0 | treasure-data/presto,Teradata/presto,raghavsethi/presto,ebyhr/presto,miniway/presto,wagnermarkd/presto,smartnews/presto,shixuan-fan/presto,jxiang/presto,haozhun/presto,raghavsethi/presto,gh351135612/presto,Praveen2112/presto,11xor6/presto,youngwookim/presto,nezihyigitbasi/presto,stewartpark/presto,ebyhr/presto,mbeitchman/presto,raghavsethi/presto,shixuan-fan/presto,electrum/presto,treasure-data/presto,ptkool/presto,EvilMcJerkface/presto,jxiang/presto,smartnews/presto,wyukawa/presto,Praveen2112/presto,erichwang/presto,hgschmie/presto,ebyhr/presto,prateek1306/presto,EvilMcJerkface/presto,yuananf/presto,erichwang/presto,Yaliang/presto,hgschmie/presto,arhimondr/presto,losipiuk/presto,smartnews/presto,prateek1306/presto,erichwang/presto,erichwang/presto,elonazoulay/presto,hgschmie/presto,treasure-data/presto,elonazoulay/presto,yuananf/presto,erichwang/presto,twitter-forks/presto,ptkool/presto,facebook/presto,zzhao0/presto,ebyhr/presto,11xor6/presto,losipiuk/presto,wyukawa/presto,mbeitchman/presto,aramesh117/presto,wyukawa/presto,shixuan-fan/presto,gh351135612/presto,yuananf/presto,ebyhr/presto,mvp/presto,electrum/presto,losipiuk/presto,miniway/presto,electrum/presto,prestodb/presto,zzhao0/presto,mbeitchman/presto,EvilMcJerkface/presto,aramesh117/presto,facebook/presto,ptkool/presto,Teradata/presto,wyukawa/presto,dain/presto,wagnermarkd/presto,facebook/presto,mvp/presto,mbeitchman/presto,Teradata/presto,prestodb/presto,dain/presto,haozhun/presto,Yaliang/presto,twitter-forks/presto,stewartpark/presto,shixuan-fan/presto,treasure-data/presto,prestodb/presto,smartnews/presto,EvilMcJerkface/presto,raghavsethi/presto,wagnermarkd/presto,dain/presto,sopel39/presto,twitter-forks/presto,martint/presto,nezihyigitbasi/presto,haozhun/presto,11xor6/presto,nezihyigitbasi/presto,miniway/presto,prestodb/presto,gh351135612/presto,miniway/presto,mvp/presto,sopel39/presto,Praveen2112/presto,gh351135612/presto,yuananf/presto,stewartpark/presto,treasure-data/presto,mvp/presto,youngwookim/presto,electrum/presto,prateek1306/presto,facebook/presto,zzhao0/presto,youngwookim/presto,facebook/presto,11xor6/presto,Yaliang/presto,smartnews/presto,twitter-forks/presto,sopel39/presto,zzhao0/presto,elonazoulay/presto,mbeitchman/presto,raghavsethi/presto,prestodb/presto,wagnermarkd/presto,jxiang/presto,prateek1306/presto,prateek1306/presto,losipiuk/presto,arhimondr/presto,arhimondr/presto,elonazoulay/presto,youngwookim/presto,aramesh117/presto,haozhun/presto,arhimondr/presto,martint/presto,11xor6/presto,ptkool/presto,martint/presto,sopel39/presto,Praveen2112/presto,twitter-forks/presto,jxiang/presto,aramesh117/presto,losipiuk/presto,nezihyigitbasi/presto,martint/presto,shixuan-fan/presto,mvp/presto,sopel39/presto,dain/presto,wagnermarkd/presto,Yaliang/presto,electrum/presto,arhimondr/presto,elonazoulay/presto,aramesh117/presto,gh351135612/presto,prestodb/presto,hgschmie/presto,jxiang/presto,miniway/presto,Teradata/presto,wyukawa/presto,zzhao0/presto,Yaliang/presto,martint/presto,hgschmie/presto,Praveen2112/presto,Teradata/presto,youngwookim/presto,dain/presto,stewartpark/presto,treasure-data/presto,yuananf/presto,ptkool/presto,nezihyigitbasi/presto,haozhun/presto,EvilMcJerkface/presto,stewartpark/presto | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator;
import com.facebook.presto.ExceededMemoryLimitException;
import com.facebook.presto.RowPagesBuilder;
import com.facebook.presto.memory.AggregatedMemoryContext;
import com.facebook.presto.metadata.MetadataManager;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.operator.HashAggregationOperator.HashAggregationOperatorFactory;
import com.facebook.presto.operator.aggregation.InternalAggregationFunction;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.BlockBuilderStatus;
import com.facebook.presto.spi.block.PageBuilderStatus;
import com.facebook.presto.spi.type.StandardTypes;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spiller.Spiller;
import com.facebook.presto.spiller.SpillerFactory;
import com.facebook.presto.sql.gen.JoinCompiler;
import com.facebook.presto.sql.planner.plan.AggregationNode.Step;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.facebook.presto.testing.MaterializedResult;
import com.facebook.presto.testing.TestingTaskContext;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.slice.Slices;
import io.airlift.units.DataSize;
import io.airlift.units.DataSize.Unit;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import static com.facebook.presto.RowPagesBuilder.rowPagesBuilder;
import static com.facebook.presto.SessionTestUtils.TEST_SESSION;
import static com.facebook.presto.metadata.FunctionKind.AGGREGATE;
import static com.facebook.presto.operator.OperatorAssertion.assertOperatorEqualsIgnoreOrder;
import static com.facebook.presto.operator.OperatorAssertion.dropChannel;
import static com.facebook.presto.operator.OperatorAssertion.toMaterializedResult;
import static com.facebook.presto.operator.OperatorAssertion.toPages;
import static com.facebook.presto.operator.OperatorAssertion.without;
import static com.facebook.presto.spi.block.BlockBuilderStatus.DEFAULT_MAX_BLOCK_SIZE_IN_BYTES;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.BooleanType.BOOLEAN;
import static com.facebook.presto.spi.type.DoubleType.DOUBLE;
import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static com.facebook.presto.testing.MaterializedResult.resultBuilder;
import static com.facebook.presto.testing.TestingTaskContext.createTaskContext;
import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static io.airlift.concurrent.Threads.daemonThreadsNamed;
import static io.airlift.slice.SizeOf.SIZE_OF_DOUBLE;
import static io.airlift.slice.SizeOf.SIZE_OF_LONG;
import static io.airlift.testing.Assertions.assertEqualsIgnoreOrder;
import static io.airlift.units.DataSize.Unit.KILOBYTE;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static io.airlift.units.DataSize.succinctBytes;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
@Test(singleThreaded = true)
public class TestHashAggregationOperator
{
private static final MetadataManager metadata = MetadataManager.createTestMetadataManager();
private static final InternalAggregationFunction LONG_AVERAGE = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("avg", AGGREGATE, DOUBLE.getTypeSignature(), BIGINT.getTypeSignature()));
private static final InternalAggregationFunction LONG_SUM = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("sum", AGGREGATE, BIGINT.getTypeSignature(), BIGINT.getTypeSignature()));
private static final InternalAggregationFunction COUNT = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("count", AGGREGATE, BIGINT.getTypeSignature()));
private ExecutorService executor;
private SpillerFactory spillerFactory = new DummySpillerFactory();
private JoinCompiler joinCompiler = new JoinCompiler();
@BeforeMethod
public void setUp()
{
executor = newCachedThreadPool(daemonThreadsNamed("test-%s"));
}
@DataProvider(name = "hashEnabled")
public static Object[][] hashEnabled()
{
return new Object[][] {{true}, {false}};
}
@DataProvider(name = "hashEnabledAndMemoryLimitBeforeSpillValues")
public static Object[][] hashEnabledAndMemoryLimitBeforeSpillValuesProvider()
{
return new Object[][] {
{true, 8, Integer.MAX_VALUE},
{false, 0, 0},
{false, 8, 0},
{false, 8, Integer.MAX_VALUE}};
}
@AfterMethod
public void tearDown()
{
executor.shutdownNow();
}
@Test(dataProvider = "hashEnabledAndMemoryLimitBeforeSpillValues")
public void testHashAggregation(boolean hashEnabled, long memoryLimitBeforeSpill, long memoryLimitForMergeWithMemory)
throws Exception
{
MetadataManager metadata = MetadataManager.createTestMetadataManager();
InternalAggregationFunction countVarcharColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("count", AGGREGATE, parseTypeSignature(StandardTypes.BIGINT), parseTypeSignature(StandardTypes.VARCHAR)));
InternalAggregationFunction countBooleanColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("count", AGGREGATE, parseTypeSignature(StandardTypes.BIGINT), parseTypeSignature(StandardTypes.BOOLEAN)));
InternalAggregationFunction maxVarcharColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("max", AGGREGATE, parseTypeSignature(StandardTypes.VARCHAR), parseTypeSignature(StandardTypes.VARCHAR)));
List<Integer> hashChannels = Ints.asList(1);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, hashChannels, VARCHAR, VARCHAR, VARCHAR, BIGINT, BOOLEAN);
List<Page> input = rowPagesBuilder
.addSequencePage(10, 100, 0, 100, 0, 500)
.addSequencePage(10, 100, 0, 200, 0, 500)
.addSequencePage(10, 100, 0, 300, 0, 500)
.build();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(VARCHAR),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
false,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty()),
LONG_SUM.bind(ImmutableList.of(3), Optional.empty()),
LONG_AVERAGE.bind(ImmutableList.of(3), Optional.empty()),
maxVarcharColumn.bind(ImmutableList.of(2), Optional.empty()),
countVarcharColumn.bind(ImmutableList.of(0), Optional.empty()),
countBooleanColumn.bind(ImmutableList.of(4), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(16, MEGABYTE),
memoryLimitBeforeSpill > 0,
succinctBytes(memoryLimitBeforeSpill),
succinctBytes(memoryLimitForMergeWithMemory),
spillerFactory,
joinCompiler);
DriverContext driverContext = createDriverContext(memoryLimitBeforeSpill);
MaterializedResult expected = resultBuilder(driverContext.getSession(), VARCHAR, BIGINT, BIGINT, DOUBLE, VARCHAR, BIGINT, BIGINT)
.row("0", 3L, 0L, 0.0, "300", 3L, 3L)
.row("1", 3L, 3L, 1.0, "301", 3L, 3L)
.row("2", 3L, 6L, 2.0, "302", 3L, 3L)
.row("3", 3L, 9L, 3.0, "303", 3L, 3L)
.row("4", 3L, 12L, 4.0, "304", 3L, 3L)
.row("5", 3L, 15L, 5.0, "305", 3L, 3L)
.row("6", 3L, 18L, 6.0, "306", 3L, 3L)
.row("7", 3L, 21L, 7.0, "307", 3L, 3L)
.row("8", 3L, 24L, 8.0, "308", 3L, 3L)
.row("9", 3L, 27L, 9.0, "309", 3L, 3L)
.build();
assertOperatorEqualsIgnoreOrder(operatorFactory, driverContext, input, expected, hashEnabled, Optional.of(hashChannels.size()));
}
@Test(dataProvider = "hashEnabledAndMemoryLimitBeforeSpillValues")
public void testHashAggregationWithGlobals(boolean hashEnabled, long memoryLimitBeforeSpill, long memoryLimitForMergeWithMemory)
throws Exception
{
MetadataManager metadata = MetadataManager.createTestMetadataManager();
InternalAggregationFunction countVarcharColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("count", AGGREGATE, parseTypeSignature(StandardTypes.BIGINT), parseTypeSignature(StandardTypes.VARCHAR)));
InternalAggregationFunction countBooleanColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("count", AGGREGATE, parseTypeSignature(StandardTypes.BIGINT), parseTypeSignature(StandardTypes.BOOLEAN)));
InternalAggregationFunction maxVarcharColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("max", AGGREGATE, parseTypeSignature(StandardTypes.VARCHAR), parseTypeSignature(StandardTypes.VARCHAR)));
Optional<Integer> groupIdChannel = Optional.of(1);
List<Integer> groupByChannels = Ints.asList(1, 2);
List<Integer> globalAggregationGroupIds = Ints.asList(42, 49);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, groupByChannels, VARCHAR, VARCHAR, VARCHAR, BIGINT, BIGINT, BOOLEAN);
List<Page> input = rowPagesBuilder.build();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(VARCHAR, BIGINT),
groupByChannels,
globalAggregationGroupIds,
Step.SINGLE,
true,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty()),
LONG_SUM.bind(ImmutableList.of(4), Optional.empty()),
LONG_AVERAGE.bind(ImmutableList.of(4), Optional.empty()),
maxVarcharColumn.bind(ImmutableList.of(2), Optional.empty()),
countVarcharColumn.bind(ImmutableList.of(0), Optional.empty()),
countBooleanColumn.bind(ImmutableList.of(5), Optional.empty())),
rowPagesBuilder.getHashChannel(),
groupIdChannel,
100_000,
new DataSize(16, MEGABYTE),
memoryLimitBeforeSpill > 0,
succinctBytes(memoryLimitBeforeSpill),
succinctBytes(memoryLimitForMergeWithMemory),
spillerFactory,
joinCompiler);
DriverContext driverContext = createDriverContext(memoryLimitBeforeSpill);
MaterializedResult expected = resultBuilder(driverContext.getSession(), VARCHAR, BIGINT, BIGINT, BIGINT, DOUBLE, VARCHAR, BIGINT, BIGINT)
.row(null, 42L, 0L, null, null, null, 0L, 0L)
.row(null, 49L, 0L, null, null, null, 0L, 0L)
.build();
assertOperatorEqualsIgnoreOrder(operatorFactory, driverContext, input, expected, hashEnabled, Optional.of(groupByChannels.size()));
}
@Test(dataProvider = "hashEnabled", expectedExceptions = ExceededMemoryLimitException.class, expectedExceptionsMessageRegExp = "Query exceeded local memory limit of 10B")
public void testMemoryLimit(boolean hashEnabled)
{
MetadataManager metadata = MetadataManager.createTestMetadataManager();
InternalAggregationFunction maxVarcharColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("max", AGGREGATE, parseTypeSignature(StandardTypes.VARCHAR), parseTypeSignature(StandardTypes.VARCHAR)));
List<Integer> hashChannels = Ints.asList(1);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, hashChannels, VARCHAR, BIGINT, VARCHAR, BIGINT);
List<Page> input = rowPagesBuilder
.addSequencePage(10, 100, 0, 100, 0)
.addSequencePage(10, 100, 0, 200, 0)
.addSequencePage(10, 100, 0, 300, 0)
.build();
DriverContext driverContext = createTaskContext(executor, TEST_SESSION, new DataSize(10, Unit.BYTE))
.addPipelineContext(0, true, true)
.addDriverContext();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(BIGINT),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty()),
LONG_SUM.bind(ImmutableList.of(3), Optional.empty()),
LONG_AVERAGE.bind(ImmutableList.of(3), Optional.empty()),
maxVarcharColumn.bind(ImmutableList.of(2), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(16, MEGABYTE),
joinCompiler);
toPages(operatorFactory, driverContext, input);
}
@Test(dataProvider = "hashEnabledAndMemoryLimitBeforeSpillValues")
public void testHashBuilderResize(boolean hashEnabled, long memoryLimitBeforeSpill, long memoryLimitForMergeWithMemory)
{
BlockBuilder builder = VARCHAR.createBlockBuilder(new BlockBuilderStatus(), 1, DEFAULT_MAX_BLOCK_SIZE_IN_BYTES);
VARCHAR.writeSlice(builder, Slices.allocate(200_000)); // this must be larger than DEFAULT_MAX_BLOCK_SIZE, 64K
builder.build();
List<Integer> hashChannels = Ints.asList(0);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, hashChannels, VARCHAR);
List<Page> input = rowPagesBuilder
.addSequencePage(10, 100)
.addBlocksPage(builder.build())
.addSequencePage(10, 100)
.build();
DriverContext driverContext = createDriverContext(memoryLimitBeforeSpill);
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(VARCHAR),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
false,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(16, MEGABYTE),
memoryLimitBeforeSpill > 0,
succinctBytes(memoryLimitBeforeSpill),
succinctBytes(memoryLimitForMergeWithMemory),
spillerFactory,
joinCompiler);
toPages(operatorFactory, driverContext, input);
}
@Test(dataProvider = "hashEnabled", expectedExceptions = ExceededMemoryLimitException.class, expectedExceptionsMessageRegExp = "Query exceeded local memory limit of 3MB")
public void testHashBuilderResizeLimit(boolean hashEnabled)
{
BlockBuilder builder = VARCHAR.createBlockBuilder(new BlockBuilderStatus(), 1, DEFAULT_MAX_BLOCK_SIZE_IN_BYTES);
VARCHAR.writeSlice(builder, Slices.allocate(5_000_000)); // this must be larger than DEFAULT_MAX_BLOCK_SIZE, 64K
builder.build();
List<Integer> hashChannels = Ints.asList(0);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, hashChannels, VARCHAR);
List<Page> input = rowPagesBuilder
.addSequencePage(10, 100)
.addBlocksPage(builder.build())
.addSequencePage(10, 100)
.build();
DriverContext driverContext = createTaskContext(executor, TEST_SESSION, new DataSize(3, MEGABYTE))
.addPipelineContext(0, true, true)
.addDriverContext();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(VARCHAR),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(16, MEGABYTE),
joinCompiler);
toPages(operatorFactory, driverContext, input);
}
@Test(dataProvider = "hashEnabled")
public void testMultiSliceAggregationOutput(boolean hashEnabled)
{
// estimate the number of entries required to create 1.5 pages of results
int fixedWidthSize = SIZE_OF_LONG + SIZE_OF_DOUBLE + SIZE_OF_DOUBLE;
int multiSlicePositionCount = (int) (1.5 * PageBuilderStatus.DEFAULT_MAX_PAGE_SIZE_IN_BYTES / fixedWidthSize);
multiSlicePositionCount = Math.min((int) (1.5 * DEFAULT_MAX_BLOCK_SIZE_IN_BYTES / SIZE_OF_DOUBLE), multiSlicePositionCount);
List<Integer> hashChannels = Ints.asList(1);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, hashChannels, BIGINT, BIGINT);
List<Page> input = rowPagesBuilder
.addSequencePage(multiSlicePositionCount, 0, 0)
.build();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(BIGINT),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty()),
LONG_AVERAGE.bind(ImmutableList.of(1), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(16, MEGABYTE),
joinCompiler);
assertEquals(toPages(operatorFactory, createDriverContext(), input).size(), 2);
}
@Test(dataProvider = "hashEnabled")
public void testMultiplePartialFlushes(boolean hashEnabled)
throws Exception
{
List<Integer> hashChannels = Ints.asList(0);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, hashChannels, BIGINT);
List<Page> input = rowPagesBuilder
.addSequencePage(500, 0)
.addSequencePage(500, 500)
.addSequencePage(500, 1000)
.addSequencePage(500, 1500)
.build();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(BIGINT),
hashChannels,
ImmutableList.of(),
Step.PARTIAL,
ImmutableList.of(LONG_SUM.bind(ImmutableList.of(0), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(1, KILOBYTE),
joinCompiler);
DriverContext driverContext = createDriverContext(1024, Integer.MAX_VALUE);
try (Operator operator = operatorFactory.createOperator(driverContext)) {
List<Page> expectedPages = rowPagesBuilder(BIGINT, BIGINT)
.addSequencePage(2000, 0, 0)
.build();
MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT)
.pages(expectedPages)
.build();
Iterator<Page> inputIterator = input.iterator();
// Fill up the aggregation
while (operator.needsInput() && inputIterator.hasNext()) {
operator.addInput(inputIterator.next());
}
// Drain the output (partial flush)
List<Page> outputPages = new ArrayList<>();
while (true) {
Page output = operator.getOutput();
if (output == null) {
break;
}
outputPages.add(output);
}
// There should be some pages that were drained
assertTrue(!outputPages.isEmpty());
// The operator need input again since this was a partial flush
assertTrue(operator.needsInput());
// Now, drive the operator to completion
outputPages.addAll(toPages(operator, inputIterator));
MaterializedResult actual;
if (hashEnabled) {
// Drop the hashChannel for all pages
List<Page> actualPages = dropChannel(outputPages, ImmutableList.of(1));
List<Type> expectedTypes = without(operator.getTypes(), ImmutableList.of(1));
actual = toMaterializedResult(operator.getOperatorContext().getSession(), expectedTypes, actualPages);
}
else {
actual = toMaterializedResult(operator.getOperatorContext().getSession(), operator.getTypes(), outputPages);
}
assertEquals(actual.getTypes(), expected.getTypes());
assertEqualsIgnoreOrder(actual.getMaterializedRows(), expected.getMaterializedRows());
}
}
@Test
public void testMergeWithMemorySpill()
{
List<Integer> hashChannels = Ints.asList(0);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(BIGINT);
int smallPagesSpillThresholdSize = 150000;
List<Page> input = rowPagesBuilder
.addSequencePage(smallPagesSpillThresholdSize, 0)
.addSequencePage(10, smallPagesSpillThresholdSize)
.build();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(BIGINT),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
false,
ImmutableList.of(LONG_SUM.bind(ImmutableList.of(0), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
1,
new DataSize(16, MEGABYTE),
true,
new DataSize(smallPagesSpillThresholdSize, Unit.BYTE),
succinctBytes(Integer.MAX_VALUE),
spillerFactory,
joinCompiler);
DriverContext driverContext = createDriverContext(smallPagesSpillThresholdSize);
MaterializedResult.Builder resultBuilder = resultBuilder(driverContext.getSession(), BIGINT);
for (int i = 0; i < smallPagesSpillThresholdSize + 10; ++i) {
resultBuilder.row((long) i, (long) i);
}
assertOperatorEqualsIgnoreOrder(operatorFactory, driverContext, input, resultBuilder.build(), false, Optional.of(hashChannels.size()));
}
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = ".* Failed to spill")
public void testSpillerFailure()
{
MetadataManager metadata = MetadataManager.createTestMetadataManager();
InternalAggregationFunction maxVarcharColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("max", AGGREGATE, parseTypeSignature(StandardTypes.VARCHAR), parseTypeSignature(StandardTypes.VARCHAR)));
List<Integer> hashChannels = Ints.asList(1);
ImmutableList<Type> types = ImmutableList.of(VARCHAR, BIGINT, VARCHAR, BIGINT);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(false, hashChannels, types);
List<Page> input = rowPagesBuilder
.addSequencePage(10, 100, 0, 100, 0)
.addSequencePage(10, 100, 0, 200, 0)
.addSequencePage(10, 100, 0, 300, 0)
.build();
DriverContext driverContext = TestingTaskContext.builder(executor, TEST_SESSION)
.setQueryMaxMemory(DataSize.valueOf("10B"))
.setMemoryPoolSize(DataSize.valueOf("1GB"))
.setSystemMemoryPoolSize(DataSize.valueOf("10B"))
.build()
.addPipelineContext(0, true, true)
.addDriverContext();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(BIGINT),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
false,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty()),
LONG_SUM.bind(ImmutableList.of(3), Optional.empty()),
LONG_AVERAGE.bind(ImmutableList.of(3), Optional.empty()),
maxVarcharColumn.bind(ImmutableList.of(2), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(16, MEGABYTE),
true,
succinctBytes(8),
succinctBytes(Integer.MAX_VALUE),
new FailingSpillerFactory(),
joinCompiler);
toPages(operatorFactory, driverContext, input);
}
private DriverContext createDriverContext()
{
return createDriverContext(Integer.MAX_VALUE);
}
private DriverContext createDriverContext(long systemMemoryLimit)
{
return createDriverContext(Integer.MAX_VALUE, systemMemoryLimit);
}
private DriverContext createDriverContext(long memoryLimit, long systemMemoryLimit)
{
return TestingTaskContext.builder(executor, TEST_SESSION)
.setMemoryPoolSize(succinctBytes(memoryLimit))
.setSystemMemoryPoolSize(succinctBytes(systemMemoryLimit))
.build()
.addPipelineContext(0, true, true)
.addDriverContext();
}
private static class DummySpillerFactory
implements SpillerFactory
{
@Override
public Spiller create(List<Type> types, SpillContext spillContext, AggregatedMemoryContext memoryContext)
{
return new Spiller()
{
private final List<Iterator<Page>> spills = new ArrayList<>();
@Override
public ListenableFuture<?> spill(Iterator<Page> pageIterator)
{
spills.add(pageIterator);
return immediateFuture(null);
}
@Override
public List<Iterator<Page>> getSpills()
{
return spills;
}
@Override
public void close()
{
}
};
}
}
private static class FailingSpillerFactory
implements SpillerFactory
{
@Override
public Spiller create(List<Type> types, SpillContext spillContext, AggregatedMemoryContext memoryContext)
{
return new Spiller()
{
@Override
public ListenableFuture<?> spill(Iterator<Page> pageIterator)
{
return immediateFailedFuture(new IOException("Failed to spill"));
}
@Override
public List<Iterator<Page>> getSpills()
{
return ImmutableList.of();
}
@Override
public void close()
{
}
};
}
}
}
| presto-main/src/test/java/com/facebook/presto/operator/TestHashAggregationOperator.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator;
import com.facebook.presto.ExceededMemoryLimitException;
import com.facebook.presto.RowPagesBuilder;
import com.facebook.presto.memory.AggregatedMemoryContext;
import com.facebook.presto.metadata.MetadataManager;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.operator.HashAggregationOperator.HashAggregationOperatorFactory;
import com.facebook.presto.operator.aggregation.InternalAggregationFunction;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.BlockBuilderStatus;
import com.facebook.presto.spi.block.PageBuilderStatus;
import com.facebook.presto.spi.type.StandardTypes;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spiller.Spiller;
import com.facebook.presto.spiller.SpillerFactory;
import com.facebook.presto.sql.gen.JoinCompiler;
import com.facebook.presto.sql.planner.plan.AggregationNode.Step;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.facebook.presto.testing.MaterializedResult;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.slice.Slices;
import io.airlift.units.DataSize;
import io.airlift.units.DataSize.Unit;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import static com.facebook.presto.RowPagesBuilder.rowPagesBuilder;
import static com.facebook.presto.SessionTestUtils.TEST_SESSION;
import static com.facebook.presto.metadata.FunctionKind.AGGREGATE;
import static com.facebook.presto.operator.OperatorAssertion.assertOperatorEqualsIgnoreOrder;
import static com.facebook.presto.operator.OperatorAssertion.dropChannel;
import static com.facebook.presto.operator.OperatorAssertion.toMaterializedResult;
import static com.facebook.presto.operator.OperatorAssertion.toPages;
import static com.facebook.presto.operator.OperatorAssertion.without;
import static com.facebook.presto.spi.block.BlockBuilderStatus.DEFAULT_MAX_BLOCK_SIZE_IN_BYTES;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.BooleanType.BOOLEAN;
import static com.facebook.presto.spi.type.DoubleType.DOUBLE;
import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static com.facebook.presto.testing.MaterializedResult.resultBuilder;
import static com.facebook.presto.testing.TestingTaskContext.createTaskContext;
import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static io.airlift.concurrent.Threads.daemonThreadsNamed;
import static io.airlift.slice.SizeOf.SIZE_OF_DOUBLE;
import static io.airlift.slice.SizeOf.SIZE_OF_LONG;
import static io.airlift.testing.Assertions.assertEqualsIgnoreOrder;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static io.airlift.units.DataSize.succinctBytes;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
@Test(singleThreaded = true)
public class TestHashAggregationOperator
{
private static final MetadataManager metadata = MetadataManager.createTestMetadataManager();
private static final InternalAggregationFunction LONG_AVERAGE = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("avg", AGGREGATE, DOUBLE.getTypeSignature(), BIGINT.getTypeSignature()));
private static final InternalAggregationFunction LONG_SUM = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("sum", AGGREGATE, BIGINT.getTypeSignature(), BIGINT.getTypeSignature()));
private static final InternalAggregationFunction COUNT = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("count", AGGREGATE, BIGINT.getTypeSignature()));
private ExecutorService executor;
private DriverContext driverContext;
private SpillerFactory spillerFactory = new DummySpillerFactory();
private JoinCompiler joinCompiler = new JoinCompiler();
@BeforeMethod
public void setUp()
{
executor = newCachedThreadPool(daemonThreadsNamed("test-%s"));
driverContext = createTaskContext(executor, TEST_SESSION)
.addPipelineContext(0, true, true)
.addDriverContext();
}
@DataProvider(name = "hashEnabled")
public static Object[][] hashEnabled()
{
return new Object[][] {{true}, {false}};
}
@DataProvider(name = "hashEnabledAndMemoryLimitBeforeSpillValues")
public static Object[][] hashEnabledAndMemoryLimitBeforeSpillValuesProvider()
{
return new Object[][] {
{true, 8, Integer.MAX_VALUE},
{false, 0, 0},
{false, 8, 0},
{false, 8, Integer.MAX_VALUE}};
}
@AfterMethod
public void tearDown()
{
executor.shutdownNow();
}
@Test(dataProvider = "hashEnabledAndMemoryLimitBeforeSpillValues")
public void testHashAggregation(boolean hashEnabled, long memoryLimitBeforeSpill, long memoryLimitForMergeWithMemory)
throws Exception
{
MetadataManager metadata = MetadataManager.createTestMetadataManager();
InternalAggregationFunction countVarcharColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("count", AGGREGATE, parseTypeSignature(StandardTypes.BIGINT), parseTypeSignature(StandardTypes.VARCHAR)));
InternalAggregationFunction countBooleanColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("count", AGGREGATE, parseTypeSignature(StandardTypes.BIGINT), parseTypeSignature(StandardTypes.BOOLEAN)));
InternalAggregationFunction maxVarcharColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("max", AGGREGATE, parseTypeSignature(StandardTypes.VARCHAR), parseTypeSignature(StandardTypes.VARCHAR)));
List<Integer> hashChannels = Ints.asList(1);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, hashChannels, VARCHAR, VARCHAR, VARCHAR, BIGINT, BOOLEAN);
List<Page> input = rowPagesBuilder
.addSequencePage(10, 100, 0, 100, 0, 500)
.addSequencePage(10, 100, 0, 200, 0, 500)
.addSequencePage(10, 100, 0, 300, 0, 500)
.build();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(VARCHAR),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
false,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty()),
LONG_SUM.bind(ImmutableList.of(3), Optional.empty()),
LONG_AVERAGE.bind(ImmutableList.of(3), Optional.empty()),
maxVarcharColumn.bind(ImmutableList.of(2), Optional.empty()),
countVarcharColumn.bind(ImmutableList.of(0), Optional.empty()),
countBooleanColumn.bind(ImmutableList.of(4), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(16, MEGABYTE),
memoryLimitBeforeSpill > 0,
succinctBytes(memoryLimitBeforeSpill),
succinctBytes(memoryLimitForMergeWithMemory),
spillerFactory,
joinCompiler);
MaterializedResult expected = resultBuilder(driverContext.getSession(), VARCHAR, BIGINT, BIGINT, DOUBLE, VARCHAR, BIGINT, BIGINT)
.row("0", 3L, 0L, 0.0, "300", 3L, 3L)
.row("1", 3L, 3L, 1.0, "301", 3L, 3L)
.row("2", 3L, 6L, 2.0, "302", 3L, 3L)
.row("3", 3L, 9L, 3.0, "303", 3L, 3L)
.row("4", 3L, 12L, 4.0, "304", 3L, 3L)
.row("5", 3L, 15L, 5.0, "305", 3L, 3L)
.row("6", 3L, 18L, 6.0, "306", 3L, 3L)
.row("7", 3L, 21L, 7.0, "307", 3L, 3L)
.row("8", 3L, 24L, 8.0, "308", 3L, 3L)
.row("9", 3L, 27L, 9.0, "309", 3L, 3L)
.build();
assertOperatorEqualsIgnoreOrder(operatorFactory, driverContext, input, expected, hashEnabled, Optional.of(hashChannels.size()));
}
@Test(dataProvider = "hashEnabled")
public void testHashAggregationWithGlobals(boolean hashEnabled)
throws Exception
{
MetadataManager metadata = MetadataManager.createTestMetadataManager();
InternalAggregationFunction countVarcharColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("count", AGGREGATE, parseTypeSignature(StandardTypes.BIGINT), parseTypeSignature(StandardTypes.VARCHAR)));
InternalAggregationFunction countBooleanColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("count", AGGREGATE, parseTypeSignature(StandardTypes.BIGINT), parseTypeSignature(StandardTypes.BOOLEAN)));
InternalAggregationFunction maxVarcharColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("max", AGGREGATE, parseTypeSignature(StandardTypes.VARCHAR), parseTypeSignature(StandardTypes.VARCHAR)));
Optional<Integer> groupIdChannel = Optional.of(1);
List<Integer> groupByChannels = Ints.asList(1, 2);
List<Integer> globalAggregationGroupIds = Ints.asList(42, 49);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, groupByChannels, VARCHAR, VARCHAR, VARCHAR, BIGINT, BIGINT, BOOLEAN);
List<Page> input = rowPagesBuilder.build();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(VARCHAR, BIGINT),
groupByChannels,
globalAggregationGroupIds,
Step.SINGLE,
true,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty()),
LONG_SUM.bind(ImmutableList.of(4), Optional.empty()),
LONG_AVERAGE.bind(ImmutableList.of(4), Optional.empty()),
maxVarcharColumn.bind(ImmutableList.of(2), Optional.empty()),
countVarcharColumn.bind(ImmutableList.of(0), Optional.empty()),
countBooleanColumn.bind(ImmutableList.of(5), Optional.empty())),
rowPagesBuilder.getHashChannel(),
groupIdChannel,
100_000,
new DataSize(16, MEGABYTE),
false,
new DataSize(0, MEGABYTE),
new DataSize(0, MEGABYTE),
spillerFactory,
joinCompiler);
MaterializedResult expected = resultBuilder(driverContext.getSession(), VARCHAR, BIGINT, BIGINT, BIGINT, DOUBLE, VARCHAR, BIGINT, BIGINT)
.row(null, 42L, 0L, null, null, null, 0L, 0L)
.row(null, 49L, 0L, null, null, null, 0L, 0L)
.build();
assertOperatorEqualsIgnoreOrder(operatorFactory, driverContext, input, expected, hashEnabled, Optional.of(groupByChannels.size()));
}
@Test(dataProvider = "hashEnabled", expectedExceptions = ExceededMemoryLimitException.class, expectedExceptionsMessageRegExp = "Query exceeded local memory limit of 10B")
public void testMemoryLimit(boolean hashEnabled)
{
MetadataManager metadata = MetadataManager.createTestMetadataManager();
InternalAggregationFunction maxVarcharColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("max", AGGREGATE, parseTypeSignature(StandardTypes.VARCHAR), parseTypeSignature(StandardTypes.VARCHAR)));
List<Integer> hashChannels = Ints.asList(1);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, hashChannels, VARCHAR, BIGINT, VARCHAR, BIGINT);
List<Page> input = rowPagesBuilder
.addSequencePage(10, 100, 0, 100, 0)
.addSequencePage(10, 100, 0, 200, 0)
.addSequencePage(10, 100, 0, 300, 0)
.build();
DriverContext driverContext = createTaskContext(executor, TEST_SESSION, new DataSize(10, Unit.BYTE))
.addPipelineContext(0, true, true)
.addDriverContext();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(BIGINT),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty()),
LONG_SUM.bind(ImmutableList.of(3), Optional.empty()),
LONG_AVERAGE.bind(ImmutableList.of(3), Optional.empty()),
maxVarcharColumn.bind(ImmutableList.of(2), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(16, MEGABYTE),
joinCompiler);
toPages(operatorFactory, driverContext, input);
}
@Test(dataProvider = "hashEnabledAndMemoryLimitBeforeSpillValues")
public void testHashBuilderResize(boolean hashEnabled, long memoryLimitBeforeSpill, long memoryLimitForMergeWithMemory)
{
BlockBuilder builder = VARCHAR.createBlockBuilder(new BlockBuilderStatus(), 1, DEFAULT_MAX_BLOCK_SIZE_IN_BYTES);
VARCHAR.writeSlice(builder, Slices.allocate(200_000)); // this must be larger than DEFAULT_MAX_BLOCK_SIZE, 64K
builder.build();
List<Integer> hashChannels = Ints.asList(0);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, hashChannels, VARCHAR);
List<Page> input = rowPagesBuilder
.addSequencePage(10, 100)
.addBlocksPage(builder.build())
.addSequencePage(10, 100)
.build();
DriverContext driverContext = createTaskContext(executor, TEST_SESSION, new DataSize(10, MEGABYTE))
.addPipelineContext(0, true, true)
.addDriverContext();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(VARCHAR),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
false,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(16, MEGABYTE),
memoryLimitBeforeSpill > 0,
succinctBytes(memoryLimitBeforeSpill),
succinctBytes(memoryLimitForMergeWithMemory),
spillerFactory,
joinCompiler);
toPages(operatorFactory, driverContext, input);
}
@Test(dataProvider = "hashEnabled", expectedExceptions = ExceededMemoryLimitException.class, expectedExceptionsMessageRegExp = "Query exceeded local memory limit of 3MB")
public void testHashBuilderResizeLimit(boolean hashEnabled)
{
BlockBuilder builder = VARCHAR.createBlockBuilder(new BlockBuilderStatus(), 1, DEFAULT_MAX_BLOCK_SIZE_IN_BYTES);
VARCHAR.writeSlice(builder, Slices.allocate(5_000_000)); // this must be larger than DEFAULT_MAX_BLOCK_SIZE, 64K
builder.build();
List<Integer> hashChannels = Ints.asList(0);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, hashChannels, VARCHAR);
List<Page> input = rowPagesBuilder
.addSequencePage(10, 100)
.addBlocksPage(builder.build())
.addSequencePage(10, 100)
.build();
DriverContext driverContext = createTaskContext(executor, TEST_SESSION, new DataSize(3, MEGABYTE))
.addPipelineContext(0, true, true)
.addDriverContext();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(VARCHAR),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(16, MEGABYTE),
joinCompiler);
toPages(operatorFactory, driverContext, input);
}
@Test(dataProvider = "hashEnabled")
public void testMultiSliceAggregationOutput(boolean hashEnabled)
{
// estimate the number of entries required to create 1.5 pages of results
int fixedWidthSize = SIZE_OF_LONG + SIZE_OF_DOUBLE + SIZE_OF_DOUBLE;
int multiSlicePositionCount = (int) (1.5 * PageBuilderStatus.DEFAULT_MAX_PAGE_SIZE_IN_BYTES / fixedWidthSize);
multiSlicePositionCount = Math.min((int) (1.5 * DEFAULT_MAX_BLOCK_SIZE_IN_BYTES / SIZE_OF_DOUBLE), multiSlicePositionCount);
List<Integer> hashChannels = Ints.asList(1);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, hashChannels, BIGINT, BIGINT);
List<Page> input = rowPagesBuilder
.addSequencePage(multiSlicePositionCount, 0, 0)
.build();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(BIGINT),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty()),
LONG_AVERAGE.bind(ImmutableList.of(1), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(16, MEGABYTE),
joinCompiler);
assertEquals(toPages(operatorFactory, driverContext, input).size(), 2);
}
@Test(dataProvider = "hashEnabledAndMemoryLimitBeforeSpillValues")
public void testMultiplePartialFlushes(boolean hashEnabled, long memoryLimitBeforeSpill, long memoryLimitForMergeWithMemory)
throws Exception
{
List<Integer> hashChannels = Ints.asList(0);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(hashEnabled, hashChannels, BIGINT);
List<Page> input = rowPagesBuilder
.addSequencePage(500, 0)
.addSequencePage(500, 500)
.addSequencePage(500, 1000)
.addSequencePage(500, 1500)
.build();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(BIGINT),
hashChannels,
ImmutableList.of(),
Step.PARTIAL,
false,
ImmutableList.of(LONG_SUM.bind(ImmutableList.of(0), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(1, Unit.KILOBYTE),
memoryLimitBeforeSpill > 0,
succinctBytes(memoryLimitBeforeSpill),
succinctBytes(memoryLimitForMergeWithMemory),
spillerFactory,
joinCompiler);
DriverContext driverContext = createTaskContext(executor, TEST_SESSION, new DataSize(4, Unit.KILOBYTE))
.addPipelineContext(0, true, true)
.addDriverContext();
try (Operator operator = operatorFactory.createOperator(driverContext)) {
List<Page> expectedPages = rowPagesBuilder(BIGINT, BIGINT)
.addSequencePage(2000, 0, 0)
.build();
MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT)
.pages(expectedPages)
.build();
Iterator<Page> inputIterator = input.iterator();
// Fill up the aggregation
while (operator.needsInput() && inputIterator.hasNext()) {
operator.addInput(inputIterator.next());
}
// Drain the output (partial flush)
List<Page> outputPages = new ArrayList<>();
while (true) {
Page output = operator.getOutput();
if (output == null) {
break;
}
outputPages.add(output);
}
// There should be some pages that were drained
assertTrue(!outputPages.isEmpty());
// The operator need input again since this was a partial flush
assertTrue(operator.needsInput());
// Now, drive the operator to completion
outputPages.addAll(toPages(operator, inputIterator));
MaterializedResult actual;
if (hashEnabled) {
// Drop the hashChannel for all pages
List<Page> actualPages = dropChannel(outputPages, ImmutableList.of(1));
List<Type> expectedTypes = without(operator.getTypes(), ImmutableList.of(1));
actual = toMaterializedResult(operator.getOperatorContext().getSession(), expectedTypes, actualPages);
}
else {
actual = toMaterializedResult(operator.getOperatorContext().getSession(), operator.getTypes(), outputPages);
}
assertEquals(actual.getTypes(), expected.getTypes());
assertEqualsIgnoreOrder(actual.getMaterializedRows(), expected.getMaterializedRows());
}
}
@Test
public void testMergeWithMemorySpill()
{
List<Integer> hashChannels = Ints.asList(0);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(BIGINT);
int smallPagesSpillThresholdSize = 150000;
List<Page> input = rowPagesBuilder
.addSequencePage(smallPagesSpillThresholdSize, 0)
.addSequencePage(10, smallPagesSpillThresholdSize)
.build();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(BIGINT),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
false,
ImmutableList.of(LONG_SUM.bind(ImmutableList.of(0), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
1,
new DataSize(16, MEGABYTE),
true,
new DataSize(smallPagesSpillThresholdSize, Unit.BYTE),
succinctBytes(Integer.MAX_VALUE),
spillerFactory,
joinCompiler);
DriverContext driverContext = createTaskContext(executor, TEST_SESSION, new DataSize(1, Unit.KILOBYTE))
.addPipelineContext(0, true, true)
.addDriverContext();
MaterializedResult.Builder resultBuilder = resultBuilder(driverContext.getSession(), BIGINT);
for (int i = 0; i < smallPagesSpillThresholdSize + 10; ++i) {
resultBuilder.row((long) i, (long) i);
}
assertOperatorEqualsIgnoreOrder(operatorFactory, driverContext, input, resultBuilder.build(), false, Optional.of(hashChannels.size()));
}
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = ".* Failed to spill")
public void testSpillerFailure()
{
MetadataManager metadata = MetadataManager.createTestMetadataManager();
InternalAggregationFunction maxVarcharColumn = metadata.getFunctionRegistry().getAggregateFunctionImplementation(
new Signature("max", AGGREGATE, parseTypeSignature(StandardTypes.VARCHAR), parseTypeSignature(StandardTypes.VARCHAR)));
List<Integer> hashChannels = Ints.asList(1);
RowPagesBuilder rowPagesBuilder = rowPagesBuilder(false, hashChannels, VARCHAR, BIGINT, VARCHAR, BIGINT);
List<Page> input = rowPagesBuilder
.addSequencePage(10, 100, 0, 100, 0)
.addSequencePage(10, 100, 0, 200, 0)
.addSequencePage(10, 100, 0, 300, 0)
.build();
DriverContext driverContext = createTaskContext(executor, TEST_SESSION, new DataSize(10, Unit.BYTE))
.addPipelineContext(0, true, true)
.addDriverContext();
HashAggregationOperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
ImmutableList.of(BIGINT),
hashChannels,
ImmutableList.of(),
Step.SINGLE,
false,
ImmutableList.of(COUNT.bind(ImmutableList.of(0), Optional.empty()),
LONG_SUM.bind(ImmutableList.of(3), Optional.empty()),
LONG_AVERAGE.bind(ImmutableList.of(3), Optional.empty()),
maxVarcharColumn.bind(ImmutableList.of(2), Optional.empty())),
rowPagesBuilder.getHashChannel(),
Optional.empty(),
100_000,
new DataSize(16, MEGABYTE),
true,
succinctBytes(8),
succinctBytes(Integer.MAX_VALUE),
new FailingSpillerFactory(),
joinCompiler);
toPages(operatorFactory, driverContext, input);
}
private static class DummySpillerFactory
implements SpillerFactory
{
@Override
public Spiller create(List<Type> types, SpillContext spillContext, AggregatedMemoryContext memoryContext)
{
return new Spiller()
{
private final List<Iterator<Page>> spills = new ArrayList<>();
@Override
public ListenableFuture<?> spill(Iterator<Page> pageIterator)
{
spills.add(pageIterator);
return immediateFuture(null);
}
@Override
public List<Iterator<Page>> getSpills()
{
return spills;
}
@Override
public void close()
{
}
};
}
}
private static class FailingSpillerFactory
implements SpillerFactory
{
@Override
public Spiller create(List<Type> types, SpillContext spillContext, AggregatedMemoryContext memoryContext)
{
return new Spiller()
{
@Override
public ListenableFuture<?> spill(Iterator<Page> pageIterator)
{
return immediateFailedFuture(new IOException("Failed to spill"));
}
@Override
public List<Iterator<Page>> getSpills()
{
return ImmutableList.of();
}
@Override
public void close()
{
}
};
}
}
}
| Always revoke memory in TestHashAggregationOperator
| presto-main/src/test/java/com/facebook/presto/operator/TestHashAggregationOperator.java | Always revoke memory in TestHashAggregationOperator |
|
Java | apache-2.0 | 872959ded738aa2db3b419a0fea081454cfa1e5e | 0 | repeats/Repeat,hptruong93/Repeat,repeats/Repeat,repeats/Repeat,hptruong93/Repeat,repeats/Repeat | package frontEnd;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;
import org.jnativehook.GlobalScreen;
import staticResources.BootStrapResources;
import utilities.DateUtility;
import utilities.ExceptableFunction;
import utilities.FileUtility;
import utilities.Function;
import utilities.NumberUtility;
import utilities.OSIdentifier;
import utilities.Pair;
import utilities.swing.KeyChainInputPanel;
import utilities.swing.SwingUtil;
import core.config.Config;
import core.controller.Core;
import core.ipc.IPCServiceManager;
import core.ipc.IPCServiceName;
import core.ipc.repeatClient.PythonIPCClientService;
import core.ipc.repeatServer.processors.TaskProcessorManager;
import core.keyChain.GlobalKeysManager;
import core.keyChain.KeyChain;
import core.languageHandler.Language;
import core.languageHandler.compiler.AbstractNativeCompiler;
import core.languageHandler.compiler.DynamicCompilerOutput;
import core.languageHandler.compiler.PythonRemoteCompiler;
import core.languageHandler.sourceGenerator.AbstractSourceGenerator;
import core.recorder.Recorder;
import core.userDefinedTask.TaskGroup;
import core.userDefinedTask.TaskSourceManager;
import core.userDefinedTask.UserDefinedAction;
public class MainBackEndHolder {
private static final Logger LOGGER = Logger.getLogger(MainBackEndHolder.class.getName());
protected ScheduledThreadPoolExecutor executor;
protected Thread compiledExecutor;
protected Recorder recorder;
protected UserDefinedAction customFunction;
protected final List<TaskGroup> taskGroups;
private TaskGroup currentGroup;
protected int selectedTaskIndex;
protected final GlobalKeysManager keysManager;
protected final Config config;
protected final UserDefinedAction switchRecord, switchReplay, switchReplayCompiled;
protected boolean isRecording, isReplaying, isRunning;
protected final MainFrame main;
public MainBackEndHolder(MainFrame main) {
this.main = main;
config = new Config(this);
executor = new ScheduledThreadPoolExecutor(5);
keysManager = new GlobalKeysManager(config);
recorder = new Recorder(keysManager);
taskGroups = new ArrayList<>();
selectedTaskIndex = -1;
switchRecord = new UserDefinedAction() {
@Override
public void action(Core controller) throws InterruptedException {
switchRecord();
}
};
switchReplay = new UserDefinedAction() {
@Override
public void action(Core controller) throws InterruptedException {
switchReplay();
}
};
switchReplayCompiled = new UserDefinedAction() {
@Override
public void action(Core controller) throws InterruptedException {
switchRunningCompiledAction();
}
};
TaskProcessorManager.setProcessorIdentifyCallback(new Function<Language, Void>(){
@Override
public Void apply(Language language) {
for (TaskGroup group : taskGroups) {
List<UserDefinedAction> tasks = group.getTasks();
for (int i = 0; i < tasks.size(); i++) {
UserDefinedAction task = tasks.get(i);
if (task.getCompiler() != language) {
continue;
}
AbstractNativeCompiler compiler = config.getCompilerFactory().getCompiler(task.getCompiler());
UserDefinedAction recompiled = task.recompile(compiler, false);
if (recompiled == null) {
continue;
}
tasks.set(i, recompiled);
if (recompiled.isEnabled()) {
if (keysManager.isTaskRegistered(recompiled).isEmpty()) {
keysManager.registerTask(recompiled);
}
}
}
}
renderTasks();
return null;
}
});
}
/*************************************************************************************************************/
/************************************************Config*******************************************************/
protected void loadConfig(File file) {
config.loadConfig(file);
File pythonExecutable = ((PythonRemoteCompiler) (config.getCompilerFactory()).getCompiler(Language.PYTHON)).getPath();
((PythonIPCClientService)IPCServiceManager.getIPCService(IPCServiceName.PYTHON)).setExecutingProgram(pythonExecutable);
applyDebugLevel();
renderSettings();
}
/*************************************************************************************************************/
/************************************************IPC**********************************************************/
protected void initiateBackEndActivities() {
executor.scheduleWithFixedDelay(new Runnable(){
@Override
public void run() {
final Point p = Core.getInstance().mouse().getPosition();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main.tfMousePosition.setText(p.x + ", " + p.y);
}
});
}
}, 0, 500, TimeUnit.MILLISECONDS);
executor.scheduleWithFixedDelay(new Runnable(){
@Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
long time = 0;
for (TaskGroup group : taskGroups) {
for (UserDefinedAction action : group.getTasks()) {
time += action.getStatistics().getTotalExecutionTime();
}
}
main.lSecondsSaved.setText((time/1000f) + "");
renderTasks();
}
});
}
}, 0, 1500, TimeUnit.MILLISECONDS);
try {
IPCServiceManager.initiateServices();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Unable to launch ipcs.", e);
}
}
protected void stopBackEndActivities() {
try {
IPCServiceManager.stopServices();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Unable to stop ipcs.", e);
}
}
protected void exit() {
stopBackEndActivities();
if (!writeConfigFile()) {
JOptionPane.showMessageDialog(main, "Error saving configuration file.");
System.exit(2);
}
System.exit(0);
}
/*************************************************************************************************************/
/****************************************Main hotkeys*********************************************************/
protected void configureMainHotkeys() {
keysManager.reRegisterTask(switchRecord, Arrays.asList(config.getRECORD()));
keysManager.reRegisterTask(switchReplay, Arrays.asList(config.getREPLAY()));
keysManager.reRegisterTask(switchReplayCompiled, Arrays.asList(config.getCOMPILED_REPLAY()));
}
/*************************************************************************************************************/
/****************************************Record and replay****************************************************/
protected void switchRecord() {
if (!isRecording) {//Start record
recorder.clear();
recorder.record();
isRecording = true;
main.bRecord.setIcon(BootStrapResources.STOP);
setEnableReplay(false);
} else {//Stop record
recorder.stopRecord();
isRecording = false;
main.bRecord.setIcon(BootStrapResources.RECORD);
setEnableReplay(true);
}
}
protected void switchReplay() {
if (isReplaying) {
isReplaying = false;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main.bReplay.setIcon(BootStrapResources.PLAY);
setEnableRecord(true);
}
});
recorder.stopReplay();
} else {
isReplaying = true;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main.bReplay.setIcon(BootStrapResources.STOP);
setEnableRecord(false);
}
});
String repeatText = main.tfRepeatCount.getText();
String delayText = main.tfRepeatDelay.getText();
if (NumberUtility.isPositiveInteger(repeatText) && NumberUtility.isNonNegativeInteger(delayText)) {
long repeatCount = Long.parseLong(repeatText);
long delay = Long.parseLong(delayText);
recorder.replay(repeatCount, delay, new Function<Void, Void>() {
@Override
public Void apply(Void r) {
switchReplay();
return null;
}
}, 5, false);
}
}
}
protected void switchRunningCompiledAction() {
if (isRunning) {
isRunning = false;
if (compiledExecutor != null) {
if (compiledExecutor != Thread.currentThread()) {
while (compiledExecutor.isAlive()) {
compiledExecutor.interrupt();
}
}
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main.bRun.setText("Run Compiled Action");
}
});
} else {
if (customFunction == null) {
JOptionPane.showMessageDialog(main, "No compiled action in memory");
return;
}
isRunning = true;
compiledExecutor = new Thread(new Runnable() {
@Override
public void run() {
try {
customFunction.setExecuteTaskInGroup(new ExceptableFunction<Integer, Void, InterruptedException> () {
@Override
public Void apply(Integer d) throws InterruptedException {
if (currentGroup == null) {
LOGGER.warning("Task group is null. Cannot execute given task with index " + d);
return null;
}
List<UserDefinedAction> tasks = currentGroup.getTasks();
if (d >= 0 && d < tasks.size()) {
currentGroup.getTasks().get(d).action(Core.getInstance());
} else {
LOGGER.warning("Index out of bound. Cannot execute given task with index " + d + " given task group only has " + tasks.size() + " elements.");
}
return null;
}
});
customFunction.action(Core.getInstance());
} catch (InterruptedException e) {//Stopped prematurely
return;
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception caught while executing custom function", e);
}
switchRunningCompiledAction();
}
});
compiledExecutor.start();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main.bRun.setText("Stop running");
}
});
}
}
/*************************************************************************************************************/
/*****************************************Task group related**************************************************/
protected void renderTaskGroup() {
main.taskGroup.renderTaskGroup();
for (TaskGroup group : taskGroups) {
if (!group.isEnabled()) {
continue;
}
for (UserDefinedAction task : group.getTasks()) {
Set<KeyChain> collisions = keysManager.areKeysRegistered(task.getHotkeys());
if (task.isEnabled() && (collisions.isEmpty())) {
keysManager.registerTask(task);
}
}
}
}
/*************************************************************************************************************/
/*****************************************Task related********************************************************/
private void removeTask(UserDefinedAction task) {
keysManager.unregisterTask(task);
if (!TaskSourceManager.removeTask(task)) {
JOptionPane.showMessageDialog(main, "Encountered error removing source file " + task.getSourcePath());
}
}
protected void addCurrentTask() {
if (customFunction != null) {
customFunction.setName("New task");
currentGroup.getTasks().add(customFunction);
customFunction = null;
renderTasks();
} else {
JOptionPane.showMessageDialog(main, "Nothing to add. Compile first?");
}
int selectedRow = main.tTasks.getSelectedRow();
selectedTaskIndex = selectedRow;
}
protected void removeCurrentTask() {
int selectedRow = main.tTasks.getSelectedRow();
selectedTaskIndex = selectedRow;
if (selectedRow >= 0 && selectedRow < currentGroup.getTasks().size()) {
UserDefinedAction selectedTask = currentGroup.getTasks().get(selectedRow);
removeTask(selectedTask);
currentGroup.getTasks().remove(selectedRow);
selectedTaskIndex = - 1; //Reset selected index
renderTasks();
} else {
JOptionPane.showMessageDialog(main, "Select a row from the table to remove");
}
}
protected void moveTaskUp() {
int selected = main.tTasks.getSelectedRow();
if (selected >= 1) {
Collections.swap(currentGroup.getTasks(), selected, selected - 1);
main.tTasks.setRowSelectionInterval(selected - 1, selected - 1);
renderTasks();
}
}
protected void moveTaskDown() {
int selected = main.tTasks.getSelectedRow();
if (selected >= 0 && selected < currentGroup.getTasks().size() - 1) {
Collections.swap(currentGroup.getTasks(), selected, selected + 1);
main.tTasks.setRowSelectionInterval(selected + 1, selected + 1);
renderTasks();
}
}
protected void changeTaskGroup() {
int selected = main.tTasks.getSelectedRow();
if (selected >= 0 && selected < currentGroup.getTasks().size()) {
int newGroupIndex = SwingUtil.OptionPaneUtil.getSelection("Select new group",
new Function<TaskGroup, String>() {
@Override
public String apply(TaskGroup d) {
return d.getName();
}
}.map(taskGroups).toArray(new String[taskGroups.size()]), -1);
if (newGroupIndex < 0) {
return;
}
TaskGroup destination = taskGroups.get(newGroupIndex);
if (destination == currentGroup) {
JOptionPane.showMessageDialog(main, "Cannot move to the same group...");
return;
}
if (currentGroup.isEnabled() ^ destination.isEnabled()) {
JOptionPane.showMessageDialog(main, "Two groups must be both enabled or disabled to move...");
return;
}
UserDefinedAction toMove = currentGroup.getTasks().remove(selected);
destination.getTasks().add(toMove);
renderTasks();
}
}
protected void overrideTask() {
int selected = main.tTasks.getSelectedRow();
if (selected >= 0) {
if (customFunction == null) {
JOptionPane.showMessageDialog(main, "Nothing to override. Compile first?");
return;
}
UserDefinedAction toRemove = currentGroup.getTasks().get(selected);
customFunction.override(toRemove);
removeTask(toRemove);
keysManager.registerTask(customFunction);
currentGroup.getTasks().set(selected, customFunction);
LOGGER.info("Successfully overridden task " + customFunction.getName());
} else {
JOptionPane.showMessageDialog(main, "Select a task to override");
}
}
protected void changeHotkeyTask(int row) {
final UserDefinedAction action = currentGroup.getTasks().get(row);
Set<KeyChain> newKeyChains = KeyChainInputPanel.getInputKeyChains(main, action.getHotkeys());
if (newKeyChains == null) {
return;
}
Set<KeyChain> collisions = keysManager.areKeysRegistered(newKeyChains);
if (!collisions.isEmpty()) {
GlobalKeysManager.showCollisionWarning(main, collisions);
return;
}
keysManager.reRegisterTask(action, newKeyChains);
KeyChain representative = action.getRepresentativeHotkey();
main.tTasks.setValueAt(representative.getKeys().isEmpty() ? "None" : representative.toString(), row, MainFrame.TTASK_COLUMN_TASK_HOTKEY);
}
protected void switchEnableTask(int row) {
final UserDefinedAction action = currentGroup.getTasks().get(row);
if (!action.isEnabled()) {
action.setEnabled(!action.isEnabled());
keysManager.unregisterTask(action);
} else {
Set<KeyChain> collisions = keysManager.areKeysRegistered(action.getHotkeys());
if (!collisions.isEmpty()) {
GlobalKeysManager.showCollisionWarning(main, collisions);
return;
}
action.setEnabled(!action.isEnabled());
keysManager.registerTask(action);
}
main.tTasks.setValueAt(action.isEnabled(), row, MainFrame.TTASK_COLUMN_ENABLED);
}
protected void renderTasks() {
main.bTaskGroup.setText(currentGroup.getName());
SwingUtil.TableUtil.setRowNumber(main.tTasks, currentGroup.getTasks().size());
SwingUtil.TableUtil.clearTable(main.tTasks);
int row = 0;
for (UserDefinedAction task : currentGroup.getTasks()) {
main.tTasks.setValueAt(task.getName(), row, MainFrame.TTASK_COLUMN_TASK_NAME);
KeyChain representative = task.getRepresentativeHotkey();
if (representative != null && !representative.getKeys().isEmpty()) {
main.tTasks.setValueAt(representative.toString(), row, MainFrame.TTASK_COLUMN_TASK_HOTKEY);
} else {
main.tTasks.setValueAt("None", row, MainFrame.TTASK_COLUMN_TASK_HOTKEY);
}
main.tTasks.setValueAt(task.isEnabled(), row, MainFrame.TTASK_COLUMN_ENABLED);
main.tTasks.setValueAt(task.getStatistics().getCount(), row, MainFrame.TTASK_COLUMN_USE_COUNT);
main.tTasks.setValueAt(DateUtility.calendarToDateString(task.getStatistics().getLastUse()), row, MainFrame.TTASK_COLUMN_LAST_USE);
row++;
}
}
protected void keyReleaseTaskTable(KeyEvent e) {
int row = main.tTasks.getSelectedRow();
int column = main.tTasks.getSelectedColumn();
if (column == MainFrame.TTASK_COLUMN_TASK_NAME && row >= 0) {
currentGroup.getTasks().get(row).setName(SwingUtil.TableUtil.getStringValueTable(main.tTasks, row, column));
} else if (column == MainFrame.TTASK_COLUMN_TASK_HOTKEY && row >= 0) {
if (e.getKeyCode() == Config.HALT_TASK) {
final UserDefinedAction action = currentGroup.getTasks().get(row);
keysManager.unregisterTask(action);
action.getHotkeys().clear();
main.tTasks.setValueAt("None", row, column);
} else {
changeHotkeyTask(row);
}
} else if (column == MainFrame.TTASK_COLUMN_ENABLED && row >= 0) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
switchEnableTask(row);
}
}
loadSource(row);
selectedTaskIndex = row;
}
protected void mouseReleaseTaskTable(MouseEvent e) {
int row = main.tTasks.getSelectedRow();
int column = main.tTasks.getSelectedColumn();
if (column == MainFrame.TTASK_COLUMN_TASK_HOTKEY && row >= 0) {
changeHotkeyTask(row);
} else if (column == MainFrame.TTASK_COLUMN_ENABLED && row >= 0) {
switchEnableTask(row);
}
loadSource(row);
selectedTaskIndex = row;
}
private void loadSource(int row) {
//Load source if possible
if (row < 0 || row >= currentGroup.getTasks().size()) {
return;
}
if (selectedTaskIndex == row) {
return;
}
UserDefinedAction task = currentGroup.getTasks().get(row);
String source = task.getSource();
if (source == null) {
JOptionPane.showMessageDialog(main, "Cannot retrieve source code for task " + task.getName() + ".\nTry recompiling and add again");
return;
}
if (!task.getCompiler().equals(getCompiler().getName())) {
main.languageSelection.get(task.getCompiler()).setSelected(true);
}
main.taSource.setText(source);
}
/*************************************************************************************************************/
/********************************************Source code related**********************************************/
protected void promptSource() {
StringBuffer sb = new StringBuffer();
sb.append(AbstractSourceGenerator.getReferenceSource(getSelectedLanguage()));
main.taSource.setText(sb.toString());
}
protected void generateSource() {
main.taSource.setText(recorder.getGeneratedCode(getSelectedLanguage()));
}
protected void cleanUnusedSource() {
List<File> files = FileUtility.walk(FileUtility.joinPath("data", "source"));
Set<String> allNames = new HashSet<>(new Function<File, String>() {
@Override
public String apply(File file) {
return file.getAbsolutePath();
}
}.map(files));
Set<String> using = new HashSet<>();
for (TaskGroup group : taskGroups) {
using.addAll(new Function<UserDefinedAction, String>() {
@Override
public String apply(UserDefinedAction task) {
return new File(task.getSourcePath()).getAbsolutePath();
}
}.map(group.getTasks()));
}
allNames.removeAll(using);
if (allNames.size() == 0) {
JOptionPane.showMessageDialog(main, "Nothing to clean...");
return;
}
String[] titles = new String[allNames.size()];
Arrays.fill(titles, "Deleting");
int confirmDelete = SwingUtil.OptionPaneUtil.confirmValues("Delete these files?", titles, allNames.toArray(new String[0]));
if (confirmDelete == JOptionPane.OK_OPTION) {
int count = 0, failed = 0;
for (String name : allNames) {
if (FileUtility.removeFile(new File(name))) {
count++;
} else {
failed++;
}
}
JOptionPane.showMessageDialog(main, "Successfully cleaned " + count + " files.\n Failed to clean " + failed + " files.");
}
}
/*************************************************************************************************************/
/***************************************Source compilation****************************************************/
protected Language getSelectedLanguage() {
for (JRadioButtonMenuItem rbmi : main.rbmiSelection.keySet()) {
if (rbmi.isSelected()) {
return main.rbmiSelection.get(rbmi);
}
}
throw new IllegalStateException("Undefined state. No language selected.");
}
protected AbstractNativeCompiler getCompiler() {
return config.getCompilerFactory().getCompiler(getSelectedLanguage());
}
protected void refreshCompilingLanguage() {
customFunction = null;
getCompiler().changeCompilationButton(main.bCompile);
promptSource();
}
protected void changeCompilerPath() {
getCompiler().promptChangePath(main);
}
protected void compileSource() {
String source = main.taSource.getText();
AbstractNativeCompiler compiler = getCompiler();
Pair<DynamicCompilerOutput, UserDefinedAction> compilationResult = compiler.compile(source);
DynamicCompilerOutput compilerStatus = compilationResult.getA();
UserDefinedAction createdInstance = compilationResult.getB();
if (compilerStatus != DynamicCompilerOutput.COMPILATION_SUCCESS) {
return;
}
customFunction = createdInstance;
customFunction.setCompiler(compiler.getName());
if (!TaskSourceManager.submitTask(customFunction, source)) {
JOptionPane.showMessageDialog(main, "Error writing source file...");
}
}
/*************************************************************************************************************/
/***************************************Configurations********************************************************/
//Write configuration file
protected boolean writeConfigFile() {
return config.writeConfig();
}
private final Level[] DEBUG_LEVELS = {Level.SEVERE, Level.WARNING, Level.INFO, Level.FINE};
protected void applyDebugLevel() {
Level debugLevel = config.getNativeHookDebugLevel();
final JRadioButtonMenuItem[] buttons = {main.rbmiDebugSevere, main.rbmiDebugWarning, main.rbmiDebugInfo, main.rbmiDebugFine};
for (int i = 0; i < DEBUG_LEVELS.length; i++) {
if (debugLevel == DEBUG_LEVELS[i]) {
buttons[i].setSelected(true);
break;
}
}
}
protected void changeDebugLevel() {
Level debugLevel = Level.WARNING;
final JRadioButtonMenuItem[] buttons = {main.rbmiDebugSevere, main.rbmiDebugWarning, main.rbmiDebugInfo, main.rbmiDebugFine};
for (int i = 0; i < DEBUG_LEVELS.length; i++) {
if (buttons[i].isSelected()) {
debugLevel = DEBUG_LEVELS[i];
break;
}
}
config.setNativeHookDebugLevel(debugLevel);
// Get the logger for "org.jnativehook" and set the level to appropriate level.
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(config.getNativeHookDebugLevel());
}
protected void renderSettings() {
if (!OSIdentifier.IS_WINDOWS) {
main.rbmiCompileCS.setEnabled(false);
}
main.cbmiUseTrayIcon.setSelected(config.isUseTrayIcon());
main.cbmiHaltByKey.setSelected(config.isEnabledHaltingKeyPressed());
}
protected void switchTrayIconUse() {
boolean trayIconEnabled = main.cbmiUseTrayIcon.isSelected();
config.setUseTrayIcon(trayIconEnabled);
}
protected void haltAllTasks() {
keysManager.haltAllTasks();
}
protected void switchHaltByKey() {
config.setEnabledHaltingKeyPressed(main.cbmiHaltByKey.isSelected());
}
/*************************************************************************************************************/
private void setEnableRecord(boolean state) {
main.bRecord.setEnabled(state);
}
private void setEnableReplay(boolean state) {
main.bReplay.setEnabled(state);
main.tfRepeatCount.setEnabled(state);
main.tfRepeatDelay.setEnabled(state);
if (state) {
main.tfRepeatCount.setText("1");
main.tfRepeatDelay.setText("0");
}
}
/*************************************************************************************************************/
/***************************************JFrame operations*****************************************************/
protected void focusMainFrame() {
if (main.taskGroup.isVisible()) {
main.taskGroup.setVisible(false);
}
if (main.hotkey.isVisible()) {
main.hotkey.setVisible(false);
}
if (main.ipcs.isVisible()) {
main.ipcs.setVisible(false);
}
}
/*************************************************************************************************************/
public List<TaskGroup> getTaskGroups() {
return taskGroups;
}
protected TaskGroup getCurrentTaskGroup() {
return this.currentGroup;
}
public void setCurrentTaskGroup(TaskGroup currentTaskGroup) {
if (currentTaskGroup != this.currentGroup) {
this.selectedTaskIndex = -1;
this.currentGroup = currentTaskGroup;
keysManager.setCurrentTaskGroup(currentTaskGroup);
}
}
}
| src/frontEnd/MainBackEndHolder.java | package frontEnd;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;
import org.jnativehook.GlobalScreen;
import staticResources.BootStrapResources;
import utilities.DateUtility;
import utilities.ExceptableFunction;
import utilities.FileUtility;
import utilities.Function;
import utilities.NumberUtility;
import utilities.OSIdentifier;
import utilities.Pair;
import utilities.swing.KeyChainInputPanel;
import utilities.swing.SwingUtil;
import core.config.Config;
import core.controller.Core;
import core.ipc.IPCServiceManager;
import core.ipc.IPCServiceName;
import core.ipc.repeatClient.PythonIPCClientService;
import core.ipc.repeatServer.processors.TaskProcessorManager;
import core.keyChain.GlobalKeysManager;
import core.keyChain.KeyChain;
import core.languageHandler.Language;
import core.languageHandler.compiler.AbstractNativeCompiler;
import core.languageHandler.compiler.DynamicCompilerOutput;
import core.languageHandler.compiler.PythonRemoteCompiler;
import core.languageHandler.sourceGenerator.AbstractSourceGenerator;
import core.recorder.Recorder;
import core.userDefinedTask.TaskGroup;
import core.userDefinedTask.TaskSourceManager;
import core.userDefinedTask.UserDefinedAction;
public class MainBackEndHolder {
private static final Logger LOGGER = Logger.getLogger(MainBackEndHolder.class.getName());
protected ScheduledThreadPoolExecutor executor;
protected Thread compiledExecutor;
protected Recorder recorder;
protected UserDefinedAction customFunction;
protected final List<TaskGroup> taskGroups;
private TaskGroup currentGroup;
protected int selectedTaskIndex;
protected final GlobalKeysManager keysManager;
protected final Config config;
protected final UserDefinedAction switchRecord, switchReplay, switchReplayCompiled;
protected boolean isRecording, isReplaying, isRunning;
protected final MainFrame main;
public MainBackEndHolder(MainFrame main) {
this.main = main;
config = new Config(this);
executor = new ScheduledThreadPoolExecutor(5);
keysManager = new GlobalKeysManager(config);
recorder = new Recorder(keysManager);
taskGroups = new ArrayList<>();
selectedTaskIndex = -1;
switchRecord = new UserDefinedAction() {
@Override
public void action(Core controller) throws InterruptedException {
switchRecord();
}
};
switchReplay = new UserDefinedAction() {
@Override
public void action(Core controller) throws InterruptedException {
switchReplay();
}
};
switchReplayCompiled = new UserDefinedAction() {
@Override
public void action(Core controller) throws InterruptedException {
switchRunningCompiledAction();
}
};
TaskProcessorManager.setProcessorIdentifyCallback(new Function<Language, Void>(){
@Override
public Void apply(Language language) {
for (TaskGroup group : taskGroups) {
List<UserDefinedAction> tasks = group.getTasks();
for (int i = 0; i < tasks.size(); i++) {
UserDefinedAction task = tasks.get(i);
if (task.getCompiler() != language) {
continue;
}
AbstractNativeCompiler compiler = config.getCompilerFactory().getCompiler(task.getCompiler());
UserDefinedAction recompiled = task.recompile(compiler, false);
if (recompiled == null) {
continue;
}
tasks.set(i, recompiled);
if (recompiled.isEnabled()) {
if (keysManager.isTaskRegistered(recompiled).isEmpty()) {
keysManager.registerTask(recompiled);
}
}
}
}
renderTasks();
return null;
}
});
}
/*************************************************************************************************************/
/************************************************Config*******************************************************/
protected void loadConfig(File file) {
config.loadConfig(file);
File pythonExecutable = ((PythonRemoteCompiler) (config.getCompilerFactory()).getCompiler(Language.PYTHON)).getPath();
((PythonIPCClientService)IPCServiceManager.getIPCService(IPCServiceName.PYTHON)).setExecutingProgram(pythonExecutable);
applyDebugLevel();
renderSettings();
}
/*************************************************************************************************************/
/************************************************IPC**********************************************************/
protected void initiateBackEndActivities() {
executor.scheduleWithFixedDelay(new Runnable(){
@Override
public void run() {
final Point p = Core.getInstance().mouse().getPosition();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main.tfMousePosition.setText(p.x + ", " + p.y);
}
});
}
}, 0, 500, TimeUnit.MILLISECONDS);
executor.scheduleWithFixedDelay(new Runnable(){
@Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
long time = 0;
for (TaskGroup group : taskGroups) {
for (UserDefinedAction action : group.getTasks()) {
time += action.getStatistics().getTotalExecutionTime();
}
}
main.lSecondsSaved.setText((time/1000f) + "");
renderTasks();
}
});
}
}, 0, 1500, TimeUnit.MILLISECONDS);
try {
IPCServiceManager.initiateServices();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Unable to launch ipcs.", e);
}
}
protected void stopBackEndActivities() {
try {
IPCServiceManager.stopServices();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Unable to stop ipcs.", e);
}
}
protected void exit() {
stopBackEndActivities();
if (!writeConfigFile()) {
JOptionPane.showMessageDialog(main, "Error saving configuration file.");
System.exit(2);
}
System.exit(0);
}
/*************************************************************************************************************/
/****************************************Main hotkeys*********************************************************/
protected void configureMainHotkeys() {
keysManager.reRegisterTask(switchRecord, Arrays.asList(config.getRECORD()));
keysManager.reRegisterTask(switchReplay, Arrays.asList(config.getREPLAY()));
keysManager.reRegisterTask(switchReplayCompiled, Arrays.asList(config.getCOMPILED_REPLAY()));
}
/*************************************************************************************************************/
/****************************************Record and replay****************************************************/
protected void switchRecord() {
if (!isRecording) {//Start record
recorder.clear();
recorder.record();
isRecording = true;
main.bRecord.setIcon(BootStrapResources.STOP);
setEnableReplay(false);
} else {//Stop record
recorder.stopRecord();
isRecording = false;
main.bRecord.setIcon(BootStrapResources.RECORD);
setEnableReplay(true);
}
}
protected void switchReplay() {
if (isReplaying) {
isReplaying = false;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main.bReplay.setIcon(BootStrapResources.PLAY);
setEnableRecord(true);
}
});
recorder.stopReplay();
} else {
isReplaying = true;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main.bReplay.setIcon(BootStrapResources.STOP);
setEnableRecord(false);
}
});
String repeatText = main.tfRepeatCount.getText();
String delayText = main.tfRepeatDelay.getText();
if (NumberUtility.isPositiveInteger(repeatText) && NumberUtility.isNonNegativeInteger(delayText)) {
long repeatCount = Long.parseLong(repeatText);
long delay = Long.parseLong(delayText);
recorder.replay(repeatCount, delay, new Function<Void, Void>() {
@Override
public Void apply(Void r) {
switchReplay();
return null;
}
}, 5, false);
}
}
}
protected void switchRunningCompiledAction() {
if (isRunning) {
isRunning = false;
if (compiledExecutor != null) {
if (compiledExecutor != Thread.currentThread()) {
while (compiledExecutor.isAlive()) {
compiledExecutor.interrupt();
}
}
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main.bRun.setText("Run Compiled Action");
}
});
} else {
if (customFunction == null) {
JOptionPane.showMessageDialog(main, "No compiled action in memory");
return;
}
isRunning = true;
compiledExecutor = new Thread(new Runnable() {
@Override
public void run() {
try {
customFunction.setExecuteTaskInGroup(new ExceptableFunction<Integer, Void, InterruptedException> () {
@Override
public Void apply(Integer d) throws InterruptedException {
if (currentGroup == null) {
LOGGER.warning("Task group is null. Cannot execute given task with index " + d);
return null;
}
List<UserDefinedAction> tasks = currentGroup.getTasks();
if (d >= 0 && d < tasks.size()) {
currentGroup.getTasks().get(d).action(Core.getInstance());
} else {
LOGGER.warning("Index out of bound. Cannot execute given task with index " + d + " given task group only has " + tasks.size() + " elements.");
}
return null;
}
});
customFunction.action(Core.getInstance());
} catch (InterruptedException e) {//Stopped prematurely
return;
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception caught while executing custom function", e);
}
switchRunningCompiledAction();
}
});
compiledExecutor.start();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main.bRun.setText("Stop running");
}
});
}
}
/*************************************************************************************************************/
/*****************************************Task group related**************************************************/
protected void renderTaskGroup() {
main.taskGroup.renderTaskGroup();
for (TaskGroup group : taskGroups) {
if (!group.isEnabled()) {
continue;
}
for (UserDefinedAction task : group.getTasks()) {
Set<KeyChain> collisions = keysManager.areKeysRegistered(task.getHotkeys());
if (task.isEnabled() && (collisions.isEmpty())) {
keysManager.registerTask(task);
}
}
}
}
/*************************************************************************************************************/
/*****************************************Task related********************************************************/
private void removeTask(UserDefinedAction task) {
keysManager.unregisterTask(task);
if (!TaskSourceManager.removeTask(task)) {
JOptionPane.showMessageDialog(main, "Encountered error removing source file " + task.getSourcePath());
}
}
protected void addCurrentTask() {
if (customFunction != null) {
customFunction.setName("New task");
currentGroup.getTasks().add(customFunction);
customFunction = null;
renderTasks();
} else {
JOptionPane.showMessageDialog(main, "Nothing to add. Compile first?");
}
int selectedRow = main.tTasks.getSelectedRow();
selectedTaskIndex = selectedRow;
}
protected void removeCurrentTask() {
int selectedRow = main.tTasks.getSelectedRow();
selectedTaskIndex = selectedRow;
if (selectedRow >= 0 && selectedRow < currentGroup.getTasks().size()) {
UserDefinedAction selectedTask = currentGroup.getTasks().get(selectedRow);
removeTask(selectedTask);
currentGroup.getTasks().remove(selectedRow);
selectedTaskIndex = - 1; //Reset selected index
renderTasks();
} else {
JOptionPane.showMessageDialog(main, "Select a row from the table to remove");
}
}
protected void moveTaskUp() {
int selected = main.tTasks.getSelectedRow();
if (selected >= 1) {
Collections.swap(currentGroup.getTasks(), selected, selected - 1);
main.tTasks.setRowSelectionInterval(selected - 1, selected - 1);
renderTasks();
}
}
protected void moveTaskDown() {
int selected = main.tTasks.getSelectedRow();
if (selected >= 0 && selected < currentGroup.getTasks().size() - 1) {
Collections.swap(currentGroup.getTasks(), selected, selected + 1);
main.tTasks.setRowSelectionInterval(selected + 1, selected + 1);
renderTasks();
}
}
protected void changeTaskGroup() {
int selected = main.tTasks.getSelectedRow();
if (selected >= 0 && selected < currentGroup.getTasks().size()) {
int newGroupIndex = SwingUtil.OptionPaneUtil.getSelection("Select new group",
new Function<TaskGroup, String>() {
@Override
public String apply(TaskGroup d) {
return d.getName();
}
}.map(taskGroups).toArray(new String[taskGroups.size()]), -1);
if (newGroupIndex < 0) {
return;
}
TaskGroup destination = taskGroups.get(newGroupIndex);
if (destination == currentGroup) {
JOptionPane.showMessageDialog(main, "Cannot move to the same group...");
return;
}
if (!(currentGroup.isEnabled() ^ destination.isEnabled())) {
JOptionPane.showMessageDialog(main, "Two groups must be both enabled or disabled to move...");
return;
}
UserDefinedAction toMove = currentGroup.getTasks().remove(selected);
destination.getTasks().add(toMove);
renderTasks();
}
}
protected void overrideTask() {
int selected = main.tTasks.getSelectedRow();
if (selected >= 0) {
if (customFunction == null) {
JOptionPane.showMessageDialog(main, "Nothing to override. Compile first?");
return;
}
UserDefinedAction toRemove = currentGroup.getTasks().get(selected);
customFunction.override(toRemove);
removeTask(toRemove);
keysManager.registerTask(customFunction);
currentGroup.getTasks().set(selected, customFunction);
LOGGER.info("Successfully overridden task " + customFunction.getName());
} else {
JOptionPane.showMessageDialog(main, "Select a task to override");
}
}
protected void changeHotkeyTask(int row) {
final UserDefinedAction action = currentGroup.getTasks().get(row);
Set<KeyChain> newKeyChains = KeyChainInputPanel.getInputKeyChains(main, action.getHotkeys());
if (newKeyChains == null) {
return;
}
Set<KeyChain> collisions = keysManager.areKeysRegistered(newKeyChains);
if (!collisions.isEmpty()) {
GlobalKeysManager.showCollisionWarning(main, collisions);
return;
}
keysManager.reRegisterTask(action, newKeyChains);
KeyChain representative = action.getRepresentativeHotkey();
main.tTasks.setValueAt(representative.getKeys().isEmpty() ? "None" : representative.toString(), row, MainFrame.TTASK_COLUMN_TASK_HOTKEY);
}
protected void switchEnableTask(int row) {
final UserDefinedAction action = currentGroup.getTasks().get(row);
if (!action.isEnabled()) {
action.setEnabled(!action.isEnabled());
keysManager.unregisterTask(action);
} else {
Set<KeyChain> collisions = keysManager.areKeysRegistered(action.getHotkeys());
if (!collisions.isEmpty()) {
GlobalKeysManager.showCollisionWarning(main, collisions);
return;
}
action.setEnabled(!action.isEnabled());
keysManager.registerTask(action);
}
main.tTasks.setValueAt(action.isEnabled(), row, MainFrame.TTASK_COLUMN_ENABLED);
}
protected void renderTasks() {
main.bTaskGroup.setText(currentGroup.getName());
SwingUtil.TableUtil.setRowNumber(main.tTasks, currentGroup.getTasks().size());
SwingUtil.TableUtil.clearTable(main.tTasks);
int row = 0;
for (UserDefinedAction task : currentGroup.getTasks()) {
main.tTasks.setValueAt(task.getName(), row, MainFrame.TTASK_COLUMN_TASK_NAME);
KeyChain representative = task.getRepresentativeHotkey();
if (representative != null && !representative.getKeys().isEmpty()) {
main.tTasks.setValueAt(representative.toString(), row, MainFrame.TTASK_COLUMN_TASK_HOTKEY);
} else {
main.tTasks.setValueAt("None", row, MainFrame.TTASK_COLUMN_TASK_HOTKEY);
}
main.tTasks.setValueAt(task.isEnabled(), row, MainFrame.TTASK_COLUMN_ENABLED);
main.tTasks.setValueAt(task.getStatistics().getCount(), row, MainFrame.TTASK_COLUMN_USE_COUNT);
main.tTasks.setValueAt(DateUtility.calendarToDateString(task.getStatistics().getLastUse()), row, MainFrame.TTASK_COLUMN_LAST_USE);
row++;
}
}
protected void keyReleaseTaskTable(KeyEvent e) {
int row = main.tTasks.getSelectedRow();
int column = main.tTasks.getSelectedColumn();
if (column == MainFrame.TTASK_COLUMN_TASK_NAME && row >= 0) {
currentGroup.getTasks().get(row).setName(SwingUtil.TableUtil.getStringValueTable(main.tTasks, row, column));
} else if (column == MainFrame.TTASK_COLUMN_TASK_HOTKEY && row >= 0) {
if (e.getKeyCode() == Config.HALT_TASK) {
final UserDefinedAction action = currentGroup.getTasks().get(row);
keysManager.unregisterTask(action);
action.getHotkeys().clear();
main.tTasks.setValueAt("None", row, column);
} else {
changeHotkeyTask(row);
}
} else if (column == MainFrame.TTASK_COLUMN_ENABLED && row >= 0) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
switchEnableTask(row);
}
}
loadSource(row);
selectedTaskIndex = row;
}
protected void mouseReleaseTaskTable(MouseEvent e) {
int row = main.tTasks.getSelectedRow();
int column = main.tTasks.getSelectedColumn();
if (column == MainFrame.TTASK_COLUMN_TASK_HOTKEY && row >= 0) {
changeHotkeyTask(row);
} else if (column == MainFrame.TTASK_COLUMN_ENABLED && row >= 0) {
switchEnableTask(row);
}
loadSource(row);
selectedTaskIndex = row;
}
private void loadSource(int row) {
//Load source if possible
if (row < 0 || row >= currentGroup.getTasks().size()) {
return;
}
if (selectedTaskIndex == row) {
return;
}
UserDefinedAction task = currentGroup.getTasks().get(row);
String source = task.getSource();
if (source == null) {
JOptionPane.showMessageDialog(main, "Cannot retrieve source code for task " + task.getName() + ".\nTry recompiling and add again");
return;
}
if (!task.getCompiler().equals(getCompiler().getName())) {
main.languageSelection.get(task.getCompiler()).setSelected(true);
}
main.taSource.setText(source);
}
/*************************************************************************************************************/
/********************************************Source code related**********************************************/
protected void promptSource() {
StringBuffer sb = new StringBuffer();
sb.append(AbstractSourceGenerator.getReferenceSource(getSelectedLanguage()));
main.taSource.setText(sb.toString());
}
protected void generateSource() {
main.taSource.setText(recorder.getGeneratedCode(getSelectedLanguage()));
}
protected void cleanUnusedSource() {
List<File> files = FileUtility.walk(FileUtility.joinPath("data", "source"));
Set<String> allNames = new HashSet<>(new Function<File, String>() {
@Override
public String apply(File file) {
return file.getAbsolutePath();
}
}.map(files));
Set<String> using = new HashSet<>();
for (TaskGroup group : taskGroups) {
using.addAll(new Function<UserDefinedAction, String>() {
@Override
public String apply(UserDefinedAction task) {
return new File(task.getSourcePath()).getAbsolutePath();
}
}.map(group.getTasks()));
}
allNames.removeAll(using);
if (allNames.size() == 0) {
JOptionPane.showMessageDialog(main, "Nothing to clean...");
return;
}
String[] titles = new String[allNames.size()];
Arrays.fill(titles, "Deleting");
int confirmDelete = SwingUtil.OptionPaneUtil.confirmValues("Delete these files?", titles, allNames.toArray(new String[0]));
if (confirmDelete == JOptionPane.OK_OPTION) {
int count = 0, failed = 0;
for (String name : allNames) {
if (FileUtility.removeFile(new File(name))) {
count++;
} else {
failed++;
}
}
JOptionPane.showMessageDialog(main, "Successfully cleaned " + count + " files.\n Failed to clean " + failed + " files.");
}
}
/*************************************************************************************************************/
/***************************************Source compilation****************************************************/
protected Language getSelectedLanguage() {
for (JRadioButtonMenuItem rbmi : main.rbmiSelection.keySet()) {
if (rbmi.isSelected()) {
return main.rbmiSelection.get(rbmi);
}
}
throw new IllegalStateException("Undefined state. No language selected.");
}
protected AbstractNativeCompiler getCompiler() {
return config.getCompilerFactory().getCompiler(getSelectedLanguage());
}
protected void refreshCompilingLanguage() {
customFunction = null;
getCompiler().changeCompilationButton(main.bCompile);
promptSource();
}
protected void changeCompilerPath() {
getCompiler().promptChangePath(main);
}
protected void compileSource() {
String source = main.taSource.getText();
AbstractNativeCompiler compiler = getCompiler();
Pair<DynamicCompilerOutput, UserDefinedAction> compilationResult = compiler.compile(source);
DynamicCompilerOutput compilerStatus = compilationResult.getA();
UserDefinedAction createdInstance = compilationResult.getB();
if (compilerStatus != DynamicCompilerOutput.COMPILATION_SUCCESS) {
return;
}
customFunction = createdInstance;
customFunction.setCompiler(compiler.getName());
if (!TaskSourceManager.submitTask(customFunction, source)) {
JOptionPane.showMessageDialog(main, "Error writing source file...");
}
}
/*************************************************************************************************************/
/***************************************Configurations********************************************************/
//Write configuration file
protected boolean writeConfigFile() {
return config.writeConfig();
}
private final Level[] DEBUG_LEVELS = {Level.SEVERE, Level.WARNING, Level.INFO, Level.FINE};
protected void applyDebugLevel() {
Level debugLevel = config.getNativeHookDebugLevel();
final JRadioButtonMenuItem[] buttons = {main.rbmiDebugSevere, main.rbmiDebugWarning, main.rbmiDebugInfo, main.rbmiDebugFine};
for (int i = 0; i < DEBUG_LEVELS.length; i++) {
if (debugLevel == DEBUG_LEVELS[i]) {
buttons[i].setSelected(true);
break;
}
}
}
protected void changeDebugLevel() {
Level debugLevel = Level.WARNING;
final JRadioButtonMenuItem[] buttons = {main.rbmiDebugSevere, main.rbmiDebugWarning, main.rbmiDebugInfo, main.rbmiDebugFine};
for (int i = 0; i < DEBUG_LEVELS.length; i++) {
if (buttons[i].isSelected()) {
debugLevel = DEBUG_LEVELS[i];
break;
}
}
config.setNativeHookDebugLevel(debugLevel);
// Get the logger for "org.jnativehook" and set the level to appropriate level.
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(config.getNativeHookDebugLevel());
}
protected void renderSettings() {
if (!OSIdentifier.IS_WINDOWS) {
main.rbmiCompileCS.setEnabled(false);
}
main.cbmiUseTrayIcon.setSelected(config.isUseTrayIcon());
main.cbmiHaltByKey.setSelected(config.isEnabledHaltingKeyPressed());
}
protected void switchTrayIconUse() {
boolean trayIconEnabled = main.cbmiUseTrayIcon.isSelected();
config.setUseTrayIcon(trayIconEnabled);
}
protected void haltAllTasks() {
keysManager.haltAllTasks();
}
protected void switchHaltByKey() {
config.setEnabledHaltingKeyPressed(main.cbmiHaltByKey.isSelected());
}
/*************************************************************************************************************/
private void setEnableRecord(boolean state) {
main.bRecord.setEnabled(state);
}
private void setEnableReplay(boolean state) {
main.bReplay.setEnabled(state);
main.tfRepeatCount.setEnabled(state);
main.tfRepeatDelay.setEnabled(state);
if (state) {
main.tfRepeatCount.setText("1");
main.tfRepeatDelay.setText("0");
}
}
/*************************************************************************************************************/
/***************************************JFrame operations*****************************************************/
protected void focusMainFrame() {
if (main.taskGroup.isVisible()) {
main.taskGroup.setVisible(false);
}
if (main.hotkey.isVisible()) {
main.hotkey.setVisible(false);
}
if (main.ipcs.isVisible()) {
main.ipcs.setVisible(false);
}
}
/*************************************************************************************************************/
public List<TaskGroup> getTaskGroups() {
return taskGroups;
}
protected TaskGroup getCurrentTaskGroup() {
return this.currentGroup;
}
public void setCurrentTaskGroup(TaskGroup currentTaskGroup) {
if (currentTaskGroup != this.currentGroup) {
this.selectedTaskIndex = -1;
this.currentGroup = currentTaskGroup;
keysManager.setCurrentTaskGroup(currentTaskGroup);
}
}
} | Fix slight logic in moving task between groups | src/frontEnd/MainBackEndHolder.java | Fix slight logic in moving task between groups |
|
Java | apache-2.0 | 8d61a03f0a0043813de73e33a1fb1dafe477d83f | 0 | mohanaraosv/commons-digester,callMeDimit/commons-digester,mohanaraosv/commons-digester,apache/commons-digester,mohanaraosv/commons-digester,callMeDimit/commons-digester,apache/commons-digester,callMeDimit/commons-digester,apache/commons-digester | package org.apache.commons.digester3.binder;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import static java.lang.String.format;
import java.util.Arrays;
import org.apache.commons.digester3.ObjectCreateRule;
/**
* Builder chained when invoking {@link LinkedRuleBuilder#createObject()}.
*
* @since 3.0
*/
public final class ObjectCreateBuilder
extends AbstractBackToLinkedRuleBuilder<ObjectCreateRule>
{
private final ClassLoader classLoader;
private Class<?> type;
private String attributeName;
/**
* The constructor argument types
*
* @since 3.2
*/
private Class<?>[] constructorArgumentsType;
/**
* Default constructor arguments.
*
* @since 3.2
*/
private Object[] defaultConstructorArguments;
ObjectCreateBuilder( String keyPattern, String namespaceURI, RulesBinder mainBinder, LinkedRuleBuilder mainBuilder,
ClassLoader classLoader )
{
super( keyPattern, namespaceURI, mainBinder, mainBuilder );
this.classLoader = classLoader;
}
/**
* Construct an object with the specified class name.
*
* @param className Java class name of the object to be created
* @return this builder instance
*/
public ObjectCreateBuilder ofType( String className )
{
if ( className == null )
{
reportError( "createObject().ofType( String )", "NULL Java type not allowed" );
return this;
}
try
{
return ofType( this.classLoader.loadClass( className ) );
}
catch ( ClassNotFoundException e )
{
reportError( "createObject().ofType( String )", String.format( "class '%s' cannot be load", className ) );
return this;
}
}
/**
* Construct an object with the specified class.
*
* @param <T> any java type
* @param type Java class of the object to be created
* @return this builder instance
*/
public <T> ObjectCreateBuilder ofType( Class<T> type )
{
if ( type == null )
{
reportError( "createObject().ofType( Class<?> )", "NULL Java type not allowed" );
return this;
}
this.type = type;
return this;
}
/**
* Allows specify the attribute containing an override class name if it is present.
*
* @param attributeName The attribute containing an override class name if it is present
* @return this builder instance
*/
public ObjectCreateBuilder ofTypeSpecifiedByAttribute( /* @Nullable */String attributeName )
{
this.attributeName = attributeName;
return this;
}
/**
* Allows users to specify constructor argument type names.
*
* @return this builder instance
* @since 3.2
*/
public ObjectCreateBuilder usingConstructor( String...paramTypeNames )
{
if ( paramTypeNames == null )
{
reportError( "createObject().usingConstructor( String[] )", "NULL parametersTypes not allowed" );
return this;
}
Class<?>[] paramTypes = new Class<?>[paramTypeNames.length];
for ( int i = 0; i < paramTypeNames.length; i++ )
{
try
{
paramTypes[i] = classLoader.loadClass( paramTypeNames[i] );
}
catch ( ClassNotFoundException e )
{
this.reportError( format( "createObject().usingConstructor( %s )",
Arrays.toString( paramTypeNames ) ),
format( "class '%s' cannot be loaded", paramTypeNames[i] ) );
}
}
return usingConstructor( paramTypes );
}
/**
* Allows users to specify constructor argument types.
*
* @return this builder instance
* @since 3.2
*/
public ObjectCreateBuilder usingConstructor( Class<?>... constructorArgumentTypes )
{
if ( constructorArgumentTypes == null )
{
reportError( "createObject().usingConstructor( Class<?>[] )", "NULL constructorArgumentTypes not allowed" );
return this;
}
this.constructorArgumentsType = constructorArgumentTypes;
return this;
}
/**
* Allows users to specify default constructor arguments.
*
* @param defaultConstructorArguments
* @return the default constructor arguments.
* @since 3.2
*/
public ObjectCreateBuilder usingDefaultConstructorArguments( Object... defaultConstructorArguments)
{
if ( defaultConstructorArguments == null )
{
reportError( "createObject().usingDefaultConstructorArguments( Object[] )", "NULL defaultConstructorArguments not allowed" );
return this;
}
this.defaultConstructorArguments = defaultConstructorArguments;
return this;
}
/**
* {@inheritDoc}
*/
@Override
protected ObjectCreateRule createRule()
{
ObjectCreateRule objectCreateRule = new ObjectCreateRule( attributeName, type );
if ( constructorArgumentsType != null )
{
objectCreateRule.setConstructorArgumentTypes( constructorArgumentsType );
}
if ( defaultConstructorArguments != null )
{
objectCreateRule.setDefaultConstructorArguments( defaultConstructorArguments );
}
return objectCreateRule;
}
}
| src/main/java/org/apache/commons/digester3/binder/ObjectCreateBuilder.java | package org.apache.commons.digester3.binder;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import static java.lang.String.format;
import java.util.Arrays;
import org.apache.commons.digester3.ObjectCreateRule;
/**
* Builder chained when invoking {@link LinkedRuleBuilder#createObject()}.
*
* @since 3.0
*/
public final class ObjectCreateBuilder
extends AbstractBackToLinkedRuleBuilder<ObjectCreateRule>
{
private final ClassLoader classLoader;
private Class<?> type;
private String attributeName;
/**
* The constructor argument types
*
* @since 3.2
*/
private Class<?>[] constructorArgumentsType;
/**
* Default constructor arguments.
*
* @since 3.2
*/
private Object[] defaultConstructorArguments;
ObjectCreateBuilder( String keyPattern, String namespaceURI, RulesBinder mainBinder, LinkedRuleBuilder mainBuilder,
ClassLoader classLoader )
{
super( keyPattern, namespaceURI, mainBinder, mainBuilder );
this.classLoader = classLoader;
}
/**
* Construct an object with the specified class name.
*
* @param className Java class name of the object to be created
* @return this builder instance
*/
public ObjectCreateBuilder ofType( String className )
{
if ( className == null )
{
reportError( "createObject().ofType( String )", "NULL Java type not allowed" );
return this;
}
try
{
return ofType( this.classLoader.loadClass( className ) );
}
catch ( ClassNotFoundException e )
{
reportError( "createObject().ofType( String )", String.format( "class '%s' cannot be load", className ) );
return this;
}
}
/**
* Construct an object with the specified class.
*
* @param <T> any java type
* @param type Java class of the object to be created
* @return this builder instance
*/
public <T> ObjectCreateBuilder ofType( Class<T> type )
{
if ( type == null )
{
reportError( "createObject().ofType( Class<?> )", "NULL Java type not allowed" );
return this;
}
this.type = type;
return this;
}
/**
* Allows specify the attribute containing an override class name if it is present.
*
* @param attributeName The attribute containing an override class name if it is present
* @return this builder instance
*/
public ObjectCreateBuilder ofTypeSpecifiedByAttribute( /* @Nullable */String attributeName )
{
this.attributeName = attributeName;
return this;
}
/**
*
* @return
* @since 3.2
*/
public ObjectCreateBuilder usingConstructor( String...paramTypeNames )
{
if ( paramTypeNames == null )
{
reportError( "createObject().usingConstructor( String[] )", "NULL parametersTypes not allowed" );
return this;
}
Class<?>[] paramTypes = new Class<?>[paramTypeNames.length];
for ( int i = 0; i < paramTypeNames.length; i++ )
{
try
{
paramTypes[i] = classLoader.loadClass( paramTypeNames[i] );
}
catch ( ClassNotFoundException e )
{
this.reportError( format( "createObject().usingConstructor( %s )",
Arrays.toString( paramTypeNames ) ),
format( "class '%s' cannot be loaded", paramTypeNames[i] ) );
}
}
return usingConstructor( paramTypes );
}
/**
*
* @return
* @since 3.2
*/
public ObjectCreateBuilder usingConstructor( Class<?>... constructorArgumentTypes )
{
if ( constructorArgumentTypes == null )
{
reportError( "createObject().usingConstructor( Class<?>[] )", "NULL constructorArgumentTypes not allowed" );
return this;
}
this.constructorArgumentsType = constructorArgumentTypes;
return this;
}
public ObjectCreateBuilder usingDefaultConstructorArguments( Object... defaultConstructorArguments)
{
if ( defaultConstructorArguments == null )
{
reportError( "createObject().usingDefaultConstructorArguments( Object[] )", "NULL defaultConstructorArguments not allowed" );
return this;
}
this.defaultConstructorArguments = defaultConstructorArguments;
return this;
}
/**
* {@inheritDoc}
*/
@Override
protected ObjectCreateRule createRule()
{
ObjectCreateRule objectCreateRule = new ObjectCreateRule( attributeName, type );
if ( constructorArgumentsType != null )
{
objectCreateRule.setConstructorArgumentTypes( constructorArgumentsType );
}
if ( defaultConstructorArguments != null )
{
objectCreateRule.setDefaultConstructorArguments( defaultConstructorArguments );
}
return objectCreateRule;
}
}
| added missing javadoc
git-svn-id: 871f264856ddff118359d15337bbbf32ea57c748@1212055 13f79535-47bb-0310-9956-ffa450edef68
| src/main/java/org/apache/commons/digester3/binder/ObjectCreateBuilder.java | added missing javadoc |
|
Java | apache-2.0 | eba0daff24c90560afe3bca3cf88de1a4d811573 | 0 | ShortStickBoy/ActionBox | package com.sunzn.action.box.library;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
/**
* Created by sunzn on 2017/2/16.
*/
public abstract class ActionBox implements DialogInterface.OnDismissListener {
private int mResource;
private View mRootView;
private Context mContext;
private Dialog mActionBox;
private float mDimAmount = 0.5F;
private boolean mCancelable = true;
private boolean mCanceledOnTouch = true;
public ActionBox(Context context, int resource) {
this.mContext = context;
this.mResource = resource;
}
public ActionBox create() {
mRootView = LayoutInflater.from(mContext).inflate(mResource, null);
mActionBox = new Dialog(mContext, R.style.Theme_ActionBox);
mActionBox.setCanceledOnTouchOutside(getCanceledOnTouch());
mActionBox.setCancelable(getCancelable());
mActionBox.setOnDismissListener(this);
mActionBox.setContentView(mRootView);
Window window = mActionBox.getWindow();
if (window != null) {
window.setGravity(Gravity.BOTTOM);
window.setDimAmount(getDimAmount());
WindowManager.LayoutParams params = window.getAttributes();
params.x = 0;
params.y = 0;
params.width = ScreenUtils.getScreenWidth(mContext);
window.setAttributes(params);
}
onActionBoxCreated();
return this;
}
public void onShow() {
// TODO
}
public void onFade() {
// TODO
}
public <T> void onShow(T t) {
// TODO
}
public <T> void onFade(T t) {
// TODO
}
public void show() {
if (mActionBox != null && !mActionBox.isShowing()) {
mActionBox.show();
onShow();
}
}
public void fade() {
if (mActionBox != null && mActionBox.isShowing()) {
mActionBox.dismiss();
onFade();
}
}
public <T> void show(T t) {
if (mActionBox != null && !mActionBox.isShowing()) {
mActionBox.show();
onShow(t);
}
}
public <T> void fade(T t) {
if (mActionBox != null && mActionBox.isShowing()) {
mActionBox.dismiss();
onFade(t);
}
}
public void postDelayShow(long millis) {
if (mActionBox != null && !mActionBox.isShowing() && mRootView != null) {
mRootView.postDelayed(new Runnable() {
@Override
public void run() {
show();
}
}, millis);
}
}
public void postDelayFade(long millis) {
if (mActionBox != null && mActionBox.isShowing() && mRootView != null) {
mRootView.postDelayed(new Runnable() {
@Override
public void run() {
fade();
}
}, millis);
}
}
public <T> void postDelayShow(long millis, final T t) {
if (mActionBox != null && !mActionBox.isShowing() && mRootView != null) {
mRootView.postDelayed(new Runnable() {
@Override
public void run() {
show(t);
}
}, millis);
}
}
public <T> void postDelayFade(long millis, final T t) {
if (mActionBox != null && mActionBox.isShowing() && mRootView != null) {
mRootView.postDelayed(new Runnable() {
@Override
public void run() {
fade(t);
}
}, millis);
}
}
public abstract void onActionBoxCreated();
private float getDimAmount() {
return this.mDimAmount;
}
private boolean getCancelable() {
return this.mCancelable;
}
private boolean getCanceledOnTouch() {
return this.mCanceledOnTouch;
}
public ActionBox setDimAmount(float amount) {
this.mDimAmount = amount;
return this;
}
public ActionBox setCancelable(boolean cancel) {
this.mCancelable = cancel;
return this;
}
public ActionBox setCanceledOnTouch(boolean cancel) {
this.mCanceledOnTouch = cancel;
return this;
}
public Context getContext() {
return mActionBox.getContext();
}
public Dialog getActionBox() {
return mActionBox;
}
protected View findViewById(int id) {
return mRootView == null ? null : mRootView.findViewById(id);
}
@Override
public void onDismiss(DialogInterface dialog) {
// TODO
}
}
| Library/src/main/java/com/sunzn/action/box/library/ActionBox.java | package com.sunzn.action.box.library;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
/**
* Created by sunzn on 2017/2/16.
*/
public abstract class ActionBox implements DialogInterface.OnDismissListener {
private int mResource;
private View mRootView;
private Context mContext;
private Dialog mActionBox;
private boolean mCancelable = true;
private boolean mCanceledOnTouch = true;
public ActionBox(Context context, int resource) {
this.mContext = context;
this.mResource = resource;
}
public ActionBox create() {
mRootView = LayoutInflater.from(mContext).inflate(mResource, null);
mActionBox = new Dialog(mContext, R.style.Theme_ActionBox);
mActionBox.setCanceledOnTouchOutside(getCanceledOnTouch());
mActionBox.setCancelable(getCancelable());
mActionBox.setOnDismissListener(this);
mActionBox.setContentView(mRootView);
Window window = mActionBox.getWindow();
if (window != null) {
window.setGravity(Gravity.BOTTOM);
WindowManager.LayoutParams params = window.getAttributes();
params.x = 0;
params.y = 0;
params.width = ScreenUtils.getScreenWidth(mContext);
window.setAttributes(params);
}
onActionBoxCreated();
return this;
}
public void onShow() {
// TODO
}
public void onFade() {
// TODO
}
public <T> void onShow(T t) {
// TODO
}
public <T> void onFade(T t) {
// TODO
}
public void show() {
if (mActionBox != null && !mActionBox.isShowing()) {
mActionBox.show();
onShow();
}
}
public void fade() {
if (mActionBox != null && mActionBox.isShowing()) {
mActionBox.dismiss();
onFade();
}
}
public <T> void show(T t) {
if (mActionBox != null && !mActionBox.isShowing()) {
mActionBox.show();
onShow(t);
}
}
public <T> void fade(T t) {
if (mActionBox != null && mActionBox.isShowing()) {
mActionBox.dismiss();
onFade(t);
}
}
public void postDelayShow(long millis) {
if (mActionBox != null && !mActionBox.isShowing() && mRootView != null) {
mRootView.postDelayed(new Runnable() {
@Override
public void run() {
show();
}
}, millis);
}
}
public void postDelayFade(long millis) {
if (mActionBox != null && mActionBox.isShowing() && mRootView != null) {
mRootView.postDelayed(new Runnable() {
@Override
public void run() {
fade();
}
}, millis);
}
}
public <T> void postDelayShow(long millis, final T t) {
if (mActionBox != null && !mActionBox.isShowing() && mRootView != null) {
mRootView.postDelayed(new Runnable() {
@Override
public void run() {
show(t);
}
}, millis);
}
}
public <T> void postDelayFade(long millis, final T t) {
if (mActionBox != null && mActionBox.isShowing() && mRootView != null) {
mRootView.postDelayed(new Runnable() {
@Override
public void run() {
fade(t);
}
}, millis);
}
}
public abstract void onActionBoxCreated();
private boolean getCancelable() {
return this.mCancelable;
}
private boolean getCanceledOnTouch() {
return this.mCanceledOnTouch;
}
public ActionBox setCancelable(boolean cancel) {
this.mCancelable = cancel;
return this;
}
public ActionBox setCanceledOnTouch(boolean cancel) {
this.mCanceledOnTouch = cancel;
return this;
}
public Context getContext() {
return mActionBox.getContext();
}
public Dialog getActionBox() {
return mActionBox;
}
protected View findViewById(int id) {
return mRootView == null ? null : mRootView.findViewById(id);
}
@Override
public void onDismiss(DialogInterface dialog) {
// TODO
}
}
| Update ActionBox
| Library/src/main/java/com/sunzn/action/box/library/ActionBox.java | Update ActionBox |
|
Java | apache-2.0 | a89579449dcfa56d171b59e8a7d23da5266b426f | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.actionSystem.impl;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.ide.HelpTooltip;
import com.intellij.ide.impl.DataManagerImpl;
import com.intellij.internal.statistic.collectors.fus.ui.persistence.ToolbarClicksCollector;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionButtonLook;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.actionSystem.ex.CustomComponentAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.keymap.ex.KeymapManagerEx;
import com.intellij.openapi.ui.popup.*;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.JBColor;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.awt.RelativeRectangle;
import com.intellij.ui.paint.LinePainter2D;
import com.intellij.ui.switcher.QuickActionProvider;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.*;
import com.intellij.util.ui.update.Activatable;
import com.intellij.util.ui.update.UiNotifyConnector;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class ActionToolbarImpl extends JPanel implements ActionToolbar, QuickActionProvider {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.actionSystem.impl.ActionToolbarImpl");
private static final List<ActionToolbarImpl> ourToolbars = new LinkedList<>();
private static final String RIGHT_ALIGN_KEY = "RIGHT_ALIGN";
static {
JBUI.addPropertyChangeListener(JBUI.USER_SCALE_FACTOR_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
((JBDimension)ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE).update();
((JBDimension)ActionToolbar.NAVBAR_MINIMUM_BUTTON_SIZE).update();
}
});
}
public static void updateAllToolbarsImmediately() {
for (ActionToolbarImpl toolbar : new ArrayList<>(ourToolbars)) {
toolbar.updateActionsImmediately();
for (Component c : toolbar.getComponents()) {
if (c instanceof ActionButton) {
((ActionButton)c).updateToolTipText();
((ActionButton)c).updateIcon();
}
}
}
}
/**
* This array contains Rectangles which define bounds of the corresponding
* components in the toolbar. This list can be consider as a cache of the
* Rectangle objects that are used in calculation of preferred sizes and
* components layout.
*/
private final List<Rectangle> myComponentBounds = new ArrayList<>();
private JBDimension myMinimumButtonSize = JBUI.emptySize();
/**
* @see ActionToolbar#getLayoutPolicy()
*/
private int myLayoutPolicy;
private int myOrientation;
private final ActionGroup myActionGroup;
private final String myPlace;
protected List<AnAction> myVisibleActions;
private final PresentationFactory myPresentationFactory = new PresentationFactory();
private final boolean myDecorateButtons;
private final ToolbarUpdater myUpdater;
/**
* @see ActionToolbar#adjustTheSameSize(boolean)
*/
private boolean myAdjustTheSameSize;
private final ActionButtonLook myButtonLook = null;
private final ActionButtonLook myMinimalButtonLook = ActionButtonLook.INPLACE_LOOK;
private final DataManager myDataManager;
protected final ActionManagerEx myActionManager;
private Rectangle myAutoPopupRec;
private final DefaultActionGroup mySecondaryActions = new DefaultActionGroup();
private PopupStateModifier mySecondaryButtonPopupStateModifier = null;
private boolean myForceMinimumSize = false;
private boolean myForceShowFirstComponent = false;
private boolean mySkipWindowAdjustments = false;
private boolean myMinimalMode;
private boolean myForceUseMacEnhancements;
public ActionButton getSecondaryActionsButton() {
return mySecondaryActionsButton;
}
private ActionButton mySecondaryActionsButton;
private int myFirstOutsideIndex = -1;
private JBPopup myPopup;
private JComponent myTargetComponent;
private boolean myReservePlaceAutoPopupIcon = true;
private boolean myAddSeparatorFirst;
public ActionToolbarImpl(String place,
@NotNull final ActionGroup actionGroup,
boolean horizontal,
@NotNull DataManager dataManager,
@NotNull ActionManagerEx actionManager,
@NotNull KeymapManagerEx keymapManager) {
this(place, actionGroup, horizontal, false, dataManager, actionManager, keymapManager, false);
}
public ActionToolbarImpl(String place,
@NotNull ActionGroup actionGroup,
boolean horizontal,
boolean decorateButtons,
@NotNull DataManager dataManager,
@NotNull ActionManagerEx actionManager,
@NotNull KeymapManagerEx keymapManager) {
this(place, actionGroup, horizontal, decorateButtons, dataManager, actionManager, keymapManager, false);
}
public ActionToolbarImpl(String place,
@NotNull ActionGroup actionGroup,
final boolean horizontal,
final boolean decorateButtons,
@NotNull DataManager dataManager,
@NotNull ActionManagerEx actionManager,
@NotNull KeymapManagerEx keymapManager,
boolean updateActionsNow) {
super(null);
myActionManager = actionManager;
myPlace = place;
myActionGroup = actionGroup;
myVisibleActions = new ArrayList<>();
myDataManager = dataManager;
myDecorateButtons = decorateButtons;
myUpdater = new ToolbarUpdater(actionManager, keymapManager, this) {
@Override
protected void updateActionsImpl(boolean transparentOnly, boolean forced) {
ActionToolbarImpl.this.updateActionsImpl(transparentOnly, forced);
}
};
setLayout(new BorderLayout());
setOrientation(horizontal ? SwingConstants.HORIZONTAL : SwingConstants.VERTICAL);
mySecondaryActions.getTemplatePresentation().setIcon(AllIcons.General.GearPlain);
mySecondaryActions.setPopup(true);
myUpdater.updateActions(updateActionsNow, false);
// If the panel doesn't handle mouse event then it will be passed to its parent.
// It means that if the panel is in sliding mode then the focus goes to the editor
// and panel will be automatically hidden.
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.COMPONENT_EVENT_MASK | AWTEvent.CONTAINER_EVENT_MASK);
setMiniMode(false);
}
@Override
public void updateUI() {
super.updateUI();
for (Component component : getComponents()) {
tweakActionComponentUI(component);
}
}
public String getPlace() {
return myPlace;
}
@Override
public void addNotify() {
super.addNotify();
ourToolbars.add(this);
// should update action right on the showing, otherwise toolbar may not be displayed at all,
// since by default all updates are postponed until frame gets focused.
updateActionsImmediately();
}
private boolean doMacEnhancementsForMainToolbar() {
return UIUtil.isUnderAquaLookAndFeel() && (ActionPlaces.MAIN_TOOLBAR.equals(myPlace) || myForceUseMacEnhancements);
}
public void setForceUseMacEnhancements(boolean useMacEnhancements) {
myForceUseMacEnhancements = useMacEnhancements;
}
private boolean isInsideNavBar() {
return ActionPlaces.NAVIGATION_BAR_TOOLBAR.equals(myPlace);
}
@Override
public void removeNotify() {
super.removeNotify();
ourToolbars.remove(this);
}
@NotNull
@Override
public JComponent getComponent() {
return this;
}
@Override
public int getLayoutPolicy() {
return myLayoutPolicy;
}
@Override
public void setLayoutPolicy(final int layoutPolicy) {
if (layoutPolicy != NOWRAP_LAYOUT_POLICY && layoutPolicy != WRAP_LAYOUT_POLICY && layoutPolicy != AUTO_LAYOUT_POLICY) {
throw new IllegalArgumentException("wrong layoutPolicy: " + layoutPolicy);
}
myLayoutPolicy = layoutPolicy;
}
@Override
protected Graphics getComponentGraphics(Graphics graphics) {
return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics));
}
@Override
protected void paintComponent(final Graphics g) {
if (doMacEnhancementsForMainToolbar()) {
final Rectangle r = getBounds();
UIUtil.drawGradientHToolbarBackground(g, r.width, r.height);
} else {
super.paintComponent(g);
}
if (myLayoutPolicy == AUTO_LAYOUT_POLICY) {
if (myAutoPopupRec != null) {
if (myOrientation == SwingConstants.HORIZONTAL) {
final int dy = myAutoPopupRec.height / 2 - AllIcons.Ide.Link.getIconHeight() / 2;
AllIcons.Ide.Link.paintIcon(this, g, (int)myAutoPopupRec.getMaxX() - AllIcons.Ide.Link.getIconWidth() - 1, myAutoPopupRec.y + dy);
}
else {
final int dx = myAutoPopupRec.width / 2 - AllIcons.Ide.Link.getIconWidth() / 2;
AllIcons.Ide.Link.paintIcon(this, g, myAutoPopupRec.x + dx, (int)myAutoPopupRec.getMaxY() - AllIcons.Ide.Link.getIconWidth() - 1);
}
}
}
}
public void setSecondaryButtonPopupStateModifier(PopupStateModifier popupStateModifier) {
mySecondaryButtonPopupStateModifier = popupStateModifier;
}
private void fillToolBar(final List<AnAction> actions, boolean layoutSecondaries) {
final List<AnAction> rightAligned = new ArrayList<>();
boolean isLastElementSeparator = false;
if (myAddSeparatorFirst) {
add(new MySeparator());
isLastElementSeparator = true;
}
for (int i = 0; i < actions.size(); i++) {
final AnAction action = actions.get(i);
if (action instanceof RightAlignedToolbarAction) {
rightAligned.add(action);
continue;
}
if (layoutSecondaries) {
if (!myActionGroup.isPrimary(action)) {
mySecondaryActions.add(action);
continue;
}
}
if (action instanceof Separator) {
if (isLastElementSeparator) continue;
if (i > 0 && i < actions.size() - 1) {
add(new MySeparator());
isLastElementSeparator = true;
continue;
}
}
else if (action instanceof CustomComponentAction) {
add(getCustomComponent(action));
}
else {
add(createToolbarButton(action));
}
isLastElementSeparator = false;
}
if (mySecondaryActions.getChildrenCount() > 0) {
mySecondaryActionsButton = new ActionButton(mySecondaryActions, myPresentationFactory.getPresentation(mySecondaryActions), myPlace, getMinimumButtonSize()) {
@Override
@ButtonState
public int getPopState() {
return mySecondaryButtonPopupStateModifier != null && mySecondaryButtonPopupStateModifier.willModify()
? mySecondaryButtonPopupStateModifier.getModifiedPopupState()
: super.getPopState();
}
};
mySecondaryActionsButton.setNoIconsInPopup(true);
add(mySecondaryActionsButton);
}
for (AnAction action : rightAligned) {
JComponent button = action instanceof CustomComponentAction ? getCustomComponent(action) : createToolbarButton(action);
if (!isInsideNavBar()) {
button.putClientProperty(RIGHT_ALIGN_KEY, Boolean.TRUE);
}
add(button);
}
//if ((ActionPlaces.MAIN_TOOLBAR.equals(myPlace) || ActionPlaces.NAVIGATION_BAR_TOOLBAR.equals(myPlace))) {
// final AnAction searchEverywhereAction = ActionManager.getInstance().getAction("SearchEverywhere");
// if (searchEverywhereAction != null) {
// try {
// final CustomComponentAction searchEveryWhereAction = (CustomComponentAction)searchEverywhereAction;
// final JComponent searchEverywhere = searchEveryWhereAction.createCustomComponent(searchEverywhereAction.getTemplatePresentation());
// searchEverywhere.putClientProperty("SEARCH_EVERYWHERE", Boolean.TRUE);
// add(searchEverywhere);
// }
// catch (Exception ignore) {}
// }
//}
}
private JComponent getCustomComponent(AnAction action) {
Presentation presentation = myPresentationFactory.getPresentation(action);
JComponent customComponent = ObjectUtils.tryCast(presentation.getClientProperty(CustomComponentAction.CUSTOM_COMPONENT_PROPERTY), JComponent.class);
if (customComponent == null) {
customComponent = ((CustomComponentAction)action).createCustomComponent(presentation);
presentation.putClientProperty(CustomComponentAction.CUSTOM_COMPONENT_PROPERTY, customComponent);
customComponent.putClientProperty(CustomComponentAction.CUSTOM_COMPONENT_ACTION_PROPERTY, action);
}
tweakActionComponentUI(customComponent);
AbstractButton clickable = UIUtil.findComponentOfType(customComponent, AbstractButton.class);
if (clickable != null) {
class ToolbarClicksCollectorListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {ToolbarClicksCollector.record(action, myPlace);}
}
if (Arrays.stream(clickable.getMouseListeners()).noneMatch(ml -> ml instanceof ToolbarClicksCollectorListener)) {
clickable.addMouseListener(new ToolbarClicksCollectorListener());
}
}
return customComponent;
}
private void tweakActionComponentUI(@NotNull Component actionComponent) {
if (ActionPlaces.EDITOR_TOOLBAR.equals(myPlace)) {
// tweak font & color for editor toolbar to match editor tabs style
actionComponent.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL));
actionComponent.setForeground(ColorUtil.dimmer(JBColor.BLACK));
}
}
private Dimension getMinimumButtonSize() {
return isInsideNavBar() ? NAVBAR_MINIMUM_BUTTON_SIZE : DEFAULT_MINIMUM_BUTTON_SIZE;
}
public ActionButton createToolbarButton(final AnAction action, final ActionButtonLook look, final String place, final Presentation presentation, final Dimension minimumSize) {
if (action.displayTextInToolbar()) {
int mnemonic = KeyEvent.getExtendedKeyCodeForChar(action.getTemplatePresentation().getMnemonic());
ActionButtonWithText buttonWithText = new ActionButtonWithText(action, presentation, place, minimumSize) {
@Override protected HelpTooltip.Alignment getTooltipLocation() {
return tooltipLocation();
}
};
if (mnemonic != KeyEvent.VK_UNDEFINED) {
buttonWithText.registerKeyboardAction(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buttonWithText.click();
}
}, KeyStroke.getKeyStroke(mnemonic,
/*SystemInfo.isMac
? InputEvent.CTRL_DOWN_MASK |
InputEvent.ALT_DOWN_MASK
:*/ InputEvent.ALT_DOWN_MASK), WHEN_IN_FOCUSED_WINDOW);
}
tweakActionComponentUI(buttonWithText);
return buttonWithText;
}
ActionButton actionButton = new ActionButton(action, presentation, place, minimumSize) {
@Override
protected DataContext getDataContext() {
return getToolbarDataContext();
}
@Override
protected HelpTooltip.Alignment getTooltipLocation() {
return tooltipLocation();
}
};
actionButton.setLook(look);
return actionButton;
}
private HelpTooltip.Alignment tooltipLocation() {
return myOrientation == SwingConstants.VERTICAL ? HelpTooltip.Alignment.RIGHT: HelpTooltip.Alignment.BOTTOM;
}
private ActionButton createToolbarButton(final AnAction action) {
return createToolbarButton(
action,
myMinimalMode ? myMinimalButtonLook : myDecorateButtons ? new ActionButtonLook() {
@Override
public void paintBorder(Graphics g, JComponent c, int state) {
g.setColor(JBColor.border());
g.drawLine(c.getWidth()-1, 0, c.getWidth()-1, c.getHeight());
}
@Override
public void paintBackground(Graphics g, JComponent component, int state) {
if (state == ActionButtonComponent.PUSHED) {
g.setColor(component.getBackground().darker());
((Graphics2D)g).fill(g.getClip());
}
}
} : myButtonLook,
myPlace, myPresentationFactory.getPresentation(action),
myMinimumButtonSize.size());
}
@Override
public void doLayout() {
if (!isValid()) {
calculateBounds(getSize(), myComponentBounds);
}
final int componentCount = getComponentCount();
LOG.assertTrue(componentCount <= myComponentBounds.size());
for (int i = componentCount - 1; i >= 0; i--) {
final Component component = getComponent(i);
component.setBounds(myComponentBounds.get(i));
}
}
@Override
public void validate() {
if (!isValid()) {
calculateBounds(getSize(), myComponentBounds);
super.validate();
}
}
private Dimension getChildPreferredSize(int index) {
Component component = getComponent(index);
return component.isVisible() ? component.getPreferredSize() : new Dimension();
}
/**
* @return maximum button width
*/
private int getMaxButtonWidth() {
int width = 0;
for (int i = 0; i < getComponentCount(); i++) {
final Dimension dimension = getChildPreferredSize(i);
width = Math.max(width, dimension.width);
}
return width;
}
/**
* @return maximum button height
*/
@Override
public int getMaxButtonHeight() {
int height = 0;
for (int i = 0; i < getComponentCount(); i++) {
final Dimension dimension = getChildPreferredSize(i);
height = Math.max(height, dimension.height);
}
return height;
}
private void calculateBoundsNowrapImpl(List<Rectangle> bounds) {
final int componentCount = getComponentCount();
LOG.assertTrue(componentCount <= bounds.size());
final int width = getWidth();
final int height = getHeight();
final Insets insets = getInsets();
if (myAdjustTheSameSize) {
final int maxWidth = getMaxButtonWidth();
final int maxHeight = getMaxButtonHeight();
if (myOrientation == SwingConstants.HORIZONTAL) {
int offset = 0;
for (int i = 0; i < componentCount; i++) {
final Rectangle r = bounds.get(i);
r.setBounds(insets.left + offset, insets.top + (height - maxHeight) / 2, maxWidth, maxHeight);
offset += maxWidth;
}
}
else {
int offset = 0;
for (int i = 0; i < componentCount; i++) {
final Rectangle r = bounds.get(i);
r.setBounds(insets.left + (width - maxWidth) / 2, insets.top + offset, maxWidth, maxHeight);
offset += maxHeight;
}
}
}
else {
if (myOrientation == SwingConstants.HORIZONTAL) {
final int maxHeight = getMaxButtonHeight();
int offset = 0;
for (int i = 0; i < componentCount; i++) {
final Dimension d = getChildPreferredSize(i);
final Rectangle r = bounds.get(i);
r.setBounds(insets.left + offset, insets.top + (maxHeight - d.height) / 2, d.width, d.height);
offset += d.width;
}
}
else {
final int maxWidth = getMaxButtonWidth();
int offset = 0;
for (int i = 0; i < componentCount; i++) {
final Dimension d = getChildPreferredSize(i);
final Rectangle r = bounds.get(i);
r.setBounds(insets.left + (maxWidth - d.width) / 2, insets.top + offset, d.width, d.height);
offset += d.height;
}
}
}
}
private void calculateBoundsAutoImp(Dimension sizeToFit, List<Rectangle> bounds) {
final int componentCount = getComponentCount();
LOG.assertTrue(componentCount <= bounds.size());
final boolean actualLayout = bounds == myComponentBounds;
if (actualLayout) {
myAutoPopupRec = null;
}
int autoButtonSize = AllIcons.Ide.Link.getIconWidth();
boolean full = false;
final Insets insets = getInsets();
int widthToFit = sizeToFit.width - insets.left - insets.right;
int heightToFit = sizeToFit.height - insets.top - insets.bottom;
if (myOrientation == SwingConstants.HORIZONTAL) {
int eachX = 0;
int maxHeight = heightToFit;
for (int i = 0; i < componentCount; i++) {
final Component eachComp = getComponent(i);
final boolean isLast = i == componentCount - 1;
final Rectangle eachBound = new Rectangle(getChildPreferredSize(i));
maxHeight = Math.max(eachBound.height, maxHeight);
if (!full) {
boolean inside;
if (isLast) {
inside = eachX + eachBound.width <= widthToFit;
} else {
inside = eachX + eachBound.width + autoButtonSize <= widthToFit;
}
if (inside) {
if (eachComp == mySecondaryActionsButton) {
assert isLast;
if (sizeToFit.width != Integer.MAX_VALUE) {
eachBound.x = sizeToFit.width - insets.right - eachBound.width;
eachX = (int)eachBound.getMaxX() - insets.left;
}
else {
eachBound.x = insets.left + eachX;
}
} else {
eachBound.x = insets.left + eachX;
eachX += eachBound.width;
}
eachBound.y = insets.top;
}
else {
full = true;
}
}
if (full) {
if (myAutoPopupRec == null) {
myAutoPopupRec = new Rectangle(insets.left + eachX, insets.top, widthToFit - eachX, heightToFit);
myFirstOutsideIndex = i;
}
eachBound.x = Integer.MAX_VALUE;
eachBound.y = Integer.MAX_VALUE;
}
bounds.get(i).setBounds(eachBound);
}
for (final Rectangle r : bounds) {
if (r.height < maxHeight) {
r.y += (maxHeight - r.height) / 2;
}
}
}
else {
int eachY = 0;
for (int i = 0; i < componentCount; i++) {
final Rectangle eachBound = new Rectangle(getChildPreferredSize(i));
if (!full) {
boolean outside;
if (i < componentCount - 1) {
outside = eachY + eachBound.height + autoButtonSize < heightToFit;
}
else {
outside = eachY + eachBound.height < heightToFit;
}
if (outside) {
eachBound.x = insets.left;
eachBound.y = insets.top + eachY;
eachY += eachBound.height;
}
else {
full = true;
}
}
if (full) {
if (myAutoPopupRec == null) {
myAutoPopupRec = new Rectangle(insets.left, insets.top + eachY, widthToFit, heightToFit - eachY);
myFirstOutsideIndex = i;
}
eachBound.x = Integer.MAX_VALUE;
eachBound.y = Integer.MAX_VALUE;
}
bounds.get(i).setBounds(eachBound);
}
}
}
private void calculateBoundsWrapImpl(Dimension sizeToFit, List<Rectangle> bounds) {
// We have to graceful handle case when toolbar was not laid out yet.
// In this case we calculate bounds as it is a NOWRAP toolbar.
if (getWidth() == 0 || getHeight() == 0) {
try {
setLayoutPolicy(NOWRAP_LAYOUT_POLICY);
calculateBoundsNowrapImpl(bounds);
}
finally {
setLayoutPolicy(WRAP_LAYOUT_POLICY);
}
return;
}
final int componentCount = getComponentCount();
LOG.assertTrue(componentCount <= bounds.size());
final Insets insets = getInsets();
int widthToFit = sizeToFit.width - insets.left - insets.right;
int heightToFit = sizeToFit.height - insets.top - insets.bottom;
if (myAdjustTheSameSize) {
if (myOrientation == SwingConstants.HORIZONTAL) {
final int maxWidth = getMaxButtonWidth();
final int maxHeight = getMaxButtonHeight();
// Lay components out
int xOffset = 0;
int yOffset = 0;
// Calculate max size of a row. It's not possible to make more than 3 row toolbar
final int maxRowWidth = Math.max(widthToFit, componentCount * maxWidth / 3);
for (int i = 0; i < componentCount; i++) {
if (xOffset + maxWidth > maxRowWidth) { // place component at new row
xOffset = 0;
yOffset += maxHeight;
}
final Rectangle each = bounds.get(i);
each.setBounds(insets.left + xOffset, insets.top + yOffset, maxWidth, maxHeight);
xOffset += maxWidth;
}
}
else {
final int maxWidth = getMaxButtonWidth();
final int maxHeight = getMaxButtonHeight();
// Lay components out
int xOffset = 0;
int yOffset = 0;
// Calculate max size of a row. It's not possible to make more then 3 column toolbar
final int maxRowHeight = Math.max(heightToFit, componentCount * myMinimumButtonSize.height() / 3);
for (int i = 0; i < componentCount; i++) {
if (yOffset + maxHeight > maxRowHeight) { // place component at new row
yOffset = 0;
xOffset += maxWidth;
}
final Rectangle each = bounds.get(i);
each.setBounds(insets.left + xOffset, insets.top + yOffset, maxWidth, maxHeight);
yOffset += maxHeight;
}
}
}
else {
if (myOrientation == SwingConstants.HORIZONTAL) {
// Calculate row height
int rowHeight = 0;
final Dimension[] dims = new Dimension[componentCount]; // we will use this dimensions later
for (int i = 0; i < componentCount; i++) {
dims[i] = getChildPreferredSize(i);
final int height = dims[i].height;
rowHeight = Math.max(rowHeight, height);
}
// Lay components out
int xOffset = 0;
int yOffset = 0;
// Calculate max size of a row. It's not possible to make more then 3 row toolbar
final int maxRowWidth = Math.max(widthToFit, componentCount * myMinimumButtonSize.width() / 3);
for (int i = 0; i < componentCount; i++) {
final Dimension d = dims[i];
if (xOffset + d.width > maxRowWidth) { // place component at new row
xOffset = 0;
yOffset += rowHeight;
}
final Rectangle each = bounds.get(i);
each.setBounds(insets.left + xOffset, insets.top + yOffset + (rowHeight - d.height) / 2, d.width, d.height);
xOffset += d.width;
}
}
else {
// Calculate row width
int rowWidth = 0;
final Dimension[] dims = new Dimension[componentCount]; // we will use this dimensions later
for (int i = 0; i < componentCount; i++) {
dims[i] = getChildPreferredSize(i);
final int width = dims[i].width;
rowWidth = Math.max(rowWidth, width);
}
// Lay components out
int xOffset = 0;
int yOffset = 0;
// Calculate max size of a row. It's not possible to make more then 3 column toolbar
final int maxRowHeight = Math.max(heightToFit, componentCount * myMinimumButtonSize.height() / 3);
for (int i = 0; i < componentCount; i++) {
final Dimension d = dims[i];
if (yOffset + d.height > maxRowHeight) { // place component at new row
yOffset = 0;
xOffset += rowWidth;
}
final Rectangle each = bounds.get(i);
each.setBounds(insets.left + xOffset + (rowWidth - d.width) / 2, insets.top + yOffset, d.width, d.height);
yOffset += d.height;
}
}
}
}
/**
* Calculates bounds of all the components in the toolbar
*/
private void calculateBounds(Dimension size2Fit, List<Rectangle> bounds) {
bounds.clear();
for (int i = 0; i < getComponentCount(); i++) {
bounds.add(new Rectangle());
}
if (myLayoutPolicy == NOWRAP_LAYOUT_POLICY) {
calculateBoundsNowrapImpl(bounds);
}
else if (myLayoutPolicy == WRAP_LAYOUT_POLICY) {
calculateBoundsWrapImpl(size2Fit, bounds);
}
else if (myLayoutPolicy == AUTO_LAYOUT_POLICY) {
calculateBoundsAutoImp(size2Fit, bounds);
}
else {
throw new IllegalStateException("unknown layoutPolicy: " + myLayoutPolicy);
}
if (getComponentCount() > 0 && size2Fit.width < Integer.MAX_VALUE) {
int maxHeight = 0;
for (int i = 0; i < bounds.size() - 2; i++) {
maxHeight = Math.max(maxHeight, bounds.get(i).height);
}
int rightOffset = 0;
Insets insets = getInsets();
for (int i = getComponentCount() - 1, j = 1; i > 0; i--, j++) {
final Component component = getComponent(i);
if (component instanceof JComponent && ((JComponent)component).getClientProperty(RIGHT_ALIGN_KEY) == Boolean.TRUE) {
rightOffset += bounds.get(i).width;
Rectangle r = bounds.get(bounds.size() - j);
r.x = size2Fit.width - rightOffset;
r.y = insets.top + (getHeight() - insets.top - insets.bottom - bounds.get(i).height) / 2;
}
}
}
}
@Override
public Dimension getPreferredSize() {
final ArrayList<Rectangle> bounds = new ArrayList<>();
calculateBounds(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE), bounds);//it doesn't take into account wrapping
if (bounds.isEmpty()) return JBUI.emptySize();
int forcedHeight = 0;
if (getWidth() > 0 && getLayoutPolicy() == ActionToolbar.WRAP_LAYOUT_POLICY && myOrientation == SwingConstants.HORIZONTAL) {
final ArrayList<Rectangle> limitedBounds = new ArrayList<>();
calculateBounds(new Dimension(getWidth(), Integer.MAX_VALUE), limitedBounds);
Rectangle union = null;
for (Rectangle bound : limitedBounds) {
if (union == null) {
union = bound;
} else {
union = union.union(bound);
}
}
forcedHeight = union != null ? union.height : 0;
}
int xLeft = Integer.MAX_VALUE;
int yTop = Integer.MAX_VALUE;
int xRight = Integer.MIN_VALUE;
int yBottom = Integer.MIN_VALUE;
for (int i = bounds.size() - 1; i >= 0; i--) {
final Rectangle each = bounds.get(i);
if (each.x == Integer.MAX_VALUE) continue;
xLeft = Math.min(xLeft, each.x);
yTop = Math.min(yTop, each.y);
xRight = Math.max(xRight, each.x + each.width);
yBottom = Math.max(yBottom, each.y + each.height);
}
final Dimension dimension = new Dimension(xRight - xLeft, Math.max(yBottom - yTop, forcedHeight));
if (myLayoutPolicy == AUTO_LAYOUT_POLICY && myReservePlaceAutoPopupIcon && !isInsideNavBar()) {
if (myOrientation == SwingConstants.HORIZONTAL) {
dimension.width += AllIcons.Ide.Link.getIconWidth();
}
else {
dimension.height += AllIcons.Ide.Link.getIconHeight();
}
}
JBInsets.addTo(dimension, getInsets());
return dimension;
}
public void setForceMinimumSize(boolean force) {
myForceMinimumSize = force;
}
/**
* By default minimum size is to show chevron only.
* If this option is <code>true</code> toolbar shows at least one (the first) component plus chevron (if need)
*/
public void setForceShowFirstComponent(boolean showFirstComponent) {
myForceShowFirstComponent = showFirstComponent;
}
/**
* This option makes sense when you use a toolbar inside JBPopup
* When some 'actions' are hidden under the chevron the popup with extra components would be shown/hidden
* with size adjustments for the main popup (this is default behavior).
* If this option is <code>true</code> size adjustments would be omitted
*/
public void setSkipWindowAdjustments(boolean skipWindowAdjustments) {
mySkipWindowAdjustments = skipWindowAdjustments;
}
@Override
public Dimension getMinimumSize() {
if (myForceMinimumSize) {
return getPreferredSize();
}
if (myLayoutPolicy == AUTO_LAYOUT_POLICY) {
final Insets i = getInsets();
if (myForceShowFirstComponent && getComponentCount() > 0) {
Component c = getComponent(0);
Dimension firstSize = c.getPreferredSize();
if (myOrientation == SwingConstants.HORIZONTAL) {
return new Dimension(firstSize.width + AllIcons.Ide.Link.getIconWidth() + i.left + i.right,
Math.max(firstSize.height, myMinimumButtonSize.height()) + i.top + i.bottom);
}
else {
return new Dimension(Math.max(firstSize.width, AllIcons.Ide.Link.getIconWidth()) + i.left + i.right,
firstSize.height + myMinimumButtonSize.height() + i.top + i.bottom);
}
}
return new Dimension(AllIcons.Ide.Link.getIconWidth() + i.left + i.right, myMinimumButtonSize.height() + i.top + i.bottom);
}
else {
return super.getMinimumSize();
}
}
private static class ToolbarReference extends WeakReference<ActionToolbarImpl> {
private static final ReferenceQueue<ActionToolbarImpl> ourQueue = new ReferenceQueue<>();
private volatile Disposable myDisposable;
ToolbarReference(ActionToolbarImpl toolbar) {
super(toolbar, ourQueue);
processQueue();
}
private static void processQueue() {
while (true) {
ToolbarReference ref = (ToolbarReference)ourQueue.poll();
if (ref == null) break;
ref.disposeReference();
}
}
private void disposeReference() {
Disposable disposable = myDisposable;
if (disposable != null) {
myDisposable = null;
Disposer.dispose(disposable);
}
}
}
private final class MySeparator extends JComponent {
@Override
public Dimension getPreferredSize() {
return (myOrientation == SwingConstants.HORIZONTAL) ? JBUI.size(7, 24) : JBUI.size(24, 7);
}
@Override
protected void paintComponent(final Graphics g) {
int gap = JBUI.scale(2);
int offset = JBUI.scale(3);
if (getParent() != null) {
g.setColor(UIUtil.getSeparatorColor());
if (myOrientation == SwingConstants.HORIZONTAL) {
LinePainter2D.paint((Graphics2D)g, offset, gap, offset, getParent().getSize().height - gap * 2 - offset);
}
else {
LinePainter2D.paint((Graphics2D)g, gap, offset, getParent().getSize().width - gap * 2 - offset, offset);
}
}
}
}
@Override
public void adjustTheSameSize(final boolean value) {
if (myAdjustTheSameSize == value) {
return;
}
myAdjustTheSameSize = value;
revalidate();
}
@Override
public void setMinimumButtonSize(@NotNull final Dimension size) {
myMinimumButtonSize = JBDimension.create(size, true);
for (int i = getComponentCount() - 1; i >= 0; i--) {
final Component component = getComponent(i);
if (component instanceof ActionButton) {
final ActionButton button = (ActionButton)component;
button.setMinimumButtonSize(size);
}
}
revalidate();
}
@Override
public void setOrientation(@MagicConstant(intValues = {SwingConstants.HORIZONTAL, SwingConstants.VERTICAL}) int orientation) {
if (SwingConstants.HORIZONTAL != orientation && SwingConstants.VERTICAL != orientation) {
throw new IllegalArgumentException("wrong orientation: " + orientation);
}
myOrientation = orientation;
}
int getOrientation() {
return myOrientation;
}
@Override
public void updateActionsImmediately() {
ApplicationManager.getApplication().assertIsDispatchThread();
myUpdater.updateActions(true, false);
}
private void updateActionsImpl(boolean transparentOnly, boolean forced) {
List<AnAction> newVisibleActions = ContainerUtil.newArrayListWithCapacity(myVisibleActions.size());
DataContext dataContext = getDataContext();
Utils.expandActionGroup(LaterInvocator.isInModalContext(), myActionGroup, newVisibleActions, myPresentationFactory, dataContext,
myPlace, myActionManager, transparentOnly, false, false, true);
if (forced || !newVisibleActions.equals(myVisibleActions)) {
boolean shouldRebuildUI = newVisibleActions.isEmpty() || myVisibleActions.isEmpty();
myVisibleActions = newVisibleActions;
Dimension oldSize = getPreferredSize();
removeAll();
mySecondaryActions.removeAll();
mySecondaryActionsButton = null;
fillToolBar(myVisibleActions, getLayoutPolicy() == AUTO_LAYOUT_POLICY && myOrientation == SwingConstants.HORIZONTAL);
Dimension newSize = getPreferredSize();
if (!mySkipWindowAdjustments) {
((WindowManagerEx)WindowManager.getInstance()).adjustContainerWindow(this, oldSize, newSize);
}
if (shouldRebuildUI) {
revalidate();
} else {
Container parent = getParent();
if (parent != null) {
parent.invalidate();
parent.validate();
}
}
repaint();
}
}
@Override
public boolean hasVisibleActions() {
return !myVisibleActions.isEmpty();
}
@Override
public void setTargetComponent(final JComponent component) {
myTargetComponent = component;
if (myTargetComponent != null) {
updateWhenFirstShown(myTargetComponent, new ToolbarReference(this));
}
}
private static void updateWhenFirstShown(JComponent targetComponent, final ToolbarReference ref) {
Activatable activatable = new Activatable.Adapter() {
public void showNotify() {
ActionToolbarImpl toolbar = ref.get();
if (toolbar != null) {
toolbar.myUpdater.updateActions(false, false);
}
}
};
ref.myDisposable = new UiNotifyConnector(targetComponent, activatable) {
@Override
protected void showNotify() {
super.showNotify();
ref.disposeReference();
}
};
}
@Override
public DataContext getToolbarDataContext() {
return getDataContext();
}
protected DataContext getDataContext() {
return myTargetComponent != null ? myDataManager.getDataContext(myTargetComponent) : ((DataManagerImpl)myDataManager).getDataContextTest(this);
}
@Override
protected void processMouseMotionEvent(final MouseEvent e) {
super.processMouseMotionEvent(e);
if (getLayoutPolicy() != AUTO_LAYOUT_POLICY) {
return;
}
if (myAutoPopupRec != null && myAutoPopupRec.contains(e.getPoint())) {
IdeFocusManager.getInstance(null).doWhenFocusSettlesDown(() -> showAutoPopup());
}
}
private void showAutoPopup() {
if (isPopupShowing()) return;
final ActionGroup group;
if (myOrientation == SwingConstants.HORIZONTAL) {
group = myActionGroup;
}
else {
final DefaultActionGroup outside = new DefaultActionGroup();
for (int i = myFirstOutsideIndex; i < myVisibleActions.size(); i++) {
outside.add(myVisibleActions.get(i));
}
group = outside;
}
PopupToolbar popupToolbar = new PopupToolbar(myPlace, group, true, myDataManager, myActionManager, myUpdater.getKeymapManager(), this) {
@Override
protected void onOtherActionPerformed() {
hidePopup();
}
@Override
protected DataContext getDataContext() {
return ActionToolbarImpl.this.getDataContext();
}
};
popupToolbar.setLayoutPolicy(NOWRAP_LAYOUT_POLICY);
popupToolbar.updateActionsImmediately();
Point location;
if (myOrientation == SwingConstants.HORIZONTAL) {
location = getLocationOnScreen();
}
else {
location = getLocationOnScreen();
location.y = location.y + getHeight() - popupToolbar.getPreferredSize().height;
}
final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(popupToolbar, null);
builder.setResizable(false)
.setMovable(true) // fit the screen automatically
.setRequestFocus(false)
.setTitle(null)
.setCancelOnClickOutside(true)
.setCancelOnOtherWindowOpen(true)
.setCancelCallback(() -> {
final boolean toClose = myActionManager.isActionPopupStackEmpty();
if (toClose) {
myUpdater.updateActions(false, true);
}
return toClose;
})
.setCancelOnMouseOutCallback(new MouseChecker() {
@Override
public boolean check(final MouseEvent event) {
return myAutoPopupRec != null &&
myActionManager.isActionPopupStackEmpty() &&
!new RelativeRectangle(ActionToolbarImpl.this, myAutoPopupRec).contains(new RelativePoint(event));
}
});
builder.addListener(new JBPopupAdapter() {
@Override
public void onClosed(LightweightWindowEvent event) {
processClosed();
}
});
myPopup = builder.createPopup();
final AnActionListener.Adapter listener = new AnActionListener.Adapter() {
@Override
public void afterActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
final JBPopup popup = myPopup;
if (popup != null && !popup.isDisposed() && popup.isVisible()) {
popup.cancel();
}
}
};
ActionManager.getInstance().addAnActionListener(listener);
Disposer.register(myPopup, popupToolbar);
Disposer.register(popupToolbar, new Disposable() {
@Override
public void dispose() {
ActionManager.getInstance().removeAnActionListener(listener);
}
});
myPopup.showInScreenCoordinates(this, location);
final Window window = SwingUtilities.getWindowAncestor(this);
if (window != null) {
final ComponentAdapter componentAdapter = new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
hidePopup();
}
@Override
public void componentMoved(final ComponentEvent e) {
hidePopup();
}
@Override
public void componentShown(final ComponentEvent e) {
hidePopup();
}
@Override
public void componentHidden(final ComponentEvent e) {
hidePopup();
}
};
window.addComponentListener(componentAdapter);
Disposer.register(popupToolbar, new Disposable() {
@Override
public void dispose() {
window.removeComponentListener(componentAdapter);
}
});
}
}
private boolean isPopupShowing() {
if (myPopup != null) {
if (myPopup.getContent() != null) {
return true;
}
}
return false;
}
private void hidePopup() {
if (myPopup != null) {
myPopup.cancel();
processClosed();
}
}
private void processClosed() {
if (myPopup == null) return;
Disposer.dispose(myPopup);
myPopup = null;
myUpdater.updateActions(false, false);
}
abstract static class PopupToolbar extends ActionToolbarImpl implements AnActionListener, Disposable {
private final JComponent myParent;
public PopupToolbar(final String place,
final ActionGroup actionGroup,
final boolean horizontal,
final DataManager dataManager,
@NotNull ActionManagerEx actionManager,
final KeymapManagerEx keymapManager,
JComponent parent) {
super(place, actionGroup, horizontal, false, dataManager, actionManager, keymapManager, true);
myActionManager.addAnActionListener(this);
myParent = parent;
}
@Override
public Container getParent() {
Container parent = super.getParent();
return parent != null ? parent : myParent;
}
@Override
public void dispose() {
myActionManager.removeAnActionListener(this);
}
@Override
public void beforeActionPerformed(final AnAction action, final DataContext dataContext, AnActionEvent event) {
}
@Override
public void afterActionPerformed(final AnAction action, final DataContext dataContext, AnActionEvent event) {
if (!myVisibleActions.contains(action)) {
onOtherActionPerformed();
}
}
protected abstract void onOtherActionPerformed();
}
@Override
public void setReservePlaceAutoPopupIcon(final boolean reserve) {
myReservePlaceAutoPopupIcon = reserve;
}
@Override
public void setSecondaryActionsTooltip(String secondaryActionsTooltip) {
mySecondaryActions.getTemplatePresentation().setDescription(secondaryActionsTooltip);
}
@Override
public void setSecondaryActionsIcon(Icon icon) {
mySecondaryActions.getTemplatePresentation().setIcon(icon);
}
@NotNull
@Override
public List<AnAction> getActions(boolean originalProvider) {
return getActions();
}
@NotNull
@Override
public List<AnAction> getActions() {
ArrayList<AnAction> result = new ArrayList<>();
ArrayList<AnAction> secondary = new ArrayList<>();
AnAction[] kids = myActionGroup.getChildren(null);
for (AnAction each : kids) {
if (myActionGroup.isPrimary(each)) {
result.add(each);
} else {
secondary.add(each);
}
}
result.add(new Separator());
result.addAll(secondary);
return result;
}
@Override
public void setMiniMode(boolean minimalMode) {
//if (myMinimalMode == minimalMode) return;
myMinimalMode = minimalMode;
if (myMinimalMode) {
setMinimumButtonSize(JBUI.emptySize());
setLayoutPolicy(NOWRAP_LAYOUT_POLICY);
setBorder(JBUI.Borders.empty());
setOpaque(false);
} else {
setBorder(JBUI.Borders.empty(2));
setMinimumButtonSize(myDecorateButtons ? JBUI.size(30, 20) : DEFAULT_MINIMUM_BUTTON_SIZE);
setOpaque(true);
setLayoutPolicy(AUTO_LAYOUT_POLICY);
}
myUpdater.updateActions(false, true);
}
public void setAddSeparatorFirst(boolean addSeparatorFirst) {
myAddSeparatorFirst = addSeparatorFirst;
myUpdater.updateActions(false, true);
}
@TestOnly
public Presentation getPresentation(AnAction action) {
return myPresentationFactory.getPresentation(action);
}
public void clearPresentationCache() {
myPresentationFactory.reset();
}
public interface PopupStateModifier {
@ActionButtonComponent.ButtonState
int getModifiedPopupState();
boolean willModify();
}
}
| platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.actionSystem.impl;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.ide.HelpTooltip;
import com.intellij.ide.impl.DataManagerImpl;
import com.intellij.internal.statistic.collectors.fus.ui.persistence.ToolbarClicksCollector;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionButtonLook;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.actionSystem.ex.CustomComponentAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.keymap.ex.KeymapManagerEx;
import com.intellij.openapi.ui.popup.*;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.JBColor;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.awt.RelativeRectangle;
import com.intellij.ui.paint.LinePainter2D;
import com.intellij.ui.switcher.QuickActionProvider;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.*;
import com.intellij.util.ui.update.Activatable;
import com.intellij.util.ui.update.UiNotifyConnector;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class ActionToolbarImpl extends JPanel implements ActionToolbar, QuickActionProvider {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.actionSystem.impl.ActionToolbarImpl");
private static final List<ActionToolbarImpl> ourToolbars = new LinkedList<>();
private static final String RIGHT_ALIGN_KEY = "RIGHT_ALIGN";
static {
JBUI.addPropertyChangeListener(JBUI.USER_SCALE_FACTOR_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
((JBDimension)ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE).update();
((JBDimension)ActionToolbar.NAVBAR_MINIMUM_BUTTON_SIZE).update();
}
});
}
public static void updateAllToolbarsImmediately() {
for (ActionToolbarImpl toolbar : new ArrayList<>(ourToolbars)) {
toolbar.updateActionsImmediately();
for (Component c : toolbar.getComponents()) {
if (c instanceof ActionButton) {
((ActionButton)c).updateToolTipText();
((ActionButton)c).updateIcon();
}
}
}
}
/**
* This array contains Rectangles which define bounds of the corresponding
* components in the toolbar. This list can be consider as a cache of the
* Rectangle objects that are used in calculation of preferred sizes and
* components layout.
*/
private final List<Rectangle> myComponentBounds = new ArrayList<>();
private JBDimension myMinimumButtonSize = JBUI.emptySize();
/**
* @see ActionToolbar#getLayoutPolicy()
*/
private int myLayoutPolicy;
private int myOrientation;
private final ActionGroup myActionGroup;
private final String myPlace;
protected List<AnAction> myVisibleActions;
private final PresentationFactory myPresentationFactory = new PresentationFactory();
private final boolean myDecorateButtons;
private final ToolbarUpdater myUpdater;
/**
* @see ActionToolbar#adjustTheSameSize(boolean)
*/
private boolean myAdjustTheSameSize;
private final ActionButtonLook myButtonLook = null;
private final ActionButtonLook myMinimalButtonLook = ActionButtonLook.INPLACE_LOOK;
private final DataManager myDataManager;
protected final ActionManagerEx myActionManager;
private Rectangle myAutoPopupRec;
private final DefaultActionGroup mySecondaryActions = new DefaultActionGroup();
private PopupStateModifier mySecondaryButtonPopupStateModifier = null;
private boolean myForceMinimumSize = false;
private boolean myForceShowFirstComponent = false;
private boolean mySkipWindowAdjustments = false;
private boolean myMinimalMode;
private boolean myForceUseMacEnhancements;
public ActionButton getSecondaryActionsButton() {
return mySecondaryActionsButton;
}
private ActionButton mySecondaryActionsButton;
private int myFirstOutsideIndex = -1;
private JBPopup myPopup;
private JComponent myTargetComponent;
private boolean myReservePlaceAutoPopupIcon = true;
private boolean myAddSeparatorFirst;
public ActionToolbarImpl(String place,
@NotNull final ActionGroup actionGroup,
boolean horizontal,
@NotNull DataManager dataManager,
@NotNull ActionManagerEx actionManager,
@NotNull KeymapManagerEx keymapManager) {
this(place, actionGroup, horizontal, false, dataManager, actionManager, keymapManager, false);
}
public ActionToolbarImpl(String place,
@NotNull ActionGroup actionGroup,
boolean horizontal,
boolean decorateButtons,
@NotNull DataManager dataManager,
@NotNull ActionManagerEx actionManager,
@NotNull KeymapManagerEx keymapManager) {
this(place, actionGroup, horizontal, decorateButtons, dataManager, actionManager, keymapManager, false);
}
public ActionToolbarImpl(String place,
@NotNull ActionGroup actionGroup,
final boolean horizontal,
final boolean decorateButtons,
@NotNull DataManager dataManager,
@NotNull ActionManagerEx actionManager,
@NotNull KeymapManagerEx keymapManager,
boolean updateActionsNow) {
super(null);
myActionManager = actionManager;
myPlace = place;
myActionGroup = actionGroup;
myVisibleActions = new ArrayList<>();
myDataManager = dataManager;
myDecorateButtons = decorateButtons;
myUpdater = new ToolbarUpdater(actionManager, keymapManager, this) {
@Override
protected void updateActionsImpl(boolean transparentOnly, boolean forced) {
ActionToolbarImpl.this.updateActionsImpl(transparentOnly, forced);
}
};
setLayout(new BorderLayout());
setOrientation(horizontal ? SwingConstants.HORIZONTAL : SwingConstants.VERTICAL);
mySecondaryActions.getTemplatePresentation().setIcon(AllIcons.General.GearPlain);
mySecondaryActions.setPopup(true);
myUpdater.updateActions(updateActionsNow, false);
// If the panel doesn't handle mouse event then it will be passed to its parent.
// It means that if the panel is in sliding mode then the focus goes to the editor
// and panel will be automatically hidden.
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.COMPONENT_EVENT_MASK | AWTEvent.CONTAINER_EVENT_MASK);
setMiniMode(false);
}
@Override
public void updateUI() {
super.updateUI();
for (Component component : getComponents()) {
tweakActionComponentUI(component);
}
}
public String getPlace() {
return myPlace;
}
@Override
public void addNotify() {
super.addNotify();
ourToolbars.add(this);
// should update action right on the showing, otherwise toolbar may not be displayed at all,
// since by default all updates are postponed until frame gets focused.
updateActionsImmediately();
}
private boolean doMacEnhancementsForMainToolbar() {
return UIUtil.isUnderAquaLookAndFeel() && (ActionPlaces.MAIN_TOOLBAR.equals(myPlace) || myForceUseMacEnhancements);
}
public void setForceUseMacEnhancements(boolean useMacEnhancements) {
myForceUseMacEnhancements = useMacEnhancements;
}
private boolean isInsideNavBar() {
return ActionPlaces.NAVIGATION_BAR_TOOLBAR.equals(myPlace);
}
@Override
public void removeNotify() {
super.removeNotify();
ourToolbars.remove(this);
}
@NotNull
@Override
public JComponent getComponent() {
return this;
}
@Override
public int getLayoutPolicy() {
return myLayoutPolicy;
}
@Override
public void setLayoutPolicy(final int layoutPolicy) {
if (layoutPolicy != NOWRAP_LAYOUT_POLICY && layoutPolicy != WRAP_LAYOUT_POLICY && layoutPolicy != AUTO_LAYOUT_POLICY) {
throw new IllegalArgumentException("wrong layoutPolicy: " + layoutPolicy);
}
myLayoutPolicy = layoutPolicy;
}
@Override
protected Graphics getComponentGraphics(Graphics graphics) {
return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics));
}
@Override
protected void paintComponent(final Graphics g) {
if (doMacEnhancementsForMainToolbar()) {
final Rectangle r = getBounds();
UIUtil.drawGradientHToolbarBackground(g, r.width, r.height);
} else {
super.paintComponent(g);
}
if (myLayoutPolicy == AUTO_LAYOUT_POLICY) {
if (myAutoPopupRec != null) {
if (myOrientation == SwingConstants.HORIZONTAL) {
final int dy = myAutoPopupRec.height / 2 - AllIcons.Ide.Link.getIconHeight() / 2;
AllIcons.Ide.Link.paintIcon(this, g, (int)myAutoPopupRec.getMaxX() - AllIcons.Ide.Link.getIconWidth() - 1, myAutoPopupRec.y + dy);
}
else {
final int dx = myAutoPopupRec.width / 2 - AllIcons.Ide.Link.getIconWidth() / 2;
AllIcons.Ide.Link.paintIcon(this, g, myAutoPopupRec.x + dx, (int)myAutoPopupRec.getMaxY() - AllIcons.Ide.Link.getIconWidth() - 1);
}
}
}
}
public void setSecondaryButtonPopupStateModifier(PopupStateModifier popupStateModifier) {
mySecondaryButtonPopupStateModifier = popupStateModifier;
}
private void fillToolBar(final List<AnAction> actions, boolean layoutSecondaries) {
final List<AnAction> rightAligned = new ArrayList<>();
boolean isLastElementSeparator = false;
if (myAddSeparatorFirst) {
add(new MySeparator());
isLastElementSeparator = true;
}
for (int i = 0; i < actions.size(); i++) {
final AnAction action = actions.get(i);
if (action instanceof RightAlignedToolbarAction) {
rightAligned.add(action);
continue;
}
if (layoutSecondaries) {
if (!myActionGroup.isPrimary(action)) {
mySecondaryActions.add(action);
continue;
}
}
if (action instanceof Separator) {
if (isLastElementSeparator) continue;
if (i > 0 && i < actions.size() - 1) {
add(new MySeparator());
isLastElementSeparator = true;
continue;
}
}
else if (action instanceof CustomComponentAction) {
add(getCustomComponent(action));
}
else {
add(createToolbarButton(action));
}
isLastElementSeparator = false;
}
if (mySecondaryActions.getChildrenCount() > 0) {
mySecondaryActionsButton = new ActionButton(mySecondaryActions, myPresentationFactory.getPresentation(mySecondaryActions), myPlace, getMinimumButtonSize()) {
@Override
@ButtonState
public int getPopState() {
return mySecondaryButtonPopupStateModifier != null && mySecondaryButtonPopupStateModifier.willModify()
? mySecondaryButtonPopupStateModifier.getModifiedPopupState()
: super.getPopState();
}
};
mySecondaryActionsButton.setNoIconsInPopup(true);
add(mySecondaryActionsButton);
}
for (AnAction action : rightAligned) {
JComponent button = action instanceof CustomComponentAction ? getCustomComponent(action) : createToolbarButton(action);
if (!isInsideNavBar()) {
button.putClientProperty(RIGHT_ALIGN_KEY, Boolean.TRUE);
}
add(button);
}
//if ((ActionPlaces.MAIN_TOOLBAR.equals(myPlace) || ActionPlaces.NAVIGATION_BAR_TOOLBAR.equals(myPlace))) {
// final AnAction searchEverywhereAction = ActionManager.getInstance().getAction("SearchEverywhere");
// if (searchEverywhereAction != null) {
// try {
// final CustomComponentAction searchEveryWhereAction = (CustomComponentAction)searchEverywhereAction;
// final JComponent searchEverywhere = searchEveryWhereAction.createCustomComponent(searchEverywhereAction.getTemplatePresentation());
// searchEverywhere.putClientProperty("SEARCH_EVERYWHERE", Boolean.TRUE);
// add(searchEverywhere);
// }
// catch (Exception ignore) {}
// }
//}
}
private JComponent getCustomComponent(AnAction action) {
Presentation presentation = myPresentationFactory.getPresentation(action);
JComponent customComponent = ObjectUtils.tryCast(presentation.getClientProperty(CustomComponentAction.CUSTOM_COMPONENT_PROPERTY), JComponent.class);
if (customComponent == null) {
customComponent = ((CustomComponentAction)action).createCustomComponent(presentation);
presentation.putClientProperty(CustomComponentAction.CUSTOM_COMPONENT_PROPERTY, customComponent);
customComponent.putClientProperty(CustomComponentAction.CUSTOM_COMPONENT_ACTION_PROPERTY, action);
}
tweakActionComponentUI(customComponent);
AbstractButton clickable = UIUtil.findComponentOfType(customComponent, AbstractButton.class);
if (clickable != null) {
class ToolbarClicksCollectorListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {ToolbarClicksCollector.record(action, myPlace);}
}
if (Arrays.stream(clickable.getMouseListeners()).noneMatch(ml -> ml instanceof ToolbarClicksCollectorListener)) {
clickable.addMouseListener(new ToolbarClicksCollectorListener());
}
}
return customComponent;
}
private void tweakActionComponentUI(@NotNull Component actionComponent) {
if (ActionPlaces.EDITOR_TOOLBAR.equals(myPlace)) {
// tweak font & color for editor toolbar to match editor tabs style
actionComponent.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL));
actionComponent.setForeground(ColorUtil.dimmer(JBColor.BLACK));
}
}
private Dimension getMinimumButtonSize() {
return isInsideNavBar() ? NAVBAR_MINIMUM_BUTTON_SIZE : DEFAULT_MINIMUM_BUTTON_SIZE;
}
public ActionButton createToolbarButton(final AnAction action, final ActionButtonLook look, final String place, final Presentation presentation, final Dimension minimumSize) {
if (action.displayTextInToolbar()) {
int mnemonic = KeyEvent.getExtendedKeyCodeForChar(action.getTemplatePresentation().getMnemonic());
ActionButtonWithText buttonWithText = new ActionButtonWithText(action, presentation, place, minimumSize) {
@Override protected HelpTooltip.Alignment getTooltipLocation() {
return tooltipLocation();
}
};
if (mnemonic != KeyEvent.VK_UNDEFINED) {
buttonWithText.registerKeyboardAction(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buttonWithText.click();
}
}, KeyStroke.getKeyStroke(mnemonic,
/*SystemInfo.isMac
? InputEvent.CTRL_DOWN_MASK |
InputEvent.ALT_DOWN_MASK
:*/ InputEvent.ALT_DOWN_MASK), WHEN_IN_FOCUSED_WINDOW);
}
tweakActionComponentUI(buttonWithText);
return buttonWithText;
}
ActionButton actionButton = new ActionButton(action, presentation, place, minimumSize) {
@Override
protected DataContext getDataContext() {
return getToolbarDataContext();
}
@Override
protected HelpTooltip.Alignment getTooltipLocation() {
return tooltipLocation();
}
};
actionButton.setLook(look);
return actionButton;
}
private HelpTooltip.Alignment tooltipLocation() {
return myOrientation == SwingConstants.VERTICAL ? HelpTooltip.Alignment.RIGHT: HelpTooltip.Alignment.BOTTOM;
}
private ActionButton createToolbarButton(final AnAction action) {
return createToolbarButton(
action,
myMinimalMode ? myMinimalButtonLook : myDecorateButtons ? new ActionButtonLook() {
@Override
public void paintBorder(Graphics g, JComponent c, int state) {
g.setColor(JBColor.border());
g.drawLine(c.getWidth()-1, 0, c.getWidth()-1, c.getHeight());
}
@Override
public void paintBackground(Graphics g, JComponent component, int state) {
if (state == ActionButtonComponent.PUSHED) {
g.setColor(component.getBackground().darker());
((Graphics2D)g).fill(g.getClip());
}
}
} : myButtonLook,
myPlace, myPresentationFactory.getPresentation(action),
myMinimumButtonSize.size());
}
@Override
public void doLayout() {
if (!isValid()) {
calculateBounds(getSize(), myComponentBounds);
}
final int componentCount = getComponentCount();
LOG.assertTrue(componentCount <= myComponentBounds.size());
for (int i = componentCount - 1; i >= 0; i--) {
final Component component = getComponent(i);
component.setBounds(myComponentBounds.get(i));
}
}
@Override
public void validate() {
if (!isValid()) {
calculateBounds(getSize(), myComponentBounds);
super.validate();
}
}
private Dimension getChildPreferredSize(int index) {
Component component = getComponent(index);
return component.isVisible() ? component.getPreferredSize() : new Dimension();
}
/**
* @return maximum button width
*/
private int getMaxButtonWidth() {
int width = 0;
for (int i = 0; i < getComponentCount(); i++) {
final Dimension dimension = getChildPreferredSize(i);
width = Math.max(width, dimension.width);
}
return width;
}
/**
* @return maximum button height
*/
@Override
public int getMaxButtonHeight() {
int height = 0;
for (int i = 0; i < getComponentCount(); i++) {
final Dimension dimension = getChildPreferredSize(i);
height = Math.max(height, dimension.height);
}
return height;
}
private void calculateBoundsNowrapImpl(List<Rectangle> bounds) {
final int componentCount = getComponentCount();
LOG.assertTrue(componentCount <= bounds.size());
final int width = getWidth();
final int height = getHeight();
final Insets insets = getInsets();
if (myAdjustTheSameSize) {
final int maxWidth = getMaxButtonWidth();
final int maxHeight = getMaxButtonHeight();
if (myOrientation == SwingConstants.HORIZONTAL) {
int offset = 0;
for (int i = 0; i < componentCount; i++) {
final Rectangle r = bounds.get(i);
r.setBounds(insets.left + offset, insets.top + (height - maxHeight) / 2, maxWidth, maxHeight);
offset += maxWidth;
}
}
else {
int offset = 0;
for (int i = 0; i < componentCount; i++) {
final Rectangle r = bounds.get(i);
r.setBounds(insets.left + (width - maxWidth) / 2, insets.top + offset, maxWidth, maxHeight);
offset += maxHeight;
}
}
}
else {
if (myOrientation == SwingConstants.HORIZONTAL) {
final int maxHeight = getMaxButtonHeight();
int offset = 0;
for (int i = 0; i < componentCount; i++) {
final Dimension d = getChildPreferredSize(i);
final Rectangle r = bounds.get(i);
r.setBounds(insets.left + offset, insets.top + (maxHeight - d.height) / 2, d.width, d.height);
offset += d.width;
}
}
else {
final int maxWidth = getMaxButtonWidth();
int offset = 0;
for (int i = 0; i < componentCount; i++) {
final Dimension d = getChildPreferredSize(i);
final Rectangle r = bounds.get(i);
r.setBounds(insets.left + (maxWidth - d.width) / 2, insets.top + offset, d.width, d.height);
offset += d.height;
}
}
}
}
private void calculateBoundsAutoImp(Dimension sizeToFit, List<Rectangle> bounds) {
final int componentCount = getComponentCount();
LOG.assertTrue(componentCount <= bounds.size());
final boolean actualLayout = bounds == myComponentBounds;
if (actualLayout) {
myAutoPopupRec = null;
}
int autoButtonSize = AllIcons.Ide.Link.getIconWidth();
boolean full = false;
final Insets insets = getInsets();
int widthToFit = sizeToFit.width - insets.left - insets.right;
int heightToFit = sizeToFit.height - insets.top - insets.bottom;
if (myOrientation == SwingConstants.HORIZONTAL) {
int eachX = 0;
int maxHeight = heightToFit;
for (int i = 0; i < componentCount; i++) {
final Component eachComp = getComponent(i);
final boolean isLast = i == componentCount - 1;
final Rectangle eachBound = new Rectangle(getChildPreferredSize(i));
maxHeight = Math.max(eachBound.height, maxHeight);
if (!full) {
boolean inside;
if (isLast) {
inside = eachX + eachBound.width <= widthToFit;
} else {
inside = eachX + eachBound.width + autoButtonSize <= widthToFit;
}
if (inside) {
if (eachComp == mySecondaryActionsButton) {
assert isLast;
if (sizeToFit.width != Integer.MAX_VALUE) {
eachBound.x = sizeToFit.width - insets.right - eachBound.width;
eachX = (int)eachBound.getMaxX() - insets.left;
}
else {
eachBound.x = insets.left + eachX;
}
} else {
eachBound.x = insets.left + eachX;
eachX += eachBound.width;
}
eachBound.y = insets.top;
}
else {
full = true;
}
}
if (full) {
if (myAutoPopupRec == null) {
myAutoPopupRec = new Rectangle(insets.left + eachX, insets.top, widthToFit - eachX, heightToFit);
myFirstOutsideIndex = i;
}
eachBound.x = Integer.MAX_VALUE;
eachBound.y = Integer.MAX_VALUE;
}
bounds.get(i).setBounds(eachBound);
}
for (final Rectangle r : bounds) {
if (r.height < maxHeight) {
r.y += (maxHeight - r.height) / 2;
}
}
}
else {
int eachY = 0;
for (int i = 0; i < componentCount; i++) {
final Rectangle eachBound = new Rectangle(getChildPreferredSize(i));
if (!full) {
boolean outside;
if (i < componentCount - 1) {
outside = eachY + eachBound.height + autoButtonSize < heightToFit;
}
else {
outside = eachY + eachBound.height < heightToFit;
}
if (outside) {
eachBound.x = insets.left;
eachBound.y = insets.top + eachY;
eachY += eachBound.height;
}
else {
full = true;
}
}
if (full) {
if (myAutoPopupRec == null) {
myAutoPopupRec = new Rectangle(insets.left, insets.top + eachY, widthToFit, heightToFit - eachY);
myFirstOutsideIndex = i;
}
eachBound.x = Integer.MAX_VALUE;
eachBound.y = Integer.MAX_VALUE;
}
bounds.get(i).setBounds(eachBound);
}
}
}
private void calculateBoundsWrapImpl(Dimension sizeToFit, List<Rectangle> bounds) {
// We have to graceful handle case when toolbar was not laid out yet.
// In this case we calculate bounds as it is a NOWRAP toolbar.
if (getWidth() == 0 || getHeight() == 0) {
try {
setLayoutPolicy(NOWRAP_LAYOUT_POLICY);
calculateBoundsNowrapImpl(bounds);
}
finally {
setLayoutPolicy(WRAP_LAYOUT_POLICY);
}
return;
}
final int componentCount = getComponentCount();
LOG.assertTrue(componentCount <= bounds.size());
final Insets insets = getInsets();
int widthToFit = sizeToFit.width - insets.left - insets.right;
int heightToFit = sizeToFit.height - insets.top - insets.bottom;
if (myAdjustTheSameSize) {
if (myOrientation == SwingConstants.HORIZONTAL) {
final int maxWidth = getMaxButtonWidth();
final int maxHeight = getMaxButtonHeight();
// Lay components out
int xOffset = 0;
int yOffset = 0;
// Calculate max size of a row. It's not possible to make more than 3 row toolbar
final int maxRowWidth = Math.max(widthToFit, componentCount * maxWidth / 3);
for (int i = 0; i < componentCount; i++) {
if (xOffset + maxWidth > maxRowWidth) { // place component at new row
xOffset = 0;
yOffset += maxHeight;
}
final Rectangle each = bounds.get(i);
each.setBounds(insets.left + xOffset, insets.top + yOffset, maxWidth, maxHeight);
xOffset += maxWidth;
}
}
else {
final int maxWidth = getMaxButtonWidth();
final int maxHeight = getMaxButtonHeight();
// Lay components out
int xOffset = 0;
int yOffset = 0;
// Calculate max size of a row. It's not possible to make more then 3 column toolbar
final int maxRowHeight = Math.max(heightToFit, componentCount * myMinimumButtonSize.height() / 3);
for (int i = 0; i < componentCount; i++) {
if (yOffset + maxHeight > maxRowHeight) { // place component at new row
yOffset = 0;
xOffset += maxWidth;
}
final Rectangle each = bounds.get(i);
each.setBounds(insets.left + xOffset, insets.top + yOffset, maxWidth, maxHeight);
yOffset += maxHeight;
}
}
}
else {
if (myOrientation == SwingConstants.HORIZONTAL) {
// Calculate row height
int rowHeight = 0;
final Dimension[] dims = new Dimension[componentCount]; // we will use this dimensions later
for (int i = 0; i < componentCount; i++) {
dims[i] = getChildPreferredSize(i);
final int height = dims[i].height;
rowHeight = Math.max(rowHeight, height);
}
// Lay components out
int xOffset = 0;
int yOffset = 0;
// Calculate max size of a row. It's not possible to make more then 3 row toolbar
final int maxRowWidth = Math.max(widthToFit, componentCount * myMinimumButtonSize.width() / 3);
for (int i = 0; i < componentCount; i++) {
final Dimension d = dims[i];
if (xOffset + d.width > maxRowWidth) { // place component at new row
xOffset = 0;
yOffset += rowHeight;
}
final Rectangle each = bounds.get(i);
each.setBounds(insets.left + xOffset, insets.top + yOffset + (rowHeight - d.height) / 2, d.width, d.height);
xOffset += d.width;
}
}
else {
// Calculate row width
int rowWidth = 0;
final Dimension[] dims = new Dimension[componentCount]; // we will use this dimensions later
for (int i = 0; i < componentCount; i++) {
dims[i] = getChildPreferredSize(i);
final int width = dims[i].width;
rowWidth = Math.max(rowWidth, width);
}
// Lay components out
int xOffset = 0;
int yOffset = 0;
// Calculate max size of a row. It's not possible to make more then 3 column toolbar
final int maxRowHeight = Math.max(heightToFit, componentCount * myMinimumButtonSize.height() / 3);
for (int i = 0; i < componentCount; i++) {
final Dimension d = dims[i];
if (yOffset + d.height > maxRowHeight) { // place component at new row
yOffset = 0;
xOffset += rowWidth;
}
final Rectangle each = bounds.get(i);
each.setBounds(insets.left + xOffset + (rowWidth - d.width) / 2, insets.top + yOffset, d.width, d.height);
yOffset += d.height;
}
}
}
}
/**
* Calculates bounds of all the components in the toolbar
*/
private void calculateBounds(Dimension size2Fit, List<Rectangle> bounds) {
bounds.clear();
for (int i = 0; i < getComponentCount(); i++) {
bounds.add(new Rectangle());
}
if (myLayoutPolicy == NOWRAP_LAYOUT_POLICY) {
calculateBoundsNowrapImpl(bounds);
}
else if (myLayoutPolicy == WRAP_LAYOUT_POLICY) {
calculateBoundsWrapImpl(size2Fit, bounds);
}
else if (myLayoutPolicy == AUTO_LAYOUT_POLICY) {
calculateBoundsAutoImp(size2Fit, bounds);
}
else {
throw new IllegalStateException("unknown layoutPolicy: " + myLayoutPolicy);
}
if (getComponentCount() > 0 && size2Fit.width < Integer.MAX_VALUE) {
int maxHeight = 0;
for (int i = 0; i < bounds.size() - 2; i++) {
maxHeight = Math.max(maxHeight, bounds.get(i).height);
}
int rightOffset = 0;
Insets insets = getInsets();
for (int i = getComponentCount() - 1, j = 1; i > 0; i--, j++) {
final Component component = getComponent(i);
if (component instanceof JComponent && ((JComponent)component).getClientProperty(RIGHT_ALIGN_KEY) == Boolean.TRUE) {
rightOffset += bounds.get(i).width;
Rectangle r = bounds.get(bounds.size() - j);
r.x = size2Fit.width - rightOffset;
r.y = insets.top + (getHeight() - insets.top - insets.bottom - bounds.get(i).height) / 2;
}
}
}
}
@Override
public Dimension getPreferredSize() {
final ArrayList<Rectangle> bounds = new ArrayList<>();
calculateBounds(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE), bounds);
if (bounds.isEmpty()) return JBUI.emptySize();
int xLeft = Integer.MAX_VALUE;
int yTop = Integer.MAX_VALUE;
int xRight = Integer.MIN_VALUE;
int yBottom = Integer.MIN_VALUE;
for (int i = bounds.size() - 1; i >= 0; i--) {
final Rectangle each = bounds.get(i);
if (each.x == Integer.MAX_VALUE) continue;
xLeft = Math.min(xLeft, each.x);
yTop = Math.min(yTop, each.y);
xRight = Math.max(xRight, each.x + each.width);
yBottom = Math.max(yBottom, each.y + each.height);
}
final Dimension dimension = new Dimension(xRight - xLeft, yBottom - yTop);
if (myLayoutPolicy == AUTO_LAYOUT_POLICY && myReservePlaceAutoPopupIcon && !isInsideNavBar()) {
if (myOrientation == SwingConstants.HORIZONTAL) {
dimension.width += AllIcons.Ide.Link.getIconWidth();
}
else {
dimension.height += AllIcons.Ide.Link.getIconHeight();
}
}
JBInsets.addTo(dimension, getInsets());
return dimension;
}
public void setForceMinimumSize(boolean force) {
myForceMinimumSize = force;
}
/**
* By default minimum size is to show chevron only.
* If this option is <code>true</code> toolbar shows at least one (the first) component plus chevron (if need)
*/
public void setForceShowFirstComponent(boolean showFirstComponent) {
myForceShowFirstComponent = showFirstComponent;
}
/**
* This option makes sense when you use a toolbar inside JBPopup
* When some 'actions' are hidden under the chevron the popup with extra components would be shown/hidden
* with size adjustments for the main popup (this is default behavior).
* If this option is <code>true</code> size adjustments would be omitted
*/
public void setSkipWindowAdjustments(boolean skipWindowAdjustments) {
mySkipWindowAdjustments = skipWindowAdjustments;
}
@Override
public Dimension getMinimumSize() {
if (myForceMinimumSize) {
return getPreferredSize();
}
if (myLayoutPolicy == AUTO_LAYOUT_POLICY) {
final Insets i = getInsets();
if (myForceShowFirstComponent && getComponentCount() > 0) {
Component c = getComponent(0);
Dimension firstSize = c.getPreferredSize();
if (myOrientation == SwingConstants.HORIZONTAL) {
return new Dimension(firstSize.width + AllIcons.Ide.Link.getIconWidth() + i.left + i.right,
Math.max(firstSize.height, myMinimumButtonSize.height()) + i.top + i.bottom);
}
else {
return new Dimension(Math.max(firstSize.width, AllIcons.Ide.Link.getIconWidth()) + i.left + i.right,
firstSize.height + myMinimumButtonSize.height() + i.top + i.bottom);
}
}
return new Dimension(AllIcons.Ide.Link.getIconWidth() + i.left + i.right, myMinimumButtonSize.height() + i.top + i.bottom);
}
else {
return super.getMinimumSize();
}
}
private static class ToolbarReference extends WeakReference<ActionToolbarImpl> {
private static final ReferenceQueue<ActionToolbarImpl> ourQueue = new ReferenceQueue<>();
private volatile Disposable myDisposable;
ToolbarReference(ActionToolbarImpl toolbar) {
super(toolbar, ourQueue);
processQueue();
}
private static void processQueue() {
while (true) {
ToolbarReference ref = (ToolbarReference)ourQueue.poll();
if (ref == null) break;
ref.disposeReference();
}
}
private void disposeReference() {
Disposable disposable = myDisposable;
if (disposable != null) {
myDisposable = null;
Disposer.dispose(disposable);
}
}
}
private final class MySeparator extends JComponent {
@Override
public Dimension getPreferredSize() {
return (myOrientation == SwingConstants.HORIZONTAL) ? JBUI.size(7, 24) : JBUI.size(24, 7);
}
@Override
protected void paintComponent(final Graphics g) {
int gap = JBUI.scale(2);
int offset = JBUI.scale(3);
if (getParent() != null) {
g.setColor(UIUtil.getSeparatorColor());
if (myOrientation == SwingConstants.HORIZONTAL) {
LinePainter2D.paint((Graphics2D)g, offset, gap, offset, getParent().getSize().height - gap * 2 - offset);
}
else {
LinePainter2D.paint((Graphics2D)g, gap, offset, getParent().getSize().width - gap * 2 - offset, offset);
}
}
}
}
@Override
public void adjustTheSameSize(final boolean value) {
if (myAdjustTheSameSize == value) {
return;
}
myAdjustTheSameSize = value;
revalidate();
}
@Override
public void setMinimumButtonSize(@NotNull final Dimension size) {
myMinimumButtonSize = JBDimension.create(size, true);
for (int i = getComponentCount() - 1; i >= 0; i--) {
final Component component = getComponent(i);
if (component instanceof ActionButton) {
final ActionButton button = (ActionButton)component;
button.setMinimumButtonSize(size);
}
}
revalidate();
}
@Override
public void setOrientation(@MagicConstant(intValues = {SwingConstants.HORIZONTAL, SwingConstants.VERTICAL}) int orientation) {
if (SwingConstants.HORIZONTAL != orientation && SwingConstants.VERTICAL != orientation) {
throw new IllegalArgumentException("wrong orientation: " + orientation);
}
myOrientation = orientation;
}
int getOrientation() {
return myOrientation;
}
@Override
public void updateActionsImmediately() {
ApplicationManager.getApplication().assertIsDispatchThread();
myUpdater.updateActions(true, false);
}
private void updateActionsImpl(boolean transparentOnly, boolean forced) {
List<AnAction> newVisibleActions = ContainerUtil.newArrayListWithCapacity(myVisibleActions.size());
DataContext dataContext = getDataContext();
Utils.expandActionGroup(LaterInvocator.isInModalContext(), myActionGroup, newVisibleActions, myPresentationFactory, dataContext,
myPlace, myActionManager, transparentOnly, false, false, true);
if (forced || !newVisibleActions.equals(myVisibleActions)) {
boolean shouldRebuildUI = newVisibleActions.isEmpty() || myVisibleActions.isEmpty();
myVisibleActions = newVisibleActions;
Dimension oldSize = getPreferredSize();
removeAll();
mySecondaryActions.removeAll();
mySecondaryActionsButton = null;
fillToolBar(myVisibleActions, getLayoutPolicy() == AUTO_LAYOUT_POLICY && myOrientation == SwingConstants.HORIZONTAL);
Dimension newSize = getPreferredSize();
if (!mySkipWindowAdjustments) {
((WindowManagerEx)WindowManager.getInstance()).adjustContainerWindow(this, oldSize, newSize);
}
if (shouldRebuildUI) {
revalidate();
} else {
Container parent = getParent();
if (parent != null) {
parent.invalidate();
parent.validate();
}
}
repaint();
}
}
@Override
public boolean hasVisibleActions() {
return !myVisibleActions.isEmpty();
}
@Override
public void setTargetComponent(final JComponent component) {
myTargetComponent = component;
if (myTargetComponent != null) {
updateWhenFirstShown(myTargetComponent, new ToolbarReference(this));
}
}
private static void updateWhenFirstShown(JComponent targetComponent, final ToolbarReference ref) {
Activatable activatable = new Activatable.Adapter() {
public void showNotify() {
ActionToolbarImpl toolbar = ref.get();
if (toolbar != null) {
toolbar.myUpdater.updateActions(false, false);
}
}
};
ref.myDisposable = new UiNotifyConnector(targetComponent, activatable) {
@Override
protected void showNotify() {
super.showNotify();
ref.disposeReference();
}
};
}
@Override
public DataContext getToolbarDataContext() {
return getDataContext();
}
protected DataContext getDataContext() {
return myTargetComponent != null ? myDataManager.getDataContext(myTargetComponent) : ((DataManagerImpl)myDataManager).getDataContextTest(this);
}
@Override
protected void processMouseMotionEvent(final MouseEvent e) {
super.processMouseMotionEvent(e);
if (getLayoutPolicy() != AUTO_LAYOUT_POLICY) {
return;
}
if (myAutoPopupRec != null && myAutoPopupRec.contains(e.getPoint())) {
IdeFocusManager.getInstance(null).doWhenFocusSettlesDown(() -> showAutoPopup());
}
}
private void showAutoPopup() {
if (isPopupShowing()) return;
final ActionGroup group;
if (myOrientation == SwingConstants.HORIZONTAL) {
group = myActionGroup;
}
else {
final DefaultActionGroup outside = new DefaultActionGroup();
for (int i = myFirstOutsideIndex; i < myVisibleActions.size(); i++) {
outside.add(myVisibleActions.get(i));
}
group = outside;
}
PopupToolbar popupToolbar = new PopupToolbar(myPlace, group, true, myDataManager, myActionManager, myUpdater.getKeymapManager(), this) {
@Override
protected void onOtherActionPerformed() {
hidePopup();
}
@Override
protected DataContext getDataContext() {
return ActionToolbarImpl.this.getDataContext();
}
};
popupToolbar.setLayoutPolicy(NOWRAP_LAYOUT_POLICY);
popupToolbar.updateActionsImmediately();
Point location;
if (myOrientation == SwingConstants.HORIZONTAL) {
location = getLocationOnScreen();
}
else {
location = getLocationOnScreen();
location.y = location.y + getHeight() - popupToolbar.getPreferredSize().height;
}
final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(popupToolbar, null);
builder.setResizable(false)
.setMovable(true) // fit the screen automatically
.setRequestFocus(false)
.setTitle(null)
.setCancelOnClickOutside(true)
.setCancelOnOtherWindowOpen(true)
.setCancelCallback(() -> {
final boolean toClose = myActionManager.isActionPopupStackEmpty();
if (toClose) {
myUpdater.updateActions(false, true);
}
return toClose;
})
.setCancelOnMouseOutCallback(new MouseChecker() {
@Override
public boolean check(final MouseEvent event) {
return myAutoPopupRec != null &&
myActionManager.isActionPopupStackEmpty() &&
!new RelativeRectangle(ActionToolbarImpl.this, myAutoPopupRec).contains(new RelativePoint(event));
}
});
builder.addListener(new JBPopupAdapter() {
@Override
public void onClosed(LightweightWindowEvent event) {
processClosed();
}
});
myPopup = builder.createPopup();
final AnActionListener.Adapter listener = new AnActionListener.Adapter() {
@Override
public void afterActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
final JBPopup popup = myPopup;
if (popup != null && !popup.isDisposed() && popup.isVisible()) {
popup.cancel();
}
}
};
ActionManager.getInstance().addAnActionListener(listener);
Disposer.register(myPopup, popupToolbar);
Disposer.register(popupToolbar, new Disposable() {
@Override
public void dispose() {
ActionManager.getInstance().removeAnActionListener(listener);
}
});
myPopup.showInScreenCoordinates(this, location);
final Window window = SwingUtilities.getWindowAncestor(this);
if (window != null) {
final ComponentAdapter componentAdapter = new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
hidePopup();
}
@Override
public void componentMoved(final ComponentEvent e) {
hidePopup();
}
@Override
public void componentShown(final ComponentEvent e) {
hidePopup();
}
@Override
public void componentHidden(final ComponentEvent e) {
hidePopup();
}
};
window.addComponentListener(componentAdapter);
Disposer.register(popupToolbar, new Disposable() {
@Override
public void dispose() {
window.removeComponentListener(componentAdapter);
}
});
}
}
private boolean isPopupShowing() {
if (myPopup != null) {
if (myPopup.getContent() != null) {
return true;
}
}
return false;
}
private void hidePopup() {
if (myPopup != null) {
myPopup.cancel();
processClosed();
}
}
private void processClosed() {
if (myPopup == null) return;
Disposer.dispose(myPopup);
myPopup = null;
myUpdater.updateActions(false, false);
}
abstract static class PopupToolbar extends ActionToolbarImpl implements AnActionListener, Disposable {
private final JComponent myParent;
public PopupToolbar(final String place,
final ActionGroup actionGroup,
final boolean horizontal,
final DataManager dataManager,
@NotNull ActionManagerEx actionManager,
final KeymapManagerEx keymapManager,
JComponent parent) {
super(place, actionGroup, horizontal, false, dataManager, actionManager, keymapManager, true);
myActionManager.addAnActionListener(this);
myParent = parent;
}
@Override
public Container getParent() {
Container parent = super.getParent();
return parent != null ? parent : myParent;
}
@Override
public void dispose() {
myActionManager.removeAnActionListener(this);
}
@Override
public void beforeActionPerformed(final AnAction action, final DataContext dataContext, AnActionEvent event) {
}
@Override
public void afterActionPerformed(final AnAction action, final DataContext dataContext, AnActionEvent event) {
if (!myVisibleActions.contains(action)) {
onOtherActionPerformed();
}
}
protected abstract void onOtherActionPerformed();
}
@Override
public void setReservePlaceAutoPopupIcon(final boolean reserve) {
myReservePlaceAutoPopupIcon = reserve;
}
@Override
public void setSecondaryActionsTooltip(String secondaryActionsTooltip) {
mySecondaryActions.getTemplatePresentation().setDescription(secondaryActionsTooltip);
}
@Override
public void setSecondaryActionsIcon(Icon icon) {
mySecondaryActions.getTemplatePresentation().setIcon(icon);
}
@NotNull
@Override
public List<AnAction> getActions(boolean originalProvider) {
return getActions();
}
@NotNull
@Override
public List<AnAction> getActions() {
ArrayList<AnAction> result = new ArrayList<>();
ArrayList<AnAction> secondary = new ArrayList<>();
AnAction[] kids = myActionGroup.getChildren(null);
for (AnAction each : kids) {
if (myActionGroup.isPrimary(each)) {
result.add(each);
} else {
secondary.add(each);
}
}
result.add(new Separator());
result.addAll(secondary);
return result;
}
@Override
public void setMiniMode(boolean minimalMode) {
//if (myMinimalMode == minimalMode) return;
myMinimalMode = minimalMode;
if (myMinimalMode) {
setMinimumButtonSize(JBUI.emptySize());
setLayoutPolicy(NOWRAP_LAYOUT_POLICY);
setBorder(JBUI.Borders.empty());
setOpaque(false);
} else {
setBorder(JBUI.Borders.empty(2));
setMinimumButtonSize(myDecorateButtons ? JBUI.size(30, 20) : DEFAULT_MINIMUM_BUTTON_SIZE);
setOpaque(true);
setLayoutPolicy(AUTO_LAYOUT_POLICY);
}
myUpdater.updateActions(false, true);
}
public void setAddSeparatorFirst(boolean addSeparatorFirst) {
myAddSeparatorFirst = addSeparatorFirst;
myUpdater.updateActions(false, true);
}
@TestOnly
public Presentation getPresentation(AnAction action) {
return myPresentationFactory.getPresentation(action);
}
public void clearPresentationCache() {
myPresentationFactory.reset();
}
public interface PopupStateModifier {
@ActionButtonComponent.ButtonState
int getModifiedPopupState();
boolean willModify();
}
}
| IDEA-164920 Wrap toolbar
| platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java | IDEA-164920 Wrap toolbar |
|
Java | apache-2.0 | f511e6f9a0a7b515a35a3ae7e64724ed4c322c61 | 0 | joshuairl/toothchat-client,joshuairl/toothchat-client,joshuairl/toothchat-client,joshuairl/toothchat-client | /**
* $Revision: $
* $Date: $
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Lesser Public License (LGPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.sparkplugin;
import org.jivesoftware.Spark;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.jingle.JingleManager;
import org.jivesoftware.smackx.jingle.JingleSessionRequest;
import org.jivesoftware.smackx.jingle.OutgoingJingleSession;
import org.jivesoftware.smackx.jingle.listeners.JingleSessionRequestListener;
import org.jivesoftware.smackx.jingle.mediaimpl.jmf.JmfMediaManager;
import org.jivesoftware.smackx.jingle.mediaimpl.jspeex.SpeexMediaManager;
import org.jivesoftware.smackx.jingle.mediaimpl.multi.MultiMediaManager;
import org.jivesoftware.smackx.jingle.nat.BridgedTransportManager;
import org.jivesoftware.smackx.jingle.nat.ICETransportManager;
import org.jivesoftware.smackx.jingle.nat.JingleTransportManager;
import org.jivesoftware.smackx.jingle.nat.STUN;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.spark.PresenceManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.phone.Phone;
import org.jivesoftware.spark.phone.PhoneManager;
import org.jivesoftware.spark.plugin.Plugin;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.TranscriptWindow;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.log.Log;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A simple Jingle Plugin for Spark that uses server Media Proxy for the transport and NAT Traversal
*/
public class JinglePlugin implements Plugin, Phone {
private JingleManager jingleManager;
private static final String JINGLE_NAMESPACE = "http://www.xmpp.org/extensions/xep-0166.html#ns";
private Map<String, Boolean> jingleFeature = new HashMap<String, Boolean>();
public void initialize() {
// Add to PhoneManager
PhoneManager.getInstance().addPhone(this);
// Adds a tab handler.
SparkManager.getChatManager().addSparkTabHandler(new JingleTabHandler());
final SwingWorker jingleLoadingThread = new SwingWorker() {
public Object construct() {
String stunServer = "stun.xten.net";
int stunPort = 3478;
if (STUN.serviceAvailable(SparkManager.getConnection())) {
STUN stun = STUN.getSTUNServer(SparkManager.getConnection());
if (stun != null) {
List<STUN.StunServerAddress> servers = stun.getServers();
if (servers.size() > 0) {
stunServer = servers.get(0).getServer();
stunPort = Integer.parseInt(servers.get(0).getPort());
}
}
}
JingleTransportManager transportManager = new ICETransportManager(SparkManager.getConnection(), stunServer, stunPort);
// if running on Windows use Direct Sound for better performance
String locator = Spark.isWindows() ? "dsound://" : "javasound://";
MultiMediaManager jingleMediaManager = new MultiMediaManager();
jingleMediaManager.addMediaManager(new JmfMediaManager(locator));
jingleMediaManager.addMediaManager(new SpeexMediaManager());
if (System.getProperty("codec") != null) {
try {
int codec = Integer.parseInt(System.getProperty("codec"));
jingleMediaManager.setPreferredPayloadType(jingleMediaManager.getPayloads().get(codec));
}
catch (NumberFormatException e) {
// Do Nothing
}
}
jingleManager = new JingleManager(SparkManager.getConnection(), transportManager, new JmfMediaManager(locator));
if (transportManager instanceof BridgedTransportManager) {
jingleManager.addCreationListener((BridgedTransportManager)transportManager);
}else if(transportManager instanceof ICETransportManager){
jingleManager.addCreationListener((ICETransportManager)transportManager);
}
// Add Jingle to discovered items list.
SparkManager.addFeature(JINGLE_NAMESPACE);
return true;
}
public void finished() {
addListeners();
}
};
jingleLoadingThread.start();
// Add Presence listener for better service discovery.
addPresenceListener();
}
/**
* Adds Jingle and ChatRoom listeners.
*/
private void addListeners() {
if (jingleManager == null) {
Log.error("Unable to resolve Jingle Connection");
return;
}
// Listen in for new incoming Jingle requests.
jingleManager.addJingleSessionRequestListener(new JingleSessionRequestListener() {
public void sessionRequested(final JingleSessionRequest request) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
incomingJingleSession(request);
}
});
}
});
}
public Collection<Action> getPhoneActions(final String jid) {
if (jingleManager == null) {
return Collections.emptyList();
}
Boolean supportsJingle = jingleFeature.get(StringUtils.parseBareAddress(jid));
if (supportsJingle == null) {
// Disco for event.
// Obtain the ServiceDiscoveryManager associated with my XMPPConnection
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(SparkManager.getConnection());
String fullJID = PresenceManager.getFullyQualifiedJID(jid);
// Get the items of a given XMPP entity
// This example gets the items associated with online catalog service
DiscoverInfo discoverInfo = null;
try {
discoverInfo = discoManager.discoverInfo(fullJID);
}
catch (XMPPException e) {
Log.error(e);
}
if (discoverInfo != null) {
// Get the discovered items of the queried XMPP entity
supportsJingle = discoverInfo.containsFeature(JINGLE_NAMESPACE);
jingleFeature.put(jid, supportsJingle);
}
else {
jingleFeature.put(jid, false);
supportsJingle = false;
}
}
if (!supportsJingle) {
return Collections.emptyList();
}
final List<Action> actions = new ArrayList<Action>();
Action action = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
placeCall(jid);
}
};
action.putValue(Action.NAME, "<html><b>Computer To Computer</b></html>");
action.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.COMPUTER_IMAGE_16x16));
actions.add(action);
return actions;
}
public void placeCall(String jid) {
jid = SparkManager.getUserManager().getFullJID(jid);
ChatRoom room = SparkManager.getChatManager().getChatRoom(StringUtils.parseBareAddress(jid));
if (JingleStateManager.getInstance().getJingleRoomState(room) != null) {
return;
}
SparkManager.getChatManager().getChatContainer().activateChatRoom(room);
// Create a new Jingle Call with a full JID
OutgoingJingleSession session = null;
try {
session = jingleManager.createOutgoingJingleSession(jid);
}
catch (XMPPException e) {
Log.error(e);
}
TranscriptWindow transcriptWindow = room.getTranscriptWindow();
StyledDocument doc = (StyledDocument)transcriptWindow.getDocument();
Style style = doc.addStyle("StyleName", null);
OutgoingCall outgoingCall = new OutgoingCall();
outgoingCall.handleOutgoingCall(session, room, jid);
StyleConstants.setComponent(style, outgoingCall);
// Insert the image at the end of the text
try {
doc.insertString(doc.getLength(), "ignored text", style);
doc.insertString(doc.getLength(), "\n", null);
}
catch (BadLocationException e) {
Log.error(e);
}
room.scrollToBottom();
}
public void shutdown() {
}
public boolean canShutDown() {
return false;
}
public void uninstall() {
}
/**
* Notify user that a new incoming jingle request has been receieved.
*
* @param request the <code>JingleSessionRequest</code>.
*/
private void incomingJingleSession(JingleSessionRequest request) {
new IncomingCall(request);
}
/**
* Adds a presence listener to remove offline users from discovered features.
*/
private void addPresenceListener() {
// Check presence changes
SparkManager.getConnection().addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Presence presence = (Presence)packet;
if (!presence.isAvailable()) {
String from = presence.getFrom();
if (ModelUtil.hasLength(from)) {
// Remove from
jingleFeature.remove(from);
}
}
}
}, new PacketTypeFilter(Presence.class));
}
}
| src/plugins/jingle/src/java/org/jivesoftware/sparkplugin/JinglePlugin.java | /**
* $Revision: $
* $Date: $
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Lesser Public License (LGPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.sparkplugin;
import org.jivesoftware.Spark;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.jingle.JingleManager;
import org.jivesoftware.smackx.jingle.JingleSessionRequest;
import org.jivesoftware.smackx.jingle.OutgoingJingleSession;
import org.jivesoftware.smackx.jingle.listeners.JingleSessionRequestListener;
import org.jivesoftware.smackx.jingle.mediaimpl.jmf.JmfMediaManager;
import org.jivesoftware.smackx.jingle.mediaimpl.jspeex.SpeexMediaManager;
import org.jivesoftware.smackx.jingle.mediaimpl.multi.MultiMediaManager;
import org.jivesoftware.smackx.jingle.nat.BridgedTransportManager;
import org.jivesoftware.smackx.jingle.nat.ICETransportManager;
import org.jivesoftware.smackx.jingle.nat.JingleTransportManager;
import org.jivesoftware.smackx.jingle.nat.STUN;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.spark.PresenceManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.phone.Phone;
import org.jivesoftware.spark.phone.PhoneManager;
import org.jivesoftware.spark.plugin.Plugin;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.TranscriptWindow;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.log.Log;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A simple Jingle Plugin for Spark that uses server Media Proxy for the transport and NAT Traversal
*/
public class JinglePlugin implements Plugin, Phone {
private JingleManager jingleManager;
private static final String JINGLE_NAMESPACE = "http://www.xmpp.org/extensions/xep-0166.html#ns";
private Map<String, Boolean> jingleFeature = new HashMap<String, Boolean>();
public void initialize() {
// Add to PhoneManager
PhoneManager.getInstance().addPhone(this);
// Adds a tab handler.
SparkManager.getChatManager().addSparkTabHandler(new JingleTabHandler());
final SwingWorker jingleLoadingThread = new SwingWorker() {
public Object construct() {
String stunServer = "stun.xten.net";
int stunPort = 3478;
if (STUN.serviceAvailable(SparkManager.getConnection())) {
STUN stun = STUN.getSTUNServer(SparkManager.getConnection());
if (stun != null) {
List<STUN.StunServerAddress> servers = stun.getServers();
if (servers.size() > 0) {
stunServer = servers.get(0).getServer();
stunPort = Integer.parseInt(servers.get(0).getPort());
}
}
}
JingleTransportManager transportManager = new ICETransportManager(SparkManager.getConnection(), stunServer, stunPort);
// if running on Windows use Direct Sound for better performance
String locator = Spark.isWindows() ? "dsound://" : "javasound://";
MultiMediaManager jingleMediaManager = new MultiMediaManager();
jingleMediaManager.addMediaManager(new JmfMediaManager(locator));
jingleMediaManager.addMediaManager(new SpeexMediaManager());
if (System.getProperty("codec") != null) {
try {
int codec = Integer.parseInt(System.getProperty("codec"));
jingleMediaManager.setPreferredPayloadType(jingleMediaManager.getPayloads().get(codec));
}
catch (NumberFormatException e) {
// Do Nothing
}
}
jingleManager = new JingleManager(SparkManager.getConnection(), transportManager, new JmfMediaManager(locator));
if (transportManager instanceof BridgedTransportManager || transportManager instanceof ICETransportManager) {
jingleManager.addCreationListener((BridgedTransportManager)transportManager);
}
// Add Jingle to discovered items list.
SparkManager.addFeature(JINGLE_NAMESPACE);
return true;
}
public void finished() {
addListeners();
}
};
jingleLoadingThread.start();
// Add Presence listener for better service discovery.
addPresenceListener();
}
/**
* Adds Jingle and ChatRoom listeners.
*/
private void addListeners() {
if (jingleManager == null) {
Log.error("Unable to resolve Jingle Connection");
return;
}
// Listen in for new incoming Jingle requests.
jingleManager.addJingleSessionRequestListener(new JingleSessionRequestListener() {
public void sessionRequested(final JingleSessionRequest request) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
incomingJingleSession(request);
}
});
}
});
}
public Collection<Action> getPhoneActions(final String jid) {
if (jingleManager == null) {
return Collections.emptyList();
}
Boolean supportsJingle = jingleFeature.get(StringUtils.parseBareAddress(jid));
if (supportsJingle == null) {
// Disco for event.
// Obtain the ServiceDiscoveryManager associated with my XMPPConnection
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(SparkManager.getConnection());
String fullJID = PresenceManager.getFullyQualifiedJID(jid);
// Get the items of a given XMPP entity
// This example gets the items associated with online catalog service
DiscoverInfo discoverInfo = null;
try {
discoverInfo = discoManager.discoverInfo(fullJID);
}
catch (XMPPException e) {
Log.error(e);
}
if (discoverInfo != null) {
// Get the discovered items of the queried XMPP entity
supportsJingle = discoverInfo.containsFeature(JINGLE_NAMESPACE);
jingleFeature.put(jid, supportsJingle);
}
else {
jingleFeature.put(jid, false);
supportsJingle = false;
}
}
if (!supportsJingle) {
return Collections.emptyList();
}
final List<Action> actions = new ArrayList<Action>();
Action action = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
placeCall(jid);
}
};
action.putValue(Action.NAME, "<html><b>Computer To Computer</b></html>");
action.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.COMPUTER_IMAGE_16x16));
actions.add(action);
return actions;
}
public void placeCall(String jid) {
jid = SparkManager.getUserManager().getFullJID(jid);
ChatRoom room = SparkManager.getChatManager().getChatRoom(StringUtils.parseBareAddress(jid));
if (JingleStateManager.getInstance().getJingleRoomState(room) != null) {
return;
}
SparkManager.getChatManager().getChatContainer().activateChatRoom(room);
// Create a new Jingle Call with a full JID
OutgoingJingleSession session = null;
try {
session = jingleManager.createOutgoingJingleSession(jid);
}
catch (XMPPException e) {
Log.error(e);
}
TranscriptWindow transcriptWindow = room.getTranscriptWindow();
StyledDocument doc = (StyledDocument)transcriptWindow.getDocument();
Style style = doc.addStyle("StyleName", null);
OutgoingCall outgoingCall = new OutgoingCall();
outgoingCall.handleOutgoingCall(session, room, jid);
StyleConstants.setComponent(style, outgoingCall);
// Insert the image at the end of the text
try {
doc.insertString(doc.getLength(), "ignored text", style);
doc.insertString(doc.getLength(), "\n", null);
}
catch (BadLocationException e) {
Log.error(e);
}
room.scrollToBottom();
}
public void shutdown() {
}
public boolean canShutDown() {
return false;
}
public void uninstall() {
}
/**
* Notify user that a new incoming jingle request has been receieved.
*
* @param request the <code>JingleSessionRequest</code>.
*/
private void incomingJingleSession(JingleSessionRequest request) {
new IncomingCall(request);
}
/**
* Adds a presence listener to remove offline users from discovered features.
*/
private void addPresenceListener() {
// Check presence changes
SparkManager.getConnection().addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Presence presence = (Presence)packet;
if (!presence.isAvailable()) {
String from = presence.getFrom();
if (ModelUtil.hasLength(from)) {
// Remove from
jingleFeature.remove(from);
}
}
}
}, new PacketTypeFilter(Presence.class));
}
}
| Small Fixes in Bridge Listeners
git-svn-id: f13e20fb8540f76a08799c0051229138c0279aa7@7829 b35dd754-fafc-0310-a699-88a17e54d16e
| src/plugins/jingle/src/java/org/jivesoftware/sparkplugin/JinglePlugin.java | Small Fixes in Bridge Listeners |
|
Java | apache-2.0 | 4fe4e4ac76d0bc9365e1a129f4976564772c0063 | 0 | code-distillery/jackrabbit-oak,code-distillery/jackrabbit-oak,alexparvulescu/jackrabbit-oak,catholicon/jackrabbit-oak,anchela/jackrabbit-oak,code-distillery/jackrabbit-oak,catholicon/jackrabbit-oak,meggermo/jackrabbit-oak,meggermo/jackrabbit-oak,stillalex/jackrabbit-oak,alexparvulescu/jackrabbit-oak,chetanmeh/jackrabbit-oak,chetanmeh/jackrabbit-oak,chetanmeh/jackrabbit-oak,anchela/jackrabbit-oak,alexparvulescu/jackrabbit-oak,catholicon/jackrabbit-oak,alexkli/jackrabbit-oak,meggermo/jackrabbit-oak,alexparvulescu/jackrabbit-oak,anchela/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,code-distillery/jackrabbit-oak,chetanmeh/jackrabbit-oak,alexkli/jackrabbit-oak,francescomari/jackrabbit-oak,meggermo/jackrabbit-oak,stillalex/jackrabbit-oak,francescomari/jackrabbit-oak,yesil/jackrabbit-oak,catholicon/jackrabbit-oak,alexkli/jackrabbit-oak,anchela/jackrabbit-oak,yesil/jackrabbit-oak,stillalex/jackrabbit-oak,stillalex/jackrabbit-oak,meggermo/jackrabbit-oak,anchela/jackrabbit-oak,alexkli/jackrabbit-oak,francescomari/jackrabbit-oak,francescomari/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,stillalex/jackrabbit-oak,yesil/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,catholicon/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexkli/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,yesil/jackrabbit-oak,francescomari/jackrabbit-oak,chetanmeh/jackrabbit-oak,code-distillery/jackrabbit-oak | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.document;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import javax.sql.DataSource;
import org.apache.jackrabbit.oak.commons.FixturesHelper;
import org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore;
import org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore;
import org.apache.jackrabbit.oak.plugins.document.rdb.RDBDataSourceFactory;
import org.apache.jackrabbit.oak.plugins.document.rdb.RDBDataSourceWrapper;
import org.apache.jackrabbit.oak.plugins.document.rdb.RDBDocumentStore;
import org.apache.jackrabbit.oak.plugins.document.rdb.RDBOptions;
import org.apache.jackrabbit.oak.plugins.document.util.MongoConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.mongodb.DB;
import static org.apache.jackrabbit.oak.commons.FixturesHelper.Fixture.DOCUMENT_MEM;
import static org.apache.jackrabbit.oak.commons.FixturesHelper.Fixture.DOCUMENT_NS;
import static org.apache.jackrabbit.oak.commons.FixturesHelper.Fixture.DOCUMENT_RDB;
public abstract class DocumentStoreFixture {
private static final Logger LOG = LoggerFactory.getLogger(DocumentStoreFixture.class);
public static final DocumentStoreFixture MEMORY = new MemoryFixture();
public static final DocumentStoreFixture MONGO = new MongoFixture();
public static final DocumentStoreFixture RDB_DB2 = new RDBFixture("RDB-DB2", System.getProperty("rdb-db2-jdbc-url",
"jdbc:db2://localhost:50000/OAK"), System.getProperty("rdb-db2-jdbc-user", "oak"), System.getProperty(
"rdb-db2-jdbc-passwd", "geheim"));
public static final DocumentStoreFixture RDB_DERBY = new RDBFixture("RDB-Derby(embedded)", System.getProperty(
"rdb-derby-jdbc-url", "jdbc:derby:./target/derby-ds-test;create=true"),
System.getProperty("rdb-derby-jdbc-user", "sa"), System.getProperty("rdb-derby-jdbc-passwd", ""));
public static final DocumentStoreFixture RDB_H2 = new RDBFixture("RDB-H2(file)", System.getProperty("rdb-h2-jdbc-url",
"jdbc:h2:file:./target/h2-ds-test"), System.getProperty("rdb-h2-jdbc-user", "sa"), System.getProperty(
"rdb-h2-jdbc-passwd", ""));
public static final DocumentStoreFixture RDB_MSSQL = new RDBFixture("RDB-MSSql", System.getProperty("rdb-mssql-jdbc-url",
"jdbc:sqlserver://localhost:1433;databaseName=OAK"), System.getProperty("rdb-mssql-jdbc-user", "sa"),
System.getProperty("rdb-mssql-jdbc-passwd", "geheim"));
public static final DocumentStoreFixture RDB_MYSQL = new RDBFixture("RDB-MySQL", System.getProperty("rdb-mysql-jdbc-url",
"jdbc:mysql://localhost:3306/oak"), System.getProperty("rdb-mysql-jdbc-user", "root"), System.getProperty(
"rdb-mysql-jdbc-passwd", "geheim"));
public static final DocumentStoreFixture RDB_ORACLE = new RDBFixture("RDB-Oracle", System.getProperty("rdb-oracle-jdbc-url",
"jdbc:oracle:thin:@localhost:1521:orcl"), System.getProperty("rdb-oracle-jdbc-user", "system"), System.getProperty(
"rdb-oracle-jdbc-passwd", "geheim"));
public static final DocumentStoreFixture RDB_PG = new RDBFixture("RDB-Postgres", System.getProperty("rdb-postgres-jdbc-url",
"jdbc:postgresql:oak"), System.getProperty("rdb-postgres-jdbc-user", "postgres"), System.getProperty(
"rdb-postgres-jdbc-passwd", "geheim"));
public static final String TABLEPREFIX = "dstest_";
public static List<Object[]> getFixtures() {
List<Object[]> fixtures = Lists.newArrayList();
if (FixturesHelper.getFixtures().contains(DOCUMENT_MEM)) {
fixtures.add(new Object[] { new DocumentStoreFixture.MemoryFixture() });
}
DocumentStoreFixture mongo = new DocumentStoreFixture.MongoFixture();
if (FixturesHelper.getFixtures().contains(DOCUMENT_NS) && mongo.isAvailable()) {
fixtures.add(new Object[] { mongo });
}
DocumentStoreFixture rdb = new DocumentStoreFixture.RDBFixture();
if (FixturesHelper.getFixtures().contains(DOCUMENT_RDB) && rdb.isAvailable()) {
fixtures.add(new Object[] { rdb });
}
return fixtures;
}
public abstract String getName();
public abstract DocumentStore createDocumentStore(int clusterId);
public DocumentStore createDocumentStore() {
return createDocumentStore(1);
}
public boolean isAvailable() {
return true;
}
// get underlying datasource if RDB persistence
public DataSource getRDBDataSource() {
return null;
}
// return false if the multiple instances will not share the same persistence
public boolean hasSinglePersistence() {
return true;
}
public String toString() {
return getClass().getSimpleName() + ": "+ getName();
}
public void dispose() throws Exception {
}
public static class MemoryFixture extends DocumentStoreFixture {
@Override
public String getName() {
return "Memory";
}
@Override
public DocumentStore createDocumentStore(int clusterId) {
return new MemoryDocumentStore();
}
@Override
public boolean hasSinglePersistence() {
return false;
}
}
public static class RDBFixture extends DocumentStoreFixture {
DataSource dataSource;
DocumentStore store1, store2;
String name;
RDBOptions options = new RDBOptions().tablePrefix(TABLEPREFIX).dropTablesOnClose(true);
public RDBFixture() {
// default RDB fixture
this("RDB-H2(file)", "jdbc:h2:file:./target/ds-test2", "sa", "");
}
public RDBFixture(String name, String url, String username, String passwd) {
this.name = name;
try {
dataSource = new RDBDataSourceWrapper(RDBDataSourceFactory.forJdbcUrl(url, username, passwd));
} catch (Exception ex) {
LOG.info("Database instance not available at " + url + ", skipping tests...", ex);
}
}
@Override
public String getName() {
return name;
}
@Override
public DocumentStore createDocumentStore(int clusterId) {
if (clusterId == 1) {
store1 = new RDBDocumentStore(dataSource, new DocumentMK.Builder().setClusterId(1), options);
return store1;
} else if (clusterId == 2) {
store2 = new RDBDocumentStore(dataSource, new DocumentMK.Builder().setClusterId(2), options);
return store2;
} else {
throw new RuntimeException("expect clusterId == 1 or == 2");
}
}
@Override
public boolean isAvailable() {
return dataSource != null;
}
@Override
public DataSource getRDBDataSource() {
return dataSource;
}
@Override
public void dispose() {
if (dataSource instanceof Closeable) {
try {
((Closeable)dataSource).close();
}
catch (IOException ignored) {
}
}
}
}
public static class MongoFixture extends DocumentStoreFixture {
private List<MongoConnection> connections = Lists.newArrayList();
@Override
public String getName() {
return "MongoDB";
}
@Override
public DocumentStore createDocumentStore(int clusterId) {
try {
MongoConnection connection = MongoUtils.getConnection();
connections.add(connection);
DB db = connection.getDB();
return new MongoDocumentStore(db, new DocumentMK.Builder().setClusterId(clusterId));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public boolean isAvailable() {
return MongoUtils.isAvailable();
}
@Override
public void dispose() {
try {
MongoUtils.dropCollections(MongoUtils.DB);
} catch (Exception ignore) {
}
for (MongoConnection c : connections) {
c.close();
}
connections.clear();
}
}
}
| oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/DocumentStoreFixture.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.document;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import javax.sql.DataSource;
import org.apache.jackrabbit.oak.commons.FixturesHelper;
import org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore;
import org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore;
import org.apache.jackrabbit.oak.plugins.document.rdb.RDBDataSourceFactory;
import org.apache.jackrabbit.oak.plugins.document.rdb.RDBDataSourceWrapper;
import org.apache.jackrabbit.oak.plugins.document.rdb.RDBDocumentStore;
import org.apache.jackrabbit.oak.plugins.document.rdb.RDBOptions;
import org.apache.jackrabbit.oak.plugins.document.util.MongoConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.mongodb.DB;
import static org.apache.jackrabbit.oak.commons.FixturesHelper.Fixture.DOCUMENT_MEM;
import static org.apache.jackrabbit.oak.commons.FixturesHelper.Fixture.DOCUMENT_NS;
import static org.apache.jackrabbit.oak.commons.FixturesHelper.Fixture.DOCUMENT_RDB;
public abstract class DocumentStoreFixture {
private static final Logger LOG = LoggerFactory.getLogger(DocumentStoreFixture.class);
public static final DocumentStoreFixture MEMORY = new MemoryFixture();
public static final DocumentStoreFixture MONGO = new MongoFixture();
public static final DocumentStoreFixture RDB_DB2 = new RDBFixture("RDB-DB2", System.getProperty("rdb-db2-jdbc-url",
"jdbc:db2://localhost:50000/OAK"), System.getProperty("rdb-db2-jdbc-user", "oak"), System.getProperty(
"rdb-db2-jdbc-passwd", "geheim"));
public static final DocumentStoreFixture RDB_DERBY = new RDBFixture("RDB-Derby(embedded)", System.getProperty(
"rdb-derby-jdbc-url", "jdbc:derby:./target/derby-ds-test;create=true"),
System.getProperty("rdb-derby-jdbc-user", "sa"), System.getProperty("rdb-derby-jdbc-passwd", ""));
public static final DocumentStoreFixture RDB_H2 = new RDBFixture("RDB-H2(file)", System.getProperty("rdb-h2-jdbc-url",
"jdbc:h2:file:./target/h2-ds-test"), System.getProperty("rdb-h2-jdbc-user", "sa"), System.getProperty(
"rdb-h2-jdbc-passwd", ""));
public static final DocumentStoreFixture RDB_MSSQL = new RDBFixture("RDB-MSSql", System.getProperty("rdb-mssql-jdbc-url",
"jdbc:sqlserver://localhost:1433;databaseName=OAK"), System.getProperty("rdb-mssql-jdbc-user", "sa"),
System.getProperty("rdb-mssql-jdbc-passwd", "geheim"));
public static final DocumentStoreFixture RDB_MYSQL = new RDBFixture("RDB-MySQL", System.getProperty("rdb-mysql-jdbc-url",
"jdbc:mysql://localhost:3306/oak"), System.getProperty("rdb-mysql-jdbc-user", "root"), System.getProperty(
"rdb-mysql-jdbc-passwd", "geheim"));
public static final DocumentStoreFixture RDB_ORACLE = new RDBFixture("RDB-Oracle", System.getProperty("rdb-oracle-jdbc-url",
"jdbc:oracle:thin:@localhost:1521:orcl"), System.getProperty("rdb-oracle-jdbc-user", "system"), System.getProperty(
"rdb-oracle-jdbc-passwd", "geheim"));
public static final DocumentStoreFixture RDB_PG = new RDBFixture("RDB-Postgres", System.getProperty("rdb-postgres-jdbc-url",
"jdbc:postgresql:oak"), System.getProperty("rdb-postgres-jdbc-user", "postgres"), System.getProperty(
"rdb-postgres-jdbc-passwd", "geheim"));
public static final String TABLEPREFIX = "dstest_";
public static List<Object[]> getFixtures() {
List<Object[]> fixtures = Lists.newArrayList();
if (FixturesHelper.getFixtures().contains(DOCUMENT_MEM)) {
fixtures.add(new Object[] { new DocumentStoreFixture.MemoryFixture() });
}
DocumentStoreFixture mongo = new DocumentStoreFixture.MongoFixture();
if (FixturesHelper.getFixtures().contains(DOCUMENT_NS) && mongo.isAvailable()) {
fixtures.add(new Object[] { mongo });
}
DocumentStoreFixture rdb = new DocumentStoreFixture.RDBFixture();
if (FixturesHelper.getFixtures().contains(DOCUMENT_RDB) && rdb.isAvailable()) {
fixtures.add(new Object[] { rdb });
}
return fixtures;
}
public abstract String getName();
public abstract DocumentStore createDocumentStore(int clusterId);
public DocumentStore createDocumentStore() {
return createDocumentStore(1);
}
public boolean isAvailable() {
return true;
}
// get underlying datasource if RDB persistence
public DataSource getRDBDataSource() {
return null;
}
// return false if the multiple instances will not share the same persistence
public boolean hasSinglePersistence() {
return true;
}
public String toString() {
return getClass().getSimpleName() + ": "+ getName();
}
public void dispose() throws Exception {
}
public static class MemoryFixture extends DocumentStoreFixture {
@Override
public String getName() {
return "Memory";
}
@Override
public DocumentStore createDocumentStore(int clusterId) {
return new MemoryDocumentStore();
}
@Override
public boolean hasSinglePersistence() {
return false;
}
}
public static class RDBFixture extends DocumentStoreFixture {
DataSource dataSource;
DocumentStore store1, store2;
String name;
RDBOptions options = new RDBOptions().tablePrefix(TABLEPREFIX).dropTablesOnClose(true);
public RDBFixture() {
// default RDB fixture
this("RDB-H2(file)", "jdbc:h2:file:./target/ds-test2", "sa", "");
}
public RDBFixture(String name, String url, String username, String passwd) {
this.name = name;
try {
dataSource = new RDBDataSourceWrapper(RDBDataSourceFactory.forJdbcUrl(url, username, passwd));
} catch (Exception ex) {
LOG.info("Database instance not available at " + url + ", skipping tests...", ex);
}
}
@Override
public String getName() {
return name;
}
@Override
public DocumentStore createDocumentStore(int clusterId) {
if (clusterId == 1) {
store1 = new RDBDocumentStore(dataSource, new DocumentMK.Builder().setClusterId(1), options);
return store1;
} else if (clusterId == 2) {
store2 = new RDBDocumentStore(dataSource, new DocumentMK.Builder().setClusterId(2), options);
return store2;
} else {
throw new RuntimeException("expect clusterId == 1 or == 2");
}
}
@Override
public boolean isAvailable() {
return dataSource != null;
}
@Override
public DataSource getRDBDataSource() {
return dataSource;
}
@Override
public void dispose() {
if (dataSource instanceof Closeable) {
try {
((Closeable)dataSource).close();
}
catch (IOException ignored) {
}
}
}
}
public static class MongoFixture extends DocumentStoreFixture {
private String uri = MongoUtils.URL;
private List<MongoConnection> connections = Lists.newArrayList();
@Override
public String getName() {
return "MongoDB";
}
@Override
public DocumentStore createDocumentStore(int clusterId) {
try {
MongoConnection connection = new MongoConnection(uri);
connections.add(connection);
DB db = connection.getDB();
return new MongoDocumentStore(db, new DocumentMK.Builder().setClusterId(clusterId));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public boolean isAvailable() {
return MongoUtils.isAvailable();
}
@Override
public void dispose() {
try {
MongoConnection connection = new MongoConnection(uri);
try {
connection.getDB().dropDatabase();
} finally {
connection.close();
}
} catch (Exception ignore) {
}
for (MongoConnection c : connections) {
c.close();
}
connections.clear();
}
}
}
| OAK-4973: Speed up tests with MongoFixture
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1765972 13f79535-47bb-0310-9956-ffa450edef68
| oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/DocumentStoreFixture.java | OAK-4973: Speed up tests with MongoFixture |
|
Java | apache-2.0 | 6a0e10cd35732d071eb38d039c55693cacdeeea0 | 0 | spotify/styx,spotify/styx,spotify/styx | /*-
* -\-\-
* Spotify Styx Scheduler Service
* --
* Copyright (C) 2016 Spotify AB
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/
package com.spotify.styx.docker;
import static com.spotify.styx.docker.KubernetesPodEventTranslator.hasPullImageError;
import static com.spotify.styx.docker.KubernetesPodEventTranslator.translate;
import static com.spotify.styx.serialization.Json.OBJECT_MAPPER;
import static com.spotify.styx.state.RunState.State.RUNNING;
import static java.util.stream.Collectors.toSet;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.rholder.retry.Attempt;
import com.github.rholder.retry.RetryException;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.spotify.styx.model.Event;
import com.spotify.styx.model.EventVisitor;
import com.spotify.styx.model.ExecutionDescription;
import com.spotify.styx.model.WorkflowConfiguration;
import com.spotify.styx.model.WorkflowInstance;
import com.spotify.styx.monitoring.Stats;
import com.spotify.styx.state.Message;
import com.spotify.styx.state.RunState;
import com.spotify.styx.state.StateManager;
import com.spotify.styx.state.Trigger;
import com.spotify.styx.util.Debug;
import com.spotify.styx.util.EventUtil;
import com.spotify.styx.util.IsClosedException;
import com.spotify.styx.util.Time;
import com.spotify.styx.util.TriggerUtil;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.ContainerBuilder;
import io.fabric8.kubernetes.api.model.ContainerStatus;
import io.fabric8.kubernetes.api.model.EnvVar;
import io.fabric8.kubernetes.api.model.EnvVarBuilder;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.PodList;
import io.fabric8.kubernetes.api.model.PodSpecBuilder;
import io.fabric8.kubernetes.api.model.Quantity;
import io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretVolumeSource;
import io.fabric8.kubernetes.api.model.SecretVolumeSourceBuilder;
import io.fabric8.kubernetes.api.model.Volume;
import io.fabric8.kubernetes.api.model.VolumeBuilder;
import io.fabric8.kubernetes.api.model.VolumeMount;
import io.fabric8.kubernetes.api.model.VolumeMountBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.kubernetes.client.Watch;
import io.fabric8.kubernetes.client.Watcher;
import io.norberg.automatter.AutoMatter;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* A {@link DockerRunner} implementation that submits container executions to a Kubernetes cluster.
*/
class KubernetesDockerRunner implements DockerRunner {
static final String STYX_WORKFLOW_INSTANCE_ANNOTATION = "styx-workflow-instance";
static final String DOCKER_TERMINATION_LOGGING_ANNOTATION = "styx-docker-termination-logging";
static final String COMPONENT_ID = "STYX_COMPONENT_ID";
static final String WORKFLOW_ID = "STYX_WORKFLOW_ID";
static final String SERVICE_ACCOUNT = "STYX_SERVICE_ACCOUNT";
static final String DOCKER_ARGS = "STYX_DOCKER_ARGS";
static final String DOCKER_IMAGE = "STYX_DOCKER_IMAGE";
static final String COMMIT_SHA = "STYX_COMMIT_SHA";
static final String PARAMETER = "STYX_PARAMETER";
static final String EXECUTION_ID = "STYX_EXECUTION_ID";
static final String TERMINATION_LOG = "STYX_TERMINATION_LOG";
static final String TRIGGER_ID = "STYX_TRIGGER_ID";
static final String TRIGGER_TYPE = "STYX_TRIGGER_TYPE";
private static final int DEFAULT_POLL_PODS_INTERVAL_SECONDS = 60;
private static final int DEFAULT_POD_DELETION_DELAY_SECONDS = 120;
private static final Time DEFAULT_TIME = Instant::now;
static final String STYX_WORKFLOW_SA_ENV_VARIABLE = "GOOGLE_APPLICATION_CREDENTIALS";
static final String STYX_WORKFLOW_SA_SECRET_NAME = "styx-wf-sa-keys";
private static final String STYX_WORKFLOW_SA_JSON_KEY = "styx-wf-sa.json";
static final String STYX_WORKFLOW_SA_SECRET_MOUNT_PATH =
"/etc/" + STYX_WORKFLOW_SA_SECRET_NAME + "/";
private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("k8s-scheduler-thread-%d")
.build();
static final String KEEPALIVE_CONTAINER_NAME = "keepalive";
private final ScheduledExecutorService executor;
private final KubernetesClient client;
private final StateManager stateManager;
private final Stats stats;
private final KubernetesGCPServiceAccountSecretManager serviceAccountSecretManager;
private final Debug debug;
private final int pollPodsIntervalSeconds;
private final int podDeletionDelaySeconds;
private final Time time;
private Watch watch;
KubernetesDockerRunner(NamespacedKubernetesClient client, StateManager stateManager, Stats stats,
KubernetesGCPServiceAccountSecretManager serviceAccountSecretManager,
Debug debug, int pollPodsIntervalSeconds, int podDeletionDelaySeconds,
Time time, ScheduledExecutorService executor) {
this.stateManager = Objects.requireNonNull(stateManager);
this.client = Objects.requireNonNull(client);
this.stats = Objects.requireNonNull(stats);
this.serviceAccountSecretManager = Objects.requireNonNull(serviceAccountSecretManager);
this.debug = debug;
this.pollPodsIntervalSeconds = pollPodsIntervalSeconds;
this.podDeletionDelaySeconds = podDeletionDelaySeconds;
this.time = Objects.requireNonNull(time);
this.executor = Objects.requireNonNull(executor);
}
KubernetesDockerRunner(NamespacedKubernetesClient client, StateManager stateManager, Stats stats,
KubernetesGCPServiceAccountSecretManager serviceAccountSecretManager,
Debug debug) {
this(client, stateManager, stats, serviceAccountSecretManager, debug,
DEFAULT_POLL_PODS_INTERVAL_SECONDS, DEFAULT_POD_DELETION_DELAY_SECONDS, DEFAULT_TIME,
Executors.newSingleThreadScheduledExecutor(THREAD_FACTORY));
}
@Override
public void start(WorkflowInstance workflowInstance, RunSpec runSpec) throws IOException {
final KubernetesSecretSpec secretSpec = ensureSecrets(workflowInstance, runSpec);
stats.recordSubmission(runSpec.executionId());
try {
client.pods().create(createPod(workflowInstance, runSpec, secretSpec));
} catch (KubernetesClientException kce) {
throw new IOException("Failed to create Kubernetes pod", kce);
}
}
@Override
public void cleanup() throws IOException {
serviceAccountSecretManager.cleanup();
}
private KubernetesSecretSpec ensureSecrets(WorkflowInstance workflowInstance, RunSpec runSpec) {
return KubernetesSecretSpec.builder()
.customSecret(ensureCustomSecret(workflowInstance, runSpec))
.serviceAccountSecret(runSpec.serviceAccount().map(
serviceAccount ->
serviceAccountSecretManager.ensureServiceAccountKeySecret(
workflowInstance.workflowId().toString(),
serviceAccount)))
.build();
}
private Optional<WorkflowConfiguration.Secret> ensureCustomSecret(
WorkflowInstance workflowInstance, RunSpec runSpec) {
return runSpec.secret().map(specSecret -> {
if (specSecret.name().startsWith(STYX_WORKFLOW_SA_SECRET_NAME)) {
LOG.warn("[AUDIT] Workflow {} refers to secret {} with managed service account key secret name prefix, "
+ "denying execution", workflowInstance.workflowId(), specSecret.name());
throw new InvalidExecutionException(
"Referenced secret '" + specSecret.name() + "' has the managed service account key secret name prefix");
}
// if it ever happens, that feels more like a hack than pure luck so let's be paranoid
if (STYX_WORKFLOW_SA_SECRET_MOUNT_PATH.equals(specSecret.mountPath())) {
LOG.warn("[AUDIT] Workflow {} tries to mount secret {} to the reserved path",
workflowInstance.workflowId(), specSecret.name());
throw new InvalidExecutionException(
"Referenced secret '" + specSecret.name() + "' has the mount path "
+ STYX_WORKFLOW_SA_SECRET_MOUNT_PATH + " defined that is reserved");
}
final Secret secret = client.secrets().withName(specSecret.name()).get();
if (secret == null) {
LOG.warn("[AUDIT] Workflow {} refers to a non-existent secret {}",
workflowInstance.workflowId(), specSecret.name());
throw new InvalidExecutionException(
"Referenced secret '" + specSecret.name() + "' was not found");
} else {
LOG.info("[AUDIT] Workflow {} refers to secret {}",
workflowInstance.workflowId(), specSecret.name());
}
return specSecret;
});
}
@VisibleForTesting
static Pod createPod(WorkflowInstance workflowInstance, RunSpec runSpec, KubernetesSecretSpec secretSpec) {
final String imageWithTag = runSpec.imageName().contains(":")
? runSpec.imageName()
: runSpec.imageName() + ":latest";
final String executionId = runSpec.executionId();
final PodBuilder podBuilder = new PodBuilder()
.withNewMetadata()
.withName(executionId)
.addToAnnotations(STYX_WORKFLOW_INSTANCE_ANNOTATION, workflowInstance.toKey())
.addToAnnotations(DOCKER_TERMINATION_LOGGING_ANNOTATION,
String.valueOf(runSpec.terminationLogging()))
.endMetadata();
final PodSpecBuilder specBuilder = new PodSpecBuilder()
.withRestartPolicy("Never");
final ResourceRequirementsBuilder resourceRequirements = new ResourceRequirementsBuilder();
runSpec.memRequest().ifPresent(s -> resourceRequirements.addToRequests("memory", new Quantity(s)));
runSpec.memLimit().ifPresent(s -> resourceRequirements.addToLimits("memory", new Quantity(s)));
final ContainerBuilder mainContainerBuilder = new ContainerBuilder()
.withName(mainContainerName(executionId))
.withImage(imageWithTag)
.withArgs(runSpec.args())
.withEnv(buildEnv(workflowInstance, runSpec))
.withResources(resourceRequirements.build());
secretSpec.serviceAccountSecret().ifPresent(serviceAccountSecret -> {
final SecretVolumeSource saVolumeSource = new SecretVolumeSourceBuilder()
.withSecretName(serviceAccountSecret)
.build();
final Volume saVolume = new VolumeBuilder()
.withName(STYX_WORKFLOW_SA_SECRET_NAME)
.withSecret(saVolumeSource)
.build();
specBuilder.addToVolumes(saVolume);
final VolumeMount saMount = new VolumeMountBuilder()
.withMountPath(STYX_WORKFLOW_SA_SECRET_MOUNT_PATH)
.withName(saVolume.getName())
.withReadOnly(true)
.build();
mainContainerBuilder.addToVolumeMounts(saMount);
mainContainerBuilder.addToEnv(envVar(STYX_WORKFLOW_SA_ENV_VARIABLE,
saMount.getMountPath() + STYX_WORKFLOW_SA_JSON_KEY));
});
secretSpec.customSecret().ifPresent(secret -> {
final SecretVolumeSource secretVolumeSource = new SecretVolumeSourceBuilder()
.withSecretName(secret.name())
.build();
final Volume secretVolume = new VolumeBuilder()
.withName(secret.name())
.withSecret(secretVolumeSource)
.build();
specBuilder.addToVolumes(secretVolume);
final VolumeMount secretMount = new VolumeMountBuilder()
.withMountPath(secret.mountPath())
.withName(secretVolume.getName())
.withReadOnly(true)
.build();
mainContainerBuilder.addToVolumeMounts(secretMount);
});
specBuilder.addToContainers(mainContainerBuilder.build());
specBuilder.addToContainers(keepaliveContainer());
podBuilder.withSpec(specBuilder.build());
return podBuilder.build();
}
private static String mainContainerName(String executionId) {
return executionId;
}
private static Container keepaliveContainer() {
return new ContainerBuilder()
.withName(KEEPALIVE_CONTAINER_NAME)
// Use the k8s pause container image. It sleeps forever until terminated.
.withImage("k8s.gcr.io/pause:3.1")
.build();
}
@VisibleForTesting
static EnvVar envVar(String name, String value) {
return new EnvVarBuilder().withName(name).withValue(value).build();
}
private static List<EnvVar> buildEnv(WorkflowInstance workflowInstance,
RunSpec runSpec) {
return Arrays.asList(
envVar(COMPONENT_ID, workflowInstance.workflowId().componentId()),
envVar(WORKFLOW_ID, workflowInstance.workflowId().id()),
envVar(PARAMETER, workflowInstance.parameter()),
envVar(COMMIT_SHA, runSpec.commitSha().orElse("")),
envVar(SERVICE_ACCOUNT, runSpec.serviceAccount().orElse("")),
envVar(DOCKER_ARGS, String.join(" ", runSpec.args())),
envVar(DOCKER_IMAGE, runSpec.imageName()),
envVar(EXECUTION_ID, runSpec.executionId()),
envVar(TERMINATION_LOG, "/dev/termination-log"),
envVar(TRIGGER_ID, runSpec.trigger().map(TriggerUtil::triggerId).orElse(null)),
envVar(TRIGGER_TYPE, runSpec.trigger().map(TriggerUtil::triggerType).orElse(null))
);
}
@Override
public void cleanup(WorkflowInstance workflowInstance, String executionId) {
// do not cleanup pod along with state machine transition and let polling thread
// take care of it
}
@VisibleForTesting
void cleanupWithRunState(WorkflowInstance workflowInstance, String executionId) {
cleanup(workflowInstance, executionId, pod ->
getMainContainerStatus(pod).ifPresent(containerStatus -> {
if (hasPullImageError(containerStatus)) {
deletePod(workflowInstance, executionId);
} else {
if (containerStatus.getState().getTerminated() != null) {
deletePodIfNonDeletePeriodExpired(workflowInstance, executionId, containerStatus);
}
}
}));
}
@VisibleForTesting
void cleanupWithoutRunState(WorkflowInstance workflowInstance, String executionId) {
cleanup(workflowInstance, executionId, pod ->
getMainContainerStatus(pod).ifPresent(containerStatus -> {
if (containerStatus.getState().getTerminated() != null) {
deletePodIfNonDeletePeriodExpired(workflowInstance, executionId, containerStatus);
} else {
// if not terminated, delete it directly
deletePod(workflowInstance, executionId);
}
}));
}
private void deletePodIfNonDeletePeriodExpired(WorkflowInstance workflowInstance,
String executionId,
ContainerStatus containerStatus) {
if (isNonDeletePeriodExpired(containerStatus)) {
// if terminated and after graceful period, delete the pod
// otherwise wait until next polling happens
deletePod(workflowInstance, executionId);
}
}
private void cleanup(WorkflowInstance workflowInstance, String executionId,
Consumer<Pod> cleaner) {
Optional.ofNullable(client.pods().withName(executionId).get()).ifPresent(pod -> {
final List<ContainerStatus> containerStatuses = pod.getStatus().getContainerStatuses();
if (!containerStatuses.isEmpty()) {
cleaner.accept(pod);
} else {
// for some cases such as evicted pod, there is no container status, so we delete directly
deletePod(workflowInstance, executionId);
}
});
}
static Optional<ContainerStatus> getMainContainerStatus(Pod pod) {
return readPodWorkflowInstance(pod)
.flatMap(wfi -> pod.getStatus().getContainerStatuses().stream()
.filter(status -> mainContainerName(pod.getMetadata().getName()).equals(status.getName()))
.findAny());
}
private boolean isNonDeletePeriodExpired(ContainerStatus containerStatus) {
return Optional.ofNullable(containerStatus.getState().getTerminated().getFinishedAt())
.map(finishedAt -> Instant.parse(finishedAt)
.isBefore(time.get().minus(
Duration.ofSeconds(podDeletionDelaySeconds))))
.orElse(true);
}
private void deletePod(WorkflowInstance workflowInstance, String executionId) {
if (!debug.get()) {
client.pods().withName(executionId).delete();
LOG.info("Cleaned up {} pod: {}", workflowInstance.toKey(), executionId);
} else {
LOG.info("Keeping {} pod: {}", workflowInstance.toKey(), executionId);
}
}
@Override
public void close() throws IOException {
if (watch != null) {
watch.close();
}
executor.shutdown();
try {
executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOG.warn("Failed to terminate executor", e);
}
}
@Override
public void restore() {
// Failing here means restarting the styx scheduler and replaying all events again. This is
// quite time consuming and distressing when deploying, so try hard.
final Retryer<Object> retryer = RetryerBuilder.newBuilder()
.retryIfException()
.withWaitStrategy(WaitStrategies.exponentialWait(10, TimeUnit.SECONDS))
.withStopStrategy(StopStrategies.stopAfterAttempt(10))
.withRetryListener(this::onRestorePollPodsAttempt)
.build();
try {
retryer.call(Executors.callable(this::tryPollPods));
} catch (ExecutionException | RetryException e) {
throw new RuntimeException(e);
}
}
private <V> void onRestorePollPodsAttempt(Attempt<V> attempt) {
if (attempt.hasException()) {
LOG.warn("restore: failed polling pods, attempt = {}", attempt.getAttemptNumber(), attempt.getExceptionCause());
}
}
public void init() {
executor.scheduleWithFixedDelay(
this::pollPods,
pollPodsIntervalSeconds,
pollPodsIntervalSeconds,
TimeUnit.SECONDS);
watch = client.pods()
.watch(new PodWatcher());
}
private Set<WorkflowInstance> getRunningWorkflowInstances() {
return stateManager.getActiveStates()
.values()
.stream()
.filter(runState -> runState.state().equals(RUNNING))
.map(RunState::workflowInstance)
.collect(toSet());
}
private void examineRunningWFISandAssociatedPods(Set<WorkflowInstance> runningWorkflowInstances,
PodList podList) {
final Set<WorkflowInstance> workflowInstancesForPods = podList.getItems().stream()
.filter(pod -> pod.getMetadata().getAnnotations()
.containsKey(STYX_WORKFLOW_INSTANCE_ANNOTATION))
.map(pod -> WorkflowInstance
.parseKey(pod.getMetadata().getAnnotations().get(STYX_WORKFLOW_INSTANCE_ANNOTATION)))
.collect(toSet());
runningWorkflowInstances.removeAll(workflowInstancesForPods);
runningWorkflowInstances.forEach(workflowInstance -> stateManager.receiveIgnoreClosed(
Event.runError(workflowInstance, "No pod associated with this instance")));
}
@VisibleForTesting
void pollPods() {
try {
tryPollPods();
} catch (Throwable t) {
LOG.warn("Error while polling pods", t);
}
}
private synchronized void tryPollPods() {
final Set<WorkflowInstance> runningWorkflowInstances = getRunningWorkflowInstances();
final PodList list = client.pods().list();
examineRunningWFISandAssociatedPods(runningWorkflowInstances, list);
for (Pod pod : list.getItems()) {
logEvent(Watcher.Action.MODIFIED, pod, list.getMetadata().getResourceVersion(), true);
final Optional<WorkflowInstance> workflowInstance = readPodWorkflowInstance(pod);
if (!workflowInstance.isPresent()) {
continue;
}
// do an extra lookup to get latest state
// this is crucial because after fetching all states in datastore, some states might
// have transitioned already; there could even be cases that we observe pods whose
// states where created after fetching the states.
final Optional<RunState> runState = lookupPodRunState(pod, workflowInstance.get());
if (runState.isPresent()) {
emitPodEvents(Watcher.Action.MODIFIED, pod, runState.get());
cleanupWithRunState(workflowInstance.get(), pod.getMetadata().getName());
} else {
cleanupWithoutRunState(workflowInstance.get(), pod.getMetadata().getName());
}
}
}
private static Optional<WorkflowInstance> readPodWorkflowInstance(Pod pod) {
final Map<String, String> annotations = pod.getMetadata().getAnnotations();
final String podName = pod.getMetadata().getName();
if (!annotations.containsKey(KubernetesDockerRunner.STYX_WORKFLOW_INSTANCE_ANNOTATION)) {
LOG.warn("[AUDIT] Got pod without workflow instance annotation {}", podName);
return Optional.empty();
}
final WorkflowInstance workflowInstance = WorkflowInstance.parseKey(
annotations.get(KubernetesDockerRunner.STYX_WORKFLOW_INSTANCE_ANNOTATION));
return Optional.of(workflowInstance);
}
private Optional<RunState> lookupPodRunState(Pod pod, WorkflowInstance workflowInstance) {
final String podName = pod.getMetadata().getName();
final Optional<RunState> runState = stateManager.getActiveState(workflowInstance);
if (!runState.isPresent()) {
LOG.debug("Pod event for unknown or inactive workflow instance {}", workflowInstance);
return Optional.empty();
}
final Optional<String> executionIdOpt = runState.get().data().executionId();
if (!executionIdOpt.isPresent()) {
LOG.debug("Pod event for state with no current executionId: {}", podName);
return Optional.empty();
}
final String executionId = executionIdOpt.get();
if (!podName.equals(executionId)) {
LOG.debug("Pod event not matching current exec id, current:{} != pod:{}",
executionId, podName);
return Optional.empty();
}
return runState;
}
private void emitPodEvents(Watcher.Action action, Pod pod, RunState runState) {
final List<Event> events = translate(runState.workflowInstance(), runState, action, pod, stats);
for (int i = 0; i < events.size(); ++i) {
final Event event = events.get(i);
if (event.accept(new PullImageErrorMatcher())) {
stats.recordPullImageError();
}
if (EventUtil.name(event).equals("started")) {
runState.data().executionId().ifPresent(stats::recordRunning);
}
try {
stateManager.receive(event, runState.counter() + i);
} catch (IsClosedException isClosedException) {
LOG.warn("Could not receive kubernetes event", isClosedException);
throw new RuntimeException(isClosedException);
}
}
}
private void logEvent(Watcher.Action action, Pod pod, String resourceVersion,
boolean polled) {
final String podName = pod.getMetadata().getName();
final String workflowInstance = pod.getMetadata().getAnnotations()
.getOrDefault(KubernetesDockerRunner.STYX_WORKFLOW_INSTANCE_ANNOTATION, "N/A");
final String status = readStatus(pod);
LOG.info("{}Pod event for {} ({}) at resource version {}, action: {}, workflow instance: {}, status: {}",
polled ? "Polled: " : "", podName, pod.getMetadata().getUid(), resourceVersion, action, workflowInstance,
status);
}
private String readStatus(Pod pod) {
try {
return OBJECT_MAPPER.writeValueAsString(pod.getStatus());
} catch (JsonProcessingException e) {
return pod.getStatus().toString();
}
}
public class PodWatcher implements Watcher<Pod> {
private static final int RECONNECT_DELAY_SECONDS = 1;
@Override
public void eventReceived(Action action, Pod pod) {
if (pod == null) {
return;
}
logEvent(action, pod, pod.getMetadata().getResourceVersion(), false);
readPodWorkflowInstance(pod)
.flatMap(workflowInstance -> lookupPodRunState(pod, workflowInstance))
.ifPresent(runState -> emitPodEvents(action, pod, runState));
}
private void reconnect() {
LOG.warn("Re-establishing pod watcher");
try {
watch = client.pods()
.watch(this);
} catch (Throwable e) {
LOG.warn("Retry threw", e);
scheduleReconnect();
}
}
private void scheduleReconnect() {
executor.schedule(this::reconnect, RECONNECT_DELAY_SECONDS, TimeUnit.SECONDS);
}
@Override
public void onClose(KubernetesClientException e) {
LOG.warn("Watch closed", e);
scheduleReconnect();
}
}
// fixme: add a Cause enum to the runError() event instead of this string matching
private static class PullImageErrorMatcher implements EventVisitor<Boolean> {
@Override
public Boolean timeTrigger(WorkflowInstance workflowInstance) {
return false;
}
@Override
public Boolean triggerExecution(WorkflowInstance workflowInstance, Trigger trigger) {
return false;
}
@Override
public Boolean info(WorkflowInstance workflowInstance, Message message) {
return false;
}
@Override
public Boolean dequeue(WorkflowInstance workflowInstance, Set<String> resourceIds) {
return false;
}
@Override
public Boolean created(WorkflowInstance workflowInstance, String executionId, String dockerImage) {
return false;
}
@Override
public Boolean submit(WorkflowInstance workflowInstance, ExecutionDescription executionDescription,
String executionId) {
return false;
}
@Override
public Boolean submitted(WorkflowInstance workflowInstance, String executionId) {
return false;
}
@Override
public Boolean started(WorkflowInstance workflowInstance) {
return false;
}
@Override
public Boolean terminate(WorkflowInstance workflowInstance, Optional<Integer> exitCode) {
return false;
}
@Override
public Boolean runError(WorkflowInstance workflowInstance, String message) {
return message.contains("failed to pull");
}
@Override
public Boolean success(WorkflowInstance workflowInstance) {
return false;
}
@Override
public Boolean retryAfter(WorkflowInstance workflowInstance, long delayMillis) {
return false;
}
@Override
public Boolean retry(WorkflowInstance workflowInstance) {
return false;
}
@Override
public Boolean stop(WorkflowInstance workflowInstance) {
return false;
}
@Override
public Boolean timeout(WorkflowInstance workflowInstance) {
return false;
}
@Override
public Boolean halt(WorkflowInstance workflowInstance) {
return false;
}
}
@AutoMatter
interface KubernetesSecretSpec {
Optional<WorkflowConfiguration.Secret> customSecret();
Optional<String> serviceAccountSecret();
static KubernetesSecretSpecBuilder builder() {
return new KubernetesSecretSpecBuilder();
}
}
}
| styx-scheduler-service/src/main/java/com/spotify/styx/docker/KubernetesDockerRunner.java | /*-
* -\-\-
* Spotify Styx Scheduler Service
* --
* Copyright (C) 2016 Spotify AB
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/
package com.spotify.styx.docker;
import static com.spotify.styx.docker.KubernetesPodEventTranslator.hasPullImageError;
import static com.spotify.styx.docker.KubernetesPodEventTranslator.translate;
import static com.spotify.styx.serialization.Json.OBJECT_MAPPER;
import static com.spotify.styx.state.RunState.State.RUNNING;
import static java.util.stream.Collectors.toSet;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.rholder.retry.Attempt;
import com.github.rholder.retry.RetryException;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.spotify.styx.model.Event;
import com.spotify.styx.model.EventVisitor;
import com.spotify.styx.model.ExecutionDescription;
import com.spotify.styx.model.WorkflowConfiguration;
import com.spotify.styx.model.WorkflowInstance;
import com.spotify.styx.monitoring.Stats;
import com.spotify.styx.state.Message;
import com.spotify.styx.state.RunState;
import com.spotify.styx.state.StateManager;
import com.spotify.styx.state.Trigger;
import com.spotify.styx.util.Debug;
import com.spotify.styx.util.EventUtil;
import com.spotify.styx.util.IsClosedException;
import com.spotify.styx.util.Time;
import com.spotify.styx.util.TriggerUtil;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.ContainerBuilder;
import io.fabric8.kubernetes.api.model.ContainerStatus;
import io.fabric8.kubernetes.api.model.EnvVar;
import io.fabric8.kubernetes.api.model.EnvVarBuilder;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.PodList;
import io.fabric8.kubernetes.api.model.PodSpecBuilder;
import io.fabric8.kubernetes.api.model.Quantity;
import io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretVolumeSource;
import io.fabric8.kubernetes.api.model.SecretVolumeSourceBuilder;
import io.fabric8.kubernetes.api.model.Volume;
import io.fabric8.kubernetes.api.model.VolumeBuilder;
import io.fabric8.kubernetes.api.model.VolumeMount;
import io.fabric8.kubernetes.api.model.VolumeMountBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.kubernetes.client.Watch;
import io.fabric8.kubernetes.client.Watcher;
import io.norberg.automatter.AutoMatter;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* A {@link DockerRunner} implementation that submits container executions to a Kubernetes cluster.
*/
class KubernetesDockerRunner implements DockerRunner {
static final String STYX_WORKFLOW_INSTANCE_ANNOTATION = "styx-workflow-instance";
static final String DOCKER_TERMINATION_LOGGING_ANNOTATION = "styx-docker-termination-logging";
static final String COMPONENT_ID = "STYX_COMPONENT_ID";
static final String WORKFLOW_ID = "STYX_WORKFLOW_ID";
static final String SERVICE_ACCOUNT = "STYX_SERVICE_ACCOUNT";
static final String DOCKER_ARGS = "STYX_DOCKER_ARGS";
static final String DOCKER_IMAGE = "STYX_DOCKER_IMAGE";
static final String COMMIT_SHA = "STYX_COMMIT_SHA";
static final String PARAMETER = "STYX_PARAMETER";
static final String EXECUTION_ID = "STYX_EXECUTION_ID";
static final String TERMINATION_LOG = "STYX_TERMINATION_LOG";
static final String TRIGGER_ID = "STYX_TRIGGER_ID";
static final String TRIGGER_TYPE = "STYX_TRIGGER_TYPE";
private static final int DEFAULT_POLL_PODS_INTERVAL_SECONDS = 60;
private static final int DEFAULT_POD_DELETION_DELAY_SECONDS = 120;
private static final Time DEFAULT_TIME = Instant::now;
static final String STYX_WORKFLOW_SA_ENV_VARIABLE = "GOOGLE_APPLICATION_CREDENTIALS";
static final String STYX_WORKFLOW_SA_SECRET_NAME = "styx-wf-sa-keys";
private static final String STYX_WORKFLOW_SA_JSON_KEY = "styx-wf-sa.json";
static final String STYX_WORKFLOW_SA_SECRET_MOUNT_PATH =
"/etc/" + STYX_WORKFLOW_SA_SECRET_NAME + "/";
private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("k8s-scheduler-thread-%d")
.build();
static final String KEEPALIVE_CONTAINER_NAME = "keepalive";
private final ScheduledExecutorService executor;
private final KubernetesClient client;
private final StateManager stateManager;
private final Stats stats;
private final KubernetesGCPServiceAccountSecretManager serviceAccountSecretManager;
private final Debug debug;
private final int pollPodsIntervalSeconds;
private final int podDeletionDelaySeconds;
private final Time time;
private Watch watch;
KubernetesDockerRunner(NamespacedKubernetesClient client, StateManager stateManager, Stats stats,
KubernetesGCPServiceAccountSecretManager serviceAccountSecretManager,
Debug debug, int pollPodsIntervalSeconds, int podDeletionDelaySeconds,
Time time, ScheduledExecutorService executor) {
this.stateManager = Objects.requireNonNull(stateManager);
this.client = Objects.requireNonNull(client);
this.stats = Objects.requireNonNull(stats);
this.serviceAccountSecretManager = Objects.requireNonNull(serviceAccountSecretManager);
this.debug = debug;
this.pollPodsIntervalSeconds = pollPodsIntervalSeconds;
this.podDeletionDelaySeconds = podDeletionDelaySeconds;
this.time = Objects.requireNonNull(time);
this.executor = Objects.requireNonNull(executor);
}
KubernetesDockerRunner(NamespacedKubernetesClient client, StateManager stateManager, Stats stats,
KubernetesGCPServiceAccountSecretManager serviceAccountSecretManager,
Debug debug) {
this(client, stateManager, stats, serviceAccountSecretManager, debug,
DEFAULT_POLL_PODS_INTERVAL_SECONDS, DEFAULT_POD_DELETION_DELAY_SECONDS, DEFAULT_TIME,
Executors.newSingleThreadScheduledExecutor(THREAD_FACTORY));
}
@Override
public void start(WorkflowInstance workflowInstance, RunSpec runSpec) throws IOException {
final KubernetesSecretSpec secretSpec = ensureSecrets(workflowInstance, runSpec);
stats.recordSubmission(runSpec.executionId());
try {
client.pods().create(createPod(workflowInstance, runSpec, secretSpec));
} catch (KubernetesClientException kce) {
throw new IOException("Failed to create Kubernetes pod", kce);
}
}
@Override
public void cleanup() throws IOException {
serviceAccountSecretManager.cleanup();
}
private KubernetesSecretSpec ensureSecrets(WorkflowInstance workflowInstance, RunSpec runSpec) {
return KubernetesSecretSpec.builder()
.customSecret(ensureCustomSecret(workflowInstance, runSpec))
.serviceAccountSecret(runSpec.serviceAccount().map(
serviceAccount ->
serviceAccountSecretManager.ensureServiceAccountKeySecret(
workflowInstance.workflowId().toString(),
serviceAccount)))
.build();
}
private Optional<WorkflowConfiguration.Secret> ensureCustomSecret(
WorkflowInstance workflowInstance, RunSpec runSpec) {
return runSpec.secret().map(specSecret -> {
if (specSecret.name().startsWith(STYX_WORKFLOW_SA_SECRET_NAME)) {
LOG.warn("[AUDIT] Workflow {} refers to secret {} with managed service account key secret name prefix, "
+ "denying execution", workflowInstance.workflowId(), specSecret.name());
throw new InvalidExecutionException(
"Referenced secret '" + specSecret.name() + "' has the managed service account key secret name prefix");
}
// if it ever happens, that feels more like a hack than pure luck so let's be paranoid
if (STYX_WORKFLOW_SA_SECRET_MOUNT_PATH.equals(specSecret.mountPath())) {
LOG.warn("[AUDIT] Workflow {} tries to mount secret {} to the reserved path",
workflowInstance.workflowId(), specSecret.name());
throw new InvalidExecutionException(
"Referenced secret '" + specSecret.name() + "' has the mount path "
+ STYX_WORKFLOW_SA_SECRET_MOUNT_PATH + " defined that is reserved");
}
final Secret secret = client.secrets().withName(specSecret.name()).get();
if (secret == null) {
LOG.warn("[AUDIT] Workflow {} refers to a non-existent secret {}",
workflowInstance.workflowId(), specSecret.name());
throw new InvalidExecutionException(
"Referenced secret '" + specSecret.name() + "' was not found");
} else {
LOG.info("[AUDIT] Workflow {} refers to secret {}",
workflowInstance.workflowId(), specSecret.name());
}
return specSecret;
});
}
@VisibleForTesting
static Pod createPod(WorkflowInstance workflowInstance, RunSpec runSpec, KubernetesSecretSpec secretSpec) {
final String imageWithTag = runSpec.imageName().contains(":")
? runSpec.imageName()
: runSpec.imageName() + ":latest";
final String executionId = runSpec.executionId();
final PodBuilder podBuilder = new PodBuilder()
.withNewMetadata()
.withName(executionId)
.addToAnnotations(STYX_WORKFLOW_INSTANCE_ANNOTATION, workflowInstance.toKey())
.addToAnnotations(DOCKER_TERMINATION_LOGGING_ANNOTATION,
String.valueOf(runSpec.terminationLogging()))
.endMetadata();
final PodSpecBuilder specBuilder = new PodSpecBuilder()
.withRestartPolicy("Never");
final ResourceRequirementsBuilder resourceRequirements = new ResourceRequirementsBuilder();
runSpec.memRequest().ifPresent(s -> resourceRequirements.addToRequests("memory", new Quantity(s)));
runSpec.memLimit().ifPresent(s -> resourceRequirements.addToLimits("memory", new Quantity(s)));
final ContainerBuilder mainContainerBuilder = new ContainerBuilder()
.withName(mainContainerName(executionId))
.withImage(imageWithTag)
.withArgs(runSpec.args())
.withEnv(buildEnv(workflowInstance, runSpec))
.withResources(resourceRequirements.build());
secretSpec.serviceAccountSecret().ifPresent(serviceAccountSecret -> {
final SecretVolumeSource saVolumeSource = new SecretVolumeSourceBuilder()
.withSecretName(serviceAccountSecret)
.build();
final Volume saVolume = new VolumeBuilder()
.withName(STYX_WORKFLOW_SA_SECRET_NAME)
.withSecret(saVolumeSource)
.build();
specBuilder.addToVolumes(saVolume);
final VolumeMount saMount = new VolumeMountBuilder()
.withMountPath(STYX_WORKFLOW_SA_SECRET_MOUNT_PATH)
.withName(saVolume.getName())
.withReadOnly(true)
.build();
mainContainerBuilder.addToVolumeMounts(saMount);
mainContainerBuilder.addToEnv(envVar(STYX_WORKFLOW_SA_ENV_VARIABLE,
saMount.getMountPath() + STYX_WORKFLOW_SA_JSON_KEY));
});
secretSpec.customSecret().ifPresent(secret -> {
final SecretVolumeSource secretVolumeSource = new SecretVolumeSourceBuilder()
.withSecretName(secret.name())
.build();
final Volume secretVolume = new VolumeBuilder()
.withName(secret.name())
.withSecret(secretVolumeSource)
.build();
specBuilder.addToVolumes(secretVolume);
final VolumeMount secretMount = new VolumeMountBuilder()
.withMountPath(secret.mountPath())
.withName(secretVolume.getName())
.withReadOnly(true)
.build();
mainContainerBuilder.addToVolumeMounts(secretMount);
});
specBuilder.addToContainers(mainContainerBuilder.build());
specBuilder.addToContainers(keepaliveContainer());
podBuilder.withSpec(specBuilder.build());
return podBuilder.build();
}
private static String mainContainerName(String executionId) {
return executionId;
}
private static Container keepaliveContainer() {
return new ContainerBuilder()
.withName(KEEPALIVE_CONTAINER_NAME)
// Use the GKE pause container image. It sleeps forever until terminated.
.withImage("gcr.io/google-containers/pause"
+ "@sha256:f78411e19d84a252e53bff71a4407a5686c46983a2c2eeed83929b888179acea")
.build();
}
@VisibleForTesting
static EnvVar envVar(String name, String value) {
return new EnvVarBuilder().withName(name).withValue(value).build();
}
private static List<EnvVar> buildEnv(WorkflowInstance workflowInstance,
RunSpec runSpec) {
return Arrays.asList(
envVar(COMPONENT_ID, workflowInstance.workflowId().componentId()),
envVar(WORKFLOW_ID, workflowInstance.workflowId().id()),
envVar(PARAMETER, workflowInstance.parameter()),
envVar(COMMIT_SHA, runSpec.commitSha().orElse("")),
envVar(SERVICE_ACCOUNT, runSpec.serviceAccount().orElse("")),
envVar(DOCKER_ARGS, String.join(" ", runSpec.args())),
envVar(DOCKER_IMAGE, runSpec.imageName()),
envVar(EXECUTION_ID, runSpec.executionId()),
envVar(TERMINATION_LOG, "/dev/termination-log"),
envVar(TRIGGER_ID, runSpec.trigger().map(TriggerUtil::triggerId).orElse(null)),
envVar(TRIGGER_TYPE, runSpec.trigger().map(TriggerUtil::triggerType).orElse(null))
);
}
@Override
public void cleanup(WorkflowInstance workflowInstance, String executionId) {
// do not cleanup pod along with state machine transition and let polling thread
// take care of it
}
@VisibleForTesting
void cleanupWithRunState(WorkflowInstance workflowInstance, String executionId) {
cleanup(workflowInstance, executionId, pod ->
getMainContainerStatus(pod).ifPresent(containerStatus -> {
if (hasPullImageError(containerStatus)) {
deletePod(workflowInstance, executionId);
} else {
if (containerStatus.getState().getTerminated() != null) {
deletePodIfNonDeletePeriodExpired(workflowInstance, executionId, containerStatus);
}
}
}));
}
@VisibleForTesting
void cleanupWithoutRunState(WorkflowInstance workflowInstance, String executionId) {
cleanup(workflowInstance, executionId, pod ->
getMainContainerStatus(pod).ifPresent(containerStatus -> {
if (containerStatus.getState().getTerminated() != null) {
deletePodIfNonDeletePeriodExpired(workflowInstance, executionId, containerStatus);
} else {
// if not terminated, delete it directly
deletePod(workflowInstance, executionId);
}
}));
}
private void deletePodIfNonDeletePeriodExpired(WorkflowInstance workflowInstance,
String executionId,
ContainerStatus containerStatus) {
if (isNonDeletePeriodExpired(containerStatus)) {
// if terminated and after graceful period, delete the pod
// otherwise wait until next polling happens
deletePod(workflowInstance, executionId);
}
}
private void cleanup(WorkflowInstance workflowInstance, String executionId,
Consumer<Pod> cleaner) {
Optional.ofNullable(client.pods().withName(executionId).get()).ifPresent(pod -> {
final List<ContainerStatus> containerStatuses = pod.getStatus().getContainerStatuses();
if (!containerStatuses.isEmpty()) {
cleaner.accept(pod);
} else {
// for some cases such as evicted pod, there is no container status, so we delete directly
deletePod(workflowInstance, executionId);
}
});
}
static Optional<ContainerStatus> getMainContainerStatus(Pod pod) {
return readPodWorkflowInstance(pod)
.flatMap(wfi -> pod.getStatus().getContainerStatuses().stream()
.filter(status -> mainContainerName(pod.getMetadata().getName()).equals(status.getName()))
.findAny());
}
private boolean isNonDeletePeriodExpired(ContainerStatus containerStatus) {
return Optional.ofNullable(containerStatus.getState().getTerminated().getFinishedAt())
.map(finishedAt -> Instant.parse(finishedAt)
.isBefore(time.get().minus(
Duration.ofSeconds(podDeletionDelaySeconds))))
.orElse(true);
}
private void deletePod(WorkflowInstance workflowInstance, String executionId) {
if (!debug.get()) {
client.pods().withName(executionId).delete();
LOG.info("Cleaned up {} pod: {}", workflowInstance.toKey(), executionId);
} else {
LOG.info("Keeping {} pod: {}", workflowInstance.toKey(), executionId);
}
}
@Override
public void close() throws IOException {
if (watch != null) {
watch.close();
}
executor.shutdown();
try {
executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOG.warn("Failed to terminate executor", e);
}
}
@Override
public void restore() {
// Failing here means restarting the styx scheduler and replaying all events again. This is
// quite time consuming and distressing when deploying, so try hard.
final Retryer<Object> retryer = RetryerBuilder.newBuilder()
.retryIfException()
.withWaitStrategy(WaitStrategies.exponentialWait(10, TimeUnit.SECONDS))
.withStopStrategy(StopStrategies.stopAfterAttempt(10))
.withRetryListener(this::onRestorePollPodsAttempt)
.build();
try {
retryer.call(Executors.callable(this::tryPollPods));
} catch (ExecutionException | RetryException e) {
throw new RuntimeException(e);
}
}
private <V> void onRestorePollPodsAttempt(Attempt<V> attempt) {
if (attempt.hasException()) {
LOG.warn("restore: failed polling pods, attempt = {}", attempt.getAttemptNumber(), attempt.getExceptionCause());
}
}
public void init() {
executor.scheduleWithFixedDelay(
this::pollPods,
pollPodsIntervalSeconds,
pollPodsIntervalSeconds,
TimeUnit.SECONDS);
watch = client.pods()
.watch(new PodWatcher());
}
private Set<WorkflowInstance> getRunningWorkflowInstances() {
return stateManager.getActiveStates()
.values()
.stream()
.filter(runState -> runState.state().equals(RUNNING))
.map(RunState::workflowInstance)
.collect(toSet());
}
private void examineRunningWFISandAssociatedPods(Set<WorkflowInstance> runningWorkflowInstances,
PodList podList) {
final Set<WorkflowInstance> workflowInstancesForPods = podList.getItems().stream()
.filter(pod -> pod.getMetadata().getAnnotations()
.containsKey(STYX_WORKFLOW_INSTANCE_ANNOTATION))
.map(pod -> WorkflowInstance
.parseKey(pod.getMetadata().getAnnotations().get(STYX_WORKFLOW_INSTANCE_ANNOTATION)))
.collect(toSet());
runningWorkflowInstances.removeAll(workflowInstancesForPods);
runningWorkflowInstances.forEach(workflowInstance -> stateManager.receiveIgnoreClosed(
Event.runError(workflowInstance, "No pod associated with this instance")));
}
@VisibleForTesting
void pollPods() {
try {
tryPollPods();
} catch (Throwable t) {
LOG.warn("Error while polling pods", t);
}
}
private synchronized void tryPollPods() {
final Set<WorkflowInstance> runningWorkflowInstances = getRunningWorkflowInstances();
final PodList list = client.pods().list();
examineRunningWFISandAssociatedPods(runningWorkflowInstances, list);
for (Pod pod : list.getItems()) {
logEvent(Watcher.Action.MODIFIED, pod, list.getMetadata().getResourceVersion(), true);
final Optional<WorkflowInstance> workflowInstance = readPodWorkflowInstance(pod);
if (!workflowInstance.isPresent()) {
continue;
}
// do an extra lookup to get latest state
// this is crucial because after fetching all states in datastore, some states might
// have transitioned already; there could even be cases that we observe pods whose
// states where created after fetching the states.
final Optional<RunState> runState = lookupPodRunState(pod, workflowInstance.get());
if (runState.isPresent()) {
emitPodEvents(Watcher.Action.MODIFIED, pod, runState.get());
cleanupWithRunState(workflowInstance.get(), pod.getMetadata().getName());
} else {
cleanupWithoutRunState(workflowInstance.get(), pod.getMetadata().getName());
}
}
}
private static Optional<WorkflowInstance> readPodWorkflowInstance(Pod pod) {
final Map<String, String> annotations = pod.getMetadata().getAnnotations();
final String podName = pod.getMetadata().getName();
if (!annotations.containsKey(KubernetesDockerRunner.STYX_WORKFLOW_INSTANCE_ANNOTATION)) {
LOG.warn("[AUDIT] Got pod without workflow instance annotation {}", podName);
return Optional.empty();
}
final WorkflowInstance workflowInstance = WorkflowInstance.parseKey(
annotations.get(KubernetesDockerRunner.STYX_WORKFLOW_INSTANCE_ANNOTATION));
return Optional.of(workflowInstance);
}
private Optional<RunState> lookupPodRunState(Pod pod, WorkflowInstance workflowInstance) {
final String podName = pod.getMetadata().getName();
final Optional<RunState> runState = stateManager.getActiveState(workflowInstance);
if (!runState.isPresent()) {
LOG.debug("Pod event for unknown or inactive workflow instance {}", workflowInstance);
return Optional.empty();
}
final Optional<String> executionIdOpt = runState.get().data().executionId();
if (!executionIdOpt.isPresent()) {
LOG.debug("Pod event for state with no current executionId: {}", podName);
return Optional.empty();
}
final String executionId = executionIdOpt.get();
if (!podName.equals(executionId)) {
LOG.debug("Pod event not matching current exec id, current:{} != pod:{}",
executionId, podName);
return Optional.empty();
}
return runState;
}
private void emitPodEvents(Watcher.Action action, Pod pod, RunState runState) {
final List<Event> events = translate(runState.workflowInstance(), runState, action, pod, stats);
for (int i = 0; i < events.size(); ++i) {
final Event event = events.get(i);
if (event.accept(new PullImageErrorMatcher())) {
stats.recordPullImageError();
}
if (EventUtil.name(event).equals("started")) {
runState.data().executionId().ifPresent(stats::recordRunning);
}
try {
stateManager.receive(event, runState.counter() + i);
} catch (IsClosedException isClosedException) {
LOG.warn("Could not receive kubernetes event", isClosedException);
throw new RuntimeException(isClosedException);
}
}
}
private void logEvent(Watcher.Action action, Pod pod, String resourceVersion,
boolean polled) {
final String podName = pod.getMetadata().getName();
final String workflowInstance = pod.getMetadata().getAnnotations()
.getOrDefault(KubernetesDockerRunner.STYX_WORKFLOW_INSTANCE_ANNOTATION, "N/A");
final String status = readStatus(pod);
LOG.info("{}Pod event for {} ({}) at resource version {}, action: {}, workflow instance: {}, status: {}",
polled ? "Polled: " : "", podName, pod.getMetadata().getUid(), resourceVersion, action, workflowInstance,
status);
}
private String readStatus(Pod pod) {
try {
return OBJECT_MAPPER.writeValueAsString(pod.getStatus());
} catch (JsonProcessingException e) {
return pod.getStatus().toString();
}
}
public class PodWatcher implements Watcher<Pod> {
private static final int RECONNECT_DELAY_SECONDS = 1;
@Override
public void eventReceived(Action action, Pod pod) {
if (pod == null) {
return;
}
logEvent(action, pod, pod.getMetadata().getResourceVersion(), false);
readPodWorkflowInstance(pod)
.flatMap(workflowInstance -> lookupPodRunState(pod, workflowInstance))
.ifPresent(runState -> emitPodEvents(action, pod, runState));
}
private void reconnect() {
LOG.warn("Re-establishing pod watcher");
try {
watch = client.pods()
.watch(this);
} catch (Throwable e) {
LOG.warn("Retry threw", e);
scheduleReconnect();
}
}
private void scheduleReconnect() {
executor.schedule(this::reconnect, RECONNECT_DELAY_SECONDS, TimeUnit.SECONDS);
}
@Override
public void onClose(KubernetesClientException e) {
LOG.warn("Watch closed", e);
scheduleReconnect();
}
}
// fixme: add a Cause enum to the runError() event instead of this string matching
private static class PullImageErrorMatcher implements EventVisitor<Boolean> {
@Override
public Boolean timeTrigger(WorkflowInstance workflowInstance) {
return false;
}
@Override
public Boolean triggerExecution(WorkflowInstance workflowInstance, Trigger trigger) {
return false;
}
@Override
public Boolean info(WorkflowInstance workflowInstance, Message message) {
return false;
}
@Override
public Boolean dequeue(WorkflowInstance workflowInstance, Set<String> resourceIds) {
return false;
}
@Override
public Boolean created(WorkflowInstance workflowInstance, String executionId, String dockerImage) {
return false;
}
@Override
public Boolean submit(WorkflowInstance workflowInstance, ExecutionDescription executionDescription,
String executionId) {
return false;
}
@Override
public Boolean submitted(WorkflowInstance workflowInstance, String executionId) {
return false;
}
@Override
public Boolean started(WorkflowInstance workflowInstance) {
return false;
}
@Override
public Boolean terminate(WorkflowInstance workflowInstance, Optional<Integer> exitCode) {
return false;
}
@Override
public Boolean runError(WorkflowInstance workflowInstance, String message) {
return message.contains("failed to pull");
}
@Override
public Boolean success(WorkflowInstance workflowInstance) {
return false;
}
@Override
public Boolean retryAfter(WorkflowInstance workflowInstance, long delayMillis) {
return false;
}
@Override
public Boolean retry(WorkflowInstance workflowInstance) {
return false;
}
@Override
public Boolean stop(WorkflowInstance workflowInstance) {
return false;
}
@Override
public Boolean timeout(WorkflowInstance workflowInstance) {
return false;
}
@Override
public Boolean halt(WorkflowInstance workflowInstance) {
return false;
}
}
@AutoMatter
interface KubernetesSecretSpec {
Optional<WorkflowConfiguration.Secret> customSecret();
Optional<String> serviceAccountSecret();
static KubernetesSecretSpecBuilder builder() {
return new KubernetesSecretSpecBuilder();
}
}
}
| use the k8s default pause container image | styx-scheduler-service/src/main/java/com/spotify/styx/docker/KubernetesDockerRunner.java | use the k8s default pause container image |
|
Java | apache-2.0 | ee222f702762e33e100b3613599817cb826a30e9 | 0 | ened/ExoPlayer,amzn/exoplayer-amazon-port,google/ExoPlayer,amzn/exoplayer-amazon-port,amzn/exoplayer-amazon-port,androidx/media,androidx/media,ened/ExoPlayer,google/ExoPlayer,ened/ExoPlayer,google/ExoPlayer,androidx/media | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.extractor.mp4;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static com.google.android.exoplayer2.util.MimeTypes.getMimeTypeFromMp4ObjectType;
import android.util.Pair;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.audio.AacUtil;
import com.google.android.exoplayer2.audio.Ac3Util;
import com.google.android.exoplayer2.audio.Ac4Util;
import com.google.android.exoplayer2.drm.DrmInitData;
import com.google.android.exoplayer2.extractor.GaplessInfoHolder;
import com.google.android.exoplayer2.metadata.Metadata;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.CodecSpecificDataUtil;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.ParsableByteArray;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.AvcConfig;
import com.google.android.exoplayer2.video.DolbyVisionConfig;
import com.google.android.exoplayer2.video.HevcConfig;
import com.google.common.base.Function;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.checkerframework.checker.nullness.compatqual.NullableType;
/** Utility methods for parsing MP4 format atom payloads according to ISO/IEC 14496-12. */
@SuppressWarnings({"ConstantField"})
/* package */ final class AtomParsers {
private static final String TAG = "AtomParsers";
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_vide = 0x76696465;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_soun = 0x736f756e;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_text = 0x74657874;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_sbtl = 0x7362746c;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_subt = 0x73756274;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_clcp = 0x636c6370;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_meta = 0x6d657461;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_mdta = 0x6d647461;
/**
* The threshold number of samples to trim from the start/end of an audio track when applying an
* edit below which gapless info can be used (rather than removing samples from the sample table).
*/
private static final int MAX_GAPLESS_TRIM_SIZE_SAMPLES = 4;
/** The magic signature for an Opus Identification header, as defined in RFC-7845. */
private static final byte[] opusMagic = Util.getUtf8Bytes("OpusHead");
/**
* Parse the trak atoms in a moov atom (defined in ISO/IEC 14496-12).
*
* @param moov Moov atom to decode.
* @param gaplessInfoHolder Holder to populate with gapless playback information.
* @param duration The duration in units of the timescale declared in the mvhd atom, or {@link
* C#TIME_UNSET} if the duration should be parsed from the tkhd atom.
* @param drmInitData {@link DrmInitData} to be included in the format, or {@code null}.
* @param ignoreEditLists Whether to ignore any edit lists in the trak boxes.
* @param isQuickTime True for QuickTime media. False otherwise.
* @param modifyTrackFunction A function to apply to the {@link Track Tracks} in the result.
* @return A list of {@link TrackSampleTable} instances.
* @throws ParserException Thrown if the trak atoms can't be parsed.
*/
public static List<TrackSampleTable> parseTraks(
Atom.ContainerAtom moov,
GaplessInfoHolder gaplessInfoHolder,
long duration,
@Nullable DrmInitData drmInitData,
boolean ignoreEditLists,
boolean isQuickTime,
Function<@NullableType Track, @NullableType Track> modifyTrackFunction)
throws ParserException {
List<TrackSampleTable> trackSampleTables = new ArrayList<>();
for (int i = 0; i < moov.containerChildren.size(); i++) {
Atom.ContainerAtom atom = moov.containerChildren.get(i);
if (atom.type != Atom.TYPE_trak) {
continue;
}
@Nullable
Track track =
modifyTrackFunction.apply(
parseTrak(
atom,
checkNotNull(moov.getLeafAtomOfType(Atom.TYPE_mvhd)),
duration,
drmInitData,
ignoreEditLists,
isQuickTime));
if (track == null) {
continue;
}
Atom.ContainerAtom stblAtom =
checkNotNull(
checkNotNull(
checkNotNull(atom.getContainerAtomOfType(Atom.TYPE_mdia))
.getContainerAtomOfType(Atom.TYPE_minf))
.getContainerAtomOfType(Atom.TYPE_stbl));
TrackSampleTable trackSampleTable = parseStbl(track, stblAtom, gaplessInfoHolder);
trackSampleTables.add(trackSampleTable);
}
return trackSampleTables;
}
/**
* Parses a udta atom.
*
* @param udtaAtom The udta (user data) atom to decode.
* @param isQuickTime True for QuickTime media. False otherwise.
* @return Parsed metadata, or null.
*/
@Nullable
public static Metadata parseUdta(Atom.LeafAtom udtaAtom, boolean isQuickTime) {
if (isQuickTime) {
// Meta boxes are regular boxes rather than full boxes in QuickTime. For now, don't try and
// decode one.
return null;
}
ParsableByteArray udtaData = udtaAtom.data;
udtaData.setPosition(Atom.HEADER_SIZE);
while (udtaData.bytesLeft() >= Atom.HEADER_SIZE) {
int atomPosition = udtaData.getPosition();
int atomSize = udtaData.readInt();
int atomType = udtaData.readInt();
if (atomType == Atom.TYPE_meta) {
udtaData.setPosition(atomPosition);
return parseUdtaMeta(udtaData, atomPosition + atomSize);
}
udtaData.setPosition(atomPosition + atomSize);
}
return null;
}
/**
* Parses a metadata meta atom if it contains metadata with handler 'mdta'.
*
* @param meta The metadata atom to decode.
* @return Parsed metadata, or null.
*/
@Nullable
public static Metadata parseMdtaFromMeta(Atom.ContainerAtom meta) {
@Nullable Atom.LeafAtom hdlrAtom = meta.getLeafAtomOfType(Atom.TYPE_hdlr);
@Nullable Atom.LeafAtom keysAtom = meta.getLeafAtomOfType(Atom.TYPE_keys);
@Nullable Atom.LeafAtom ilstAtom = meta.getLeafAtomOfType(Atom.TYPE_ilst);
if (hdlrAtom == null
|| keysAtom == null
|| ilstAtom == null
|| parseHdlr(hdlrAtom.data) != TYPE_mdta) {
// There isn't enough information to parse the metadata, or the handler type is unexpected.
return null;
}
// Parse metadata keys.
ParsableByteArray keys = keysAtom.data;
keys.setPosition(Atom.FULL_HEADER_SIZE);
int entryCount = keys.readInt();
String[] keyNames = new String[entryCount];
for (int i = 0; i < entryCount; i++) {
int entrySize = keys.readInt();
keys.skipBytes(4); // keyNamespace
int keySize = entrySize - 8;
keyNames[i] = keys.readString(keySize);
}
// Parse metadata items.
ParsableByteArray ilst = ilstAtom.data;
ilst.setPosition(Atom.HEADER_SIZE);
ArrayList<Metadata.Entry> entries = new ArrayList<>();
while (ilst.bytesLeft() > Atom.HEADER_SIZE) {
int atomPosition = ilst.getPosition();
int atomSize = ilst.readInt();
int keyIndex = ilst.readInt() - 1;
if (keyIndex >= 0 && keyIndex < keyNames.length) {
String key = keyNames[keyIndex];
@Nullable
Metadata.Entry entry =
MetadataUtil.parseMdtaMetadataEntryFromIlst(ilst, atomPosition + atomSize, key);
if (entry != null) {
entries.add(entry);
}
} else {
Log.w(TAG, "Skipped metadata with unknown key index: " + keyIndex);
}
ilst.setPosition(atomPosition + atomSize);
}
return entries.isEmpty() ? null : new Metadata(entries);
}
/**
* Parses a trak atom (defined in ISO/IEC 14496-12).
*
* @param trak Atom to decode.
* @param mvhd Movie header atom, used to get the timescale.
* @param duration The duration in units of the timescale declared in the mvhd atom, or {@link
* C#TIME_UNSET} if the duration should be parsed from the tkhd atom.
* @param drmInitData {@link DrmInitData} to be included in the format, or {@code null}.
* @param ignoreEditLists Whether to ignore any edit lists in the trak box.
* @param isQuickTime True for QuickTime media. False otherwise.
* @return A {@link Track} instance, or {@code null} if the track's type isn't supported.
* @throws ParserException Thrown if the trak atom can't be parsed.
*/
@Nullable
private static Track parseTrak(
Atom.ContainerAtom trak,
Atom.LeafAtom mvhd,
long duration,
@Nullable DrmInitData drmInitData,
boolean ignoreEditLists,
boolean isQuickTime)
throws ParserException {
Atom.ContainerAtom mdia = checkNotNull(trak.getContainerAtomOfType(Atom.TYPE_mdia));
int trackType =
getTrackTypeForHdlr(parseHdlr(checkNotNull(mdia.getLeafAtomOfType(Atom.TYPE_hdlr)).data));
if (trackType == C.TRACK_TYPE_UNKNOWN) {
return null;
}
TkhdData tkhdData = parseTkhd(checkNotNull(trak.getLeafAtomOfType(Atom.TYPE_tkhd)).data);
if (duration == C.TIME_UNSET) {
duration = tkhdData.duration;
}
long movieTimescale = parseMvhd(mvhd.data);
long durationUs;
if (duration == C.TIME_UNSET) {
durationUs = C.TIME_UNSET;
} else {
durationUs = Util.scaleLargeTimestamp(duration, C.MICROS_PER_SECOND, movieTimescale);
}
Atom.ContainerAtom stbl =
checkNotNull(
checkNotNull(mdia.getContainerAtomOfType(Atom.TYPE_minf))
.getContainerAtomOfType(Atom.TYPE_stbl));
Pair<Long, String> mdhdData =
parseMdhd(checkNotNull(mdia.getLeafAtomOfType(Atom.TYPE_mdhd)).data);
StsdData stsdData =
parseStsd(
checkNotNull(stbl.getLeafAtomOfType(Atom.TYPE_stsd)).data,
tkhdData.id,
tkhdData.rotationDegrees,
mdhdData.second,
drmInitData,
isQuickTime);
@Nullable long[] editListDurations = null;
@Nullable long[] editListMediaTimes = null;
if (!ignoreEditLists) {
@Nullable Atom.ContainerAtom edtsAtom = trak.getContainerAtomOfType(Atom.TYPE_edts);
if (edtsAtom != null) {
@Nullable Pair<long[], long[]> edtsData = parseEdts(edtsAtom);
if (edtsData != null) {
editListDurations = edtsData.first;
editListMediaTimes = edtsData.second;
}
}
}
return stsdData.format == null ? null
: new Track(tkhdData.id, trackType, mdhdData.first, movieTimescale, durationUs,
stsdData.format, stsdData.requiredSampleTransformation, stsdData.trackEncryptionBoxes,
stsdData.nalUnitLengthFieldLength, editListDurations, editListMediaTimes);
}
/**
* Parses an stbl atom (defined in ISO/IEC 14496-12).
*
* @param track Track to which this sample table corresponds.
* @param stblAtom stbl (sample table) atom to decode.
* @param gaplessInfoHolder Holder to populate with gapless playback information.
* @return Sample table described by the stbl atom.
* @throws ParserException Thrown if the stbl atom can't be parsed.
*/
private static TrackSampleTable parseStbl(
Track track, Atom.ContainerAtom stblAtom, GaplessInfoHolder gaplessInfoHolder)
throws ParserException {
SampleSizeBox sampleSizeBox;
@Nullable Atom.LeafAtom stszAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stsz);
if (stszAtom != null) {
sampleSizeBox = new StszSampleSizeBox(stszAtom);
} else {
@Nullable Atom.LeafAtom stz2Atom = stblAtom.getLeafAtomOfType(Atom.TYPE_stz2);
if (stz2Atom == null) {
throw new ParserException("Track has no sample table size information");
}
sampleSizeBox = new Stz2SampleSizeBox(stz2Atom);
}
int sampleCount = sampleSizeBox.getSampleCount();
if (sampleCount == 0) {
return new TrackSampleTable(
track,
/* offsets= */ new long[0],
/* sizes= */ new int[0],
/* maximumSize= */ 0,
/* timestampsUs= */ new long[0],
/* flags= */ new int[0],
/* durationUs= */ 0);
}
// Entries are byte offsets of chunks.
boolean chunkOffsetsAreLongs = false;
@Nullable Atom.LeafAtom chunkOffsetsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stco);
if (chunkOffsetsAtom == null) {
chunkOffsetsAreLongs = true;
chunkOffsetsAtom = checkNotNull(stblAtom.getLeafAtomOfType(Atom.TYPE_co64));
}
ParsableByteArray chunkOffsets = chunkOffsetsAtom.data;
// Entries are (chunk number, number of samples per chunk, sample description index).
ParsableByteArray stsc = checkNotNull(stblAtom.getLeafAtomOfType(Atom.TYPE_stsc)).data;
// Entries are (number of samples, timestamp delta between those samples).
ParsableByteArray stts = checkNotNull(stblAtom.getLeafAtomOfType(Atom.TYPE_stts)).data;
// Entries are the indices of samples that are synchronization samples.
@Nullable Atom.LeafAtom stssAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stss);
@Nullable ParsableByteArray stss = stssAtom != null ? stssAtom.data : null;
// Entries are (number of samples, timestamp offset).
@Nullable Atom.LeafAtom cttsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_ctts);
@Nullable ParsableByteArray ctts = cttsAtom != null ? cttsAtom.data : null;
// Prepare to read chunk information.
ChunkIterator chunkIterator = new ChunkIterator(stsc, chunkOffsets, chunkOffsetsAreLongs);
// Prepare to read sample timestamps.
stts.setPosition(Atom.FULL_HEADER_SIZE);
int remainingTimestampDeltaChanges = stts.readUnsignedIntToInt() - 1;
int remainingSamplesAtTimestampDelta = stts.readUnsignedIntToInt();
int timestampDeltaInTimeUnits = stts.readUnsignedIntToInt();
// Prepare to read sample timestamp offsets, if ctts is present.
int remainingSamplesAtTimestampOffset = 0;
int remainingTimestampOffsetChanges = 0;
int timestampOffset = 0;
if (ctts != null) {
ctts.setPosition(Atom.FULL_HEADER_SIZE);
remainingTimestampOffsetChanges = ctts.readUnsignedIntToInt();
}
int nextSynchronizationSampleIndex = C.INDEX_UNSET;
int remainingSynchronizationSamples = 0;
if (stss != null) {
stss.setPosition(Atom.FULL_HEADER_SIZE);
remainingSynchronizationSamples = stss.readUnsignedIntToInt();
if (remainingSynchronizationSamples > 0) {
nextSynchronizationSampleIndex = stss.readUnsignedIntToInt() - 1;
} else {
// Ignore empty stss boxes, which causes all samples to be treated as sync samples.
stss = null;
}
}
// Fixed sample size raw audio may need to be rechunked.
boolean isFixedSampleSizeRawAudio =
sampleSizeBox.isFixedSampleSize()
&& MimeTypes.AUDIO_RAW.equals(track.format.sampleMimeType)
&& remainingTimestampDeltaChanges == 0
&& remainingTimestampOffsetChanges == 0
&& remainingSynchronizationSamples == 0;
long[] offsets;
int[] sizes;
int maximumSize = 0;
long[] timestamps;
int[] flags;
long timestampTimeUnits = 0;
long duration;
if (isFixedSampleSizeRawAudio) {
long[] chunkOffsetsBytes = new long[chunkIterator.length];
int[] chunkSampleCounts = new int[chunkIterator.length];
while (chunkIterator.moveNext()) {
chunkOffsetsBytes[chunkIterator.index] = chunkIterator.offset;
chunkSampleCounts[chunkIterator.index] = chunkIterator.numSamples;
}
int fixedSampleSize = Util.getPcmFrameSize(track.format.encoding, track.format.channelCount);
FixedSampleSizeRechunker.Results rechunkedResults =
FixedSampleSizeRechunker.rechunk(
fixedSampleSize, chunkOffsetsBytes, chunkSampleCounts, timestampDeltaInTimeUnits);
offsets = rechunkedResults.offsets;
sizes = rechunkedResults.sizes;
maximumSize = rechunkedResults.maximumSize;
timestamps = rechunkedResults.timestamps;
flags = rechunkedResults.flags;
duration = rechunkedResults.duration;
} else {
offsets = new long[sampleCount];
sizes = new int[sampleCount];
timestamps = new long[sampleCount];
flags = new int[sampleCount];
long offset = 0;
int remainingSamplesInChunk = 0;
for (int i = 0; i < sampleCount; i++) {
// Advance to the next chunk if necessary.
boolean chunkDataComplete = true;
while (remainingSamplesInChunk == 0 && (chunkDataComplete = chunkIterator.moveNext())) {
offset = chunkIterator.offset;
remainingSamplesInChunk = chunkIterator.numSamples;
}
if (!chunkDataComplete) {
Log.w(TAG, "Unexpected end of chunk data");
sampleCount = i;
offsets = Arrays.copyOf(offsets, sampleCount);
sizes = Arrays.copyOf(sizes, sampleCount);
timestamps = Arrays.copyOf(timestamps, sampleCount);
flags = Arrays.copyOf(flags, sampleCount);
break;
}
// Add on the timestamp offset if ctts is present.
if (ctts != null) {
while (remainingSamplesAtTimestampOffset == 0 && remainingTimestampOffsetChanges > 0) {
remainingSamplesAtTimestampOffset = ctts.readUnsignedIntToInt();
// The BMFF spec (ISO/IEC 14496-12) states that sample offsets should be unsigned
// integers in version 0 ctts boxes, however some streams violate the spec and use
// signed integers instead. It's safe to always decode sample offsets as signed integers
// here, because unsigned integers will still be parsed correctly (unless their top bit
// is set, which is never true in practice because sample offsets are always small).
timestampOffset = ctts.readInt();
remainingTimestampOffsetChanges--;
}
remainingSamplesAtTimestampOffset--;
}
offsets[i] = offset;
sizes[i] = sampleSizeBox.readNextSampleSize();
if (sizes[i] > maximumSize) {
maximumSize = sizes[i];
}
timestamps[i] = timestampTimeUnits + timestampOffset;
// All samples are synchronization samples if the stss is not present.
flags[i] = stss == null ? C.BUFFER_FLAG_KEY_FRAME : 0;
if (i == nextSynchronizationSampleIndex) {
flags[i] = C.BUFFER_FLAG_KEY_FRAME;
remainingSynchronizationSamples--;
if (remainingSynchronizationSamples > 0) {
nextSynchronizationSampleIndex = checkNotNull(stss).readUnsignedIntToInt() - 1;
}
}
// Add on the duration of this sample.
timestampTimeUnits += timestampDeltaInTimeUnits;
remainingSamplesAtTimestampDelta--;
if (remainingSamplesAtTimestampDelta == 0 && remainingTimestampDeltaChanges > 0) {
remainingSamplesAtTimestampDelta = stts.readUnsignedIntToInt();
// The BMFF spec (ISO/IEC 14496-12) states that sample deltas should be unsigned integers
// in stts boxes, however some streams violate the spec and use signed integers instead.
// See https://github.com/google/ExoPlayer/issues/3384. It's safe to always decode sample
// deltas as signed integers here, because unsigned integers will still be parsed
// correctly (unless their top bit is set, which is never true in practice because sample
// deltas are always small).
timestampDeltaInTimeUnits = stts.readInt();
remainingTimestampDeltaChanges--;
}
offset += sizes[i];
remainingSamplesInChunk--;
}
duration = timestampTimeUnits + timestampOffset;
// If the stbl's child boxes are not consistent the container is malformed, but the stream may
// still be playable.
boolean isCttsValid = true;
if (ctts != null) {
while (remainingTimestampOffsetChanges > 0) {
if (ctts.readUnsignedIntToInt() != 0) {
isCttsValid = false;
break;
}
ctts.readInt(); // Ignore offset.
remainingTimestampOffsetChanges--;
}
}
if (remainingSynchronizationSamples != 0
|| remainingSamplesAtTimestampDelta != 0
|| remainingSamplesInChunk != 0
|| remainingTimestampDeltaChanges != 0
|| remainingSamplesAtTimestampOffset != 0
|| !isCttsValid) {
Log.w(
TAG,
"Inconsistent stbl box for track "
+ track.id
+ ": remainingSynchronizationSamples "
+ remainingSynchronizationSamples
+ ", remainingSamplesAtTimestampDelta "
+ remainingSamplesAtTimestampDelta
+ ", remainingSamplesInChunk "
+ remainingSamplesInChunk
+ ", remainingTimestampDeltaChanges "
+ remainingTimestampDeltaChanges
+ ", remainingSamplesAtTimestampOffset "
+ remainingSamplesAtTimestampOffset
+ (!isCttsValid ? ", ctts invalid" : ""));
}
}
long durationUs = Util.scaleLargeTimestamp(duration, C.MICROS_PER_SECOND, track.timescale);
if (track.editListDurations == null) {
Util.scaleLargeTimestampsInPlace(timestamps, C.MICROS_PER_SECOND, track.timescale);
return new TrackSampleTable(
track, offsets, sizes, maximumSize, timestamps, flags, durationUs);
}
// See the BMFF spec (ISO/IEC 14496-12) subsection 8.6.6. Edit lists that require prerolling
// from a sync sample after reordering are not supported. Partial audio sample truncation is
// only supported in edit lists with one edit that removes less than
// MAX_GAPLESS_TRIM_SIZE_SAMPLES samples from the start/end of the track. This implementation
// handles simple discarding/delaying of samples. The extractor may place further restrictions
// on what edited streams are playable.
if (track.editListDurations.length == 1
&& track.type == C.TRACK_TYPE_AUDIO
&& timestamps.length >= 2) {
long editStartTime = checkNotNull(track.editListMediaTimes)[0];
long editEndTime = editStartTime + Util.scaleLargeTimestamp(track.editListDurations[0],
track.timescale, track.movieTimescale);
if (canApplyEditWithGaplessInfo(timestamps, duration, editStartTime, editEndTime)) {
long paddingTimeUnits = duration - editEndTime;
long encoderDelay = Util.scaleLargeTimestamp(editStartTime - timestamps[0],
track.format.sampleRate, track.timescale);
long encoderPadding = Util.scaleLargeTimestamp(paddingTimeUnits,
track.format.sampleRate, track.timescale);
if ((encoderDelay != 0 || encoderPadding != 0) && encoderDelay <= Integer.MAX_VALUE
&& encoderPadding <= Integer.MAX_VALUE) {
gaplessInfoHolder.encoderDelay = (int) encoderDelay;
gaplessInfoHolder.encoderPadding = (int) encoderPadding;
Util.scaleLargeTimestampsInPlace(timestamps, C.MICROS_PER_SECOND, track.timescale);
long editedDurationUs =
Util.scaleLargeTimestamp(
track.editListDurations[0], C.MICROS_PER_SECOND, track.movieTimescale);
return new TrackSampleTable(
track, offsets, sizes, maximumSize, timestamps, flags, editedDurationUs);
}
}
}
if (track.editListDurations.length == 1 && track.editListDurations[0] == 0) {
// The current version of the spec leaves handling of an edit with zero segment_duration in
// unfragmented files open to interpretation. We handle this as a special case and include all
// samples in the edit.
long editStartTime = checkNotNull(track.editListMediaTimes)[0];
for (int i = 0; i < timestamps.length; i++) {
timestamps[i] =
Util.scaleLargeTimestamp(
timestamps[i] - editStartTime, C.MICROS_PER_SECOND, track.timescale);
}
durationUs =
Util.scaleLargeTimestamp(duration - editStartTime, C.MICROS_PER_SECOND, track.timescale);
return new TrackSampleTable(
track, offsets, sizes, maximumSize, timestamps, flags, durationUs);
}
// Omit any sample at the end point of an edit for audio tracks.
boolean omitClippedSample = track.type == C.TRACK_TYPE_AUDIO;
// Count the number of samples after applying edits.
int editedSampleCount = 0;
int nextSampleIndex = 0;
boolean copyMetadata = false;
int[] startIndices = new int[track.editListDurations.length];
int[] endIndices = new int[track.editListDurations.length];
long[] editListMediaTimes = checkNotNull(track.editListMediaTimes);
for (int i = 0; i < track.editListDurations.length; i++) {
long editMediaTime = editListMediaTimes[i];
if (editMediaTime != -1) {
long editDuration =
Util.scaleLargeTimestamp(
track.editListDurations[i], track.timescale, track.movieTimescale);
startIndices[i] =
Util.binarySearchFloor(
timestamps, editMediaTime, /* inclusive= */ true, /* stayInBounds= */ true);
endIndices[i] =
Util.binarySearchCeil(
timestamps,
editMediaTime + editDuration,
/* inclusive= */ omitClippedSample,
/* stayInBounds= */ false);
while (startIndices[i] < endIndices[i]
&& (flags[startIndices[i]] & C.BUFFER_FLAG_KEY_FRAME) == 0) {
// Applying the edit correctly would require prerolling from the previous sync sample. In
// the current implementation we advance to the next sync sample instead. Only other
// tracks (i.e. audio) will be rendered until the time of the first sync sample.
// See https://github.com/google/ExoPlayer/issues/1659.
startIndices[i]++;
}
editedSampleCount += endIndices[i] - startIndices[i];
copyMetadata |= nextSampleIndex != startIndices[i];
nextSampleIndex = endIndices[i];
}
}
copyMetadata |= editedSampleCount != sampleCount;
// Calculate edited sample timestamps and update the corresponding metadata arrays.
long[] editedOffsets = copyMetadata ? new long[editedSampleCount] : offsets;
int[] editedSizes = copyMetadata ? new int[editedSampleCount] : sizes;
int editedMaximumSize = copyMetadata ? 0 : maximumSize;
int[] editedFlags = copyMetadata ? new int[editedSampleCount] : flags;
long[] editedTimestamps = new long[editedSampleCount];
long pts = 0;
int sampleIndex = 0;
for (int i = 0; i < track.editListDurations.length; i++) {
long editMediaTime = track.editListMediaTimes[i];
int startIndex = startIndices[i];
int endIndex = endIndices[i];
if (copyMetadata) {
int count = endIndex - startIndex;
System.arraycopy(offsets, startIndex, editedOffsets, sampleIndex, count);
System.arraycopy(sizes, startIndex, editedSizes, sampleIndex, count);
System.arraycopy(flags, startIndex, editedFlags, sampleIndex, count);
}
for (int j = startIndex; j < endIndex; j++) {
long ptsUs = Util.scaleLargeTimestamp(pts, C.MICROS_PER_SECOND, track.movieTimescale);
long timeInSegmentUs =
Util.scaleLargeTimestamp(
Math.max(0, timestamps[j] - editMediaTime), C.MICROS_PER_SECOND, track.timescale);
editedTimestamps[sampleIndex] = ptsUs + timeInSegmentUs;
if (copyMetadata && editedSizes[sampleIndex] > editedMaximumSize) {
editedMaximumSize = sizes[j];
}
sampleIndex++;
}
pts += track.editListDurations[i];
}
long editedDurationUs =
Util.scaleLargeTimestamp(pts, C.MICROS_PER_SECOND, track.movieTimescale);
return new TrackSampleTable(
track,
editedOffsets,
editedSizes,
editedMaximumSize,
editedTimestamps,
editedFlags,
editedDurationUs);
}
@Nullable
private static Metadata parseUdtaMeta(ParsableByteArray meta, int limit) {
meta.skipBytes(Atom.FULL_HEADER_SIZE);
while (meta.getPosition() < limit) {
int atomPosition = meta.getPosition();
int atomSize = meta.readInt();
int atomType = meta.readInt();
if (atomType == Atom.TYPE_ilst) {
meta.setPosition(atomPosition);
return parseIlst(meta, atomPosition + atomSize);
}
meta.setPosition(atomPosition + atomSize);
}
return null;
}
@Nullable
private static Metadata parseIlst(ParsableByteArray ilst, int limit) {
ilst.skipBytes(Atom.HEADER_SIZE);
ArrayList<Metadata.Entry> entries = new ArrayList<>();
while (ilst.getPosition() < limit) {
@Nullable Metadata.Entry entry = MetadataUtil.parseIlstElement(ilst);
if (entry != null) {
entries.add(entry);
}
}
return entries.isEmpty() ? null : new Metadata(entries);
}
/**
* Parses a mvhd atom (defined in ISO/IEC 14496-12), returning the timescale for the movie.
*
* @param mvhd Contents of the mvhd atom to be parsed.
* @return Timescale for the movie.
*/
private static long parseMvhd(ParsableByteArray mvhd) {
mvhd.setPosition(Atom.HEADER_SIZE);
int fullAtom = mvhd.readInt();
int version = Atom.parseFullAtomVersion(fullAtom);
mvhd.skipBytes(version == 0 ? 8 : 16);
return mvhd.readUnsignedInt();
}
/**
* Parses a tkhd atom (defined in ISO/IEC 14496-12).
*
* @return An object containing the parsed data.
*/
private static TkhdData parseTkhd(ParsableByteArray tkhd) {
tkhd.setPosition(Atom.HEADER_SIZE);
int fullAtom = tkhd.readInt();
int version = Atom.parseFullAtomVersion(fullAtom);
tkhd.skipBytes(version == 0 ? 8 : 16);
int trackId = tkhd.readInt();
tkhd.skipBytes(4);
boolean durationUnknown = true;
int durationPosition = tkhd.getPosition();
int durationByteCount = version == 0 ? 4 : 8;
for (int i = 0; i < durationByteCount; i++) {
if (tkhd.data[durationPosition + i] != -1) {
durationUnknown = false;
break;
}
}
long duration;
if (durationUnknown) {
tkhd.skipBytes(durationByteCount);
duration = C.TIME_UNSET;
} else {
duration = version == 0 ? tkhd.readUnsignedInt() : tkhd.readUnsignedLongToLong();
if (duration == 0) {
// 0 duration normally indicates that the file is fully fragmented (i.e. all of the media
// samples are in fragments). Treat as unknown.
duration = C.TIME_UNSET;
}
}
tkhd.skipBytes(16);
int a00 = tkhd.readInt();
int a01 = tkhd.readInt();
tkhd.skipBytes(4);
int a10 = tkhd.readInt();
int a11 = tkhd.readInt();
int rotationDegrees;
int fixedOne = 65536;
if (a00 == 0 && a01 == fixedOne && a10 == -fixedOne && a11 == 0) {
rotationDegrees = 90;
} else if (a00 == 0 && a01 == -fixedOne && a10 == fixedOne && a11 == 0) {
rotationDegrees = 270;
} else if (a00 == -fixedOne && a01 == 0 && a10 == 0 && a11 == -fixedOne) {
rotationDegrees = 180;
} else {
// Only 0, 90, 180 and 270 are supported. Treat anything else as 0.
rotationDegrees = 0;
}
return new TkhdData(trackId, duration, rotationDegrees);
}
/**
* Parses an hdlr atom.
*
* @param hdlr The hdlr atom to decode.
* @return The handler value.
*/
private static int parseHdlr(ParsableByteArray hdlr) {
hdlr.setPosition(Atom.FULL_HEADER_SIZE + 4);
return hdlr.readInt();
}
/** Returns the track type for a given handler value. */
private static int getTrackTypeForHdlr(int hdlr) {
if (hdlr == TYPE_soun) {
return C.TRACK_TYPE_AUDIO;
} else if (hdlr == TYPE_vide) {
return C.TRACK_TYPE_VIDEO;
} else if (hdlr == TYPE_text || hdlr == TYPE_sbtl || hdlr == TYPE_subt || hdlr == TYPE_clcp) {
return C.TRACK_TYPE_TEXT;
} else if (hdlr == TYPE_meta) {
return C.TRACK_TYPE_METADATA;
} else {
return C.TRACK_TYPE_UNKNOWN;
}
}
/**
* Parses an mdhd atom (defined in ISO/IEC 14496-12).
*
* @param mdhd The mdhd atom to decode.
* @return A pair consisting of the media timescale defined as the number of time units that pass
* in one second, and the language code.
*/
private static Pair<Long, String> parseMdhd(ParsableByteArray mdhd) {
mdhd.setPosition(Atom.HEADER_SIZE);
int fullAtom = mdhd.readInt();
int version = Atom.parseFullAtomVersion(fullAtom);
mdhd.skipBytes(version == 0 ? 8 : 16);
long timescale = mdhd.readUnsignedInt();
mdhd.skipBytes(version == 0 ? 4 : 8);
int languageCode = mdhd.readUnsignedShort();
String language =
""
+ (char) (((languageCode >> 10) & 0x1F) + 0x60)
+ (char) (((languageCode >> 5) & 0x1F) + 0x60)
+ (char) ((languageCode & 0x1F) + 0x60);
return Pair.create(timescale, language);
}
/**
* Parses a stsd atom (defined in ISO/IEC 14496-12).
*
* @param stsd The stsd atom to decode.
* @param trackId The track's identifier in its container.
* @param rotationDegrees The rotation of the track in degrees.
* @param language The language of the track.
* @param drmInitData {@link DrmInitData} to be included in the format, or {@code null}.
* @param isQuickTime True for QuickTime media. False otherwise.
* @return An object containing the parsed data.
*/
private static StsdData parseStsd(
ParsableByteArray stsd,
int trackId,
int rotationDegrees,
String language,
@Nullable DrmInitData drmInitData,
boolean isQuickTime)
throws ParserException {
stsd.setPosition(Atom.FULL_HEADER_SIZE);
int numberOfEntries = stsd.readInt();
StsdData out = new StsdData(numberOfEntries);
for (int i = 0; i < numberOfEntries; i++) {
int childStartPosition = stsd.getPosition();
int childAtomSize = stsd.readInt();
Assertions.checkState(childAtomSize > 0, "childAtomSize should be positive");
int childAtomType = stsd.readInt();
if (childAtomType == Atom.TYPE_avc1
|| childAtomType == Atom.TYPE_avc3
|| childAtomType == Atom.TYPE_encv
|| childAtomType == Atom.TYPE_mp4v
|| childAtomType == Atom.TYPE_hvc1
|| childAtomType == Atom.TYPE_hev1
|| childAtomType == Atom.TYPE_s263
|| childAtomType == Atom.TYPE_vp08
|| childAtomType == Atom.TYPE_vp09
|| childAtomType == Atom.TYPE_av01
|| childAtomType == Atom.TYPE_dvav
|| childAtomType == Atom.TYPE_dva1
|| childAtomType == Atom.TYPE_dvhe
|| childAtomType == Atom.TYPE_dvh1) {
parseVideoSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId,
rotationDegrees, drmInitData, out, i);
} else if (childAtomType == Atom.TYPE_mp4a
|| childAtomType == Atom.TYPE_enca
|| childAtomType == Atom.TYPE_ac_3
|| childAtomType == Atom.TYPE_ec_3
|| childAtomType == Atom.TYPE_ac_4
|| childAtomType == Atom.TYPE_dtsc
|| childAtomType == Atom.TYPE_dtse
|| childAtomType == Atom.TYPE_dtsh
|| childAtomType == Atom.TYPE_dtsl
|| childAtomType == Atom.TYPE_samr
|| childAtomType == Atom.TYPE_sawb
|| childAtomType == Atom.TYPE_lpcm
|| childAtomType == Atom.TYPE_sowt
|| childAtomType == Atom.TYPE_twos
|| childAtomType == Atom.TYPE__mp3
|| childAtomType == Atom.TYPE_alac
|| childAtomType == Atom.TYPE_alaw
|| childAtomType == Atom.TYPE_ulaw
|| childAtomType == Atom.TYPE_Opus
|| childAtomType == Atom.TYPE_fLaC) {
parseAudioSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId,
language, isQuickTime, drmInitData, out, i);
} else if (childAtomType == Atom.TYPE_TTML || childAtomType == Atom.TYPE_tx3g
|| childAtomType == Atom.TYPE_wvtt || childAtomType == Atom.TYPE_stpp
|| childAtomType == Atom.TYPE_c608) {
parseTextSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId,
language, out);
} else if (childAtomType == Atom.TYPE_camm) {
out.format =
new Format.Builder()
.setId(trackId)
.setSampleMimeType(MimeTypes.APPLICATION_CAMERA_MOTION)
.build();
}
stsd.setPosition(childStartPosition + childAtomSize);
}
return out;
}
private static void parseTextSampleEntry(
ParsableByteArray parent,
int atomType,
int position,
int atomSize,
int trackId,
String language,
StsdData out) {
parent.setPosition(position + Atom.HEADER_SIZE + StsdData.STSD_HEADER_SIZE);
// Default values.
@Nullable List<byte[]> initializationData = null;
long subsampleOffsetUs = Format.OFFSET_SAMPLE_RELATIVE;
String mimeType;
if (atomType == Atom.TYPE_TTML) {
mimeType = MimeTypes.APPLICATION_TTML;
} else if (atomType == Atom.TYPE_tx3g) {
mimeType = MimeTypes.APPLICATION_TX3G;
int sampleDescriptionLength = atomSize - Atom.HEADER_SIZE - 8;
byte[] sampleDescriptionData = new byte[sampleDescriptionLength];
parent.readBytes(sampleDescriptionData, 0, sampleDescriptionLength);
initializationData = Collections.singletonList(sampleDescriptionData);
} else if (atomType == Atom.TYPE_wvtt) {
mimeType = MimeTypes.APPLICATION_MP4VTT;
} else if (atomType == Atom.TYPE_stpp) {
mimeType = MimeTypes.APPLICATION_TTML;
subsampleOffsetUs = 0; // Subsample timing is absolute.
} else if (atomType == Atom.TYPE_c608) {
// Defined by the QuickTime File Format specification.
mimeType = MimeTypes.APPLICATION_MP4CEA608;
out.requiredSampleTransformation = Track.TRANSFORMATION_CEA608_CDAT;
} else {
// Never happens.
throw new IllegalStateException();
}
out.format =
new Format.Builder()
.setId(trackId)
.setSampleMimeType(mimeType)
.setLanguage(language)
.setSubsampleOffsetUs(subsampleOffsetUs)
.setInitializationData(initializationData)
.build();
}
private static void parseVideoSampleEntry(
ParsableByteArray parent,
int atomType,
int position,
int size,
int trackId,
int rotationDegrees,
@Nullable DrmInitData drmInitData,
StsdData out,
int entryIndex)
throws ParserException {
parent.setPosition(position + Atom.HEADER_SIZE + StsdData.STSD_HEADER_SIZE);
parent.skipBytes(16);
int width = parent.readUnsignedShort();
int height = parent.readUnsignedShort();
boolean pixelWidthHeightRatioFromPasp = false;
float pixelWidthHeightRatio = 1;
parent.skipBytes(50);
int childPosition = parent.getPosition();
if (atomType == Atom.TYPE_encv) {
@Nullable
Pair<Integer, TrackEncryptionBox> sampleEntryEncryptionData =
parseSampleEntryEncryptionData(parent, position, size);
if (sampleEntryEncryptionData != null) {
atomType = sampleEntryEncryptionData.first;
drmInitData = drmInitData == null ? null
: drmInitData.copyWithSchemeType(sampleEntryEncryptionData.second.schemeType);
out.trackEncryptionBoxes[entryIndex] = sampleEntryEncryptionData.second;
}
parent.setPosition(childPosition);
}
// TODO: Uncomment when [Internal: b/63092960] is fixed.
// else {
// drmInitData = null;
// }
@Nullable List<byte[]> initializationData = null;
@Nullable String mimeType = null;
@Nullable String codecs = null;
@Nullable byte[] projectionData = null;
@C.StereoMode
int stereoMode = Format.NO_VALUE;
while (childPosition - position < size) {
parent.setPosition(childPosition);
int childStartPosition = parent.getPosition();
int childAtomSize = parent.readInt();
if (childAtomSize == 0 && parent.getPosition() - position == size) {
// Handle optional terminating four zero bytes in MOV files.
break;
}
Assertions.checkState(childAtomSize > 0, "childAtomSize should be positive");
int childAtomType = parent.readInt();
if (childAtomType == Atom.TYPE_avcC) {
Assertions.checkState(mimeType == null);
mimeType = MimeTypes.VIDEO_H264;
parent.setPosition(childStartPosition + Atom.HEADER_SIZE);
AvcConfig avcConfig = AvcConfig.parse(parent);
initializationData = avcConfig.initializationData;
out.nalUnitLengthFieldLength = avcConfig.nalUnitLengthFieldLength;
if (!pixelWidthHeightRatioFromPasp) {
pixelWidthHeightRatio = avcConfig.pixelWidthAspectRatio;
}
} else if (childAtomType == Atom.TYPE_hvcC) {
Assertions.checkState(mimeType == null);
mimeType = MimeTypes.VIDEO_H265;
parent.setPosition(childStartPosition + Atom.HEADER_SIZE);
HevcConfig hevcConfig = HevcConfig.parse(parent);
initializationData = hevcConfig.initializationData;
out.nalUnitLengthFieldLength = hevcConfig.nalUnitLengthFieldLength;
} else if (childAtomType == Atom.TYPE_dvcC || childAtomType == Atom.TYPE_dvvC) {
@Nullable DolbyVisionConfig dolbyVisionConfig = DolbyVisionConfig.parse(parent);
if (dolbyVisionConfig != null) {
codecs = dolbyVisionConfig.codecs;
mimeType = MimeTypes.VIDEO_DOLBY_VISION;
}
} else if (childAtomType == Atom.TYPE_vpcC) {
Assertions.checkState(mimeType == null);
mimeType = (atomType == Atom.TYPE_vp08) ? MimeTypes.VIDEO_VP8 : MimeTypes.VIDEO_VP9;
} else if (childAtomType == Atom.TYPE_av1C) {
Assertions.checkState(mimeType == null);
mimeType = MimeTypes.VIDEO_AV1;
} else if (childAtomType == Atom.TYPE_d263) {
Assertions.checkState(mimeType == null);
mimeType = MimeTypes.VIDEO_H263;
} else if (childAtomType == Atom.TYPE_esds) {
Assertions.checkState(mimeType == null);
Pair<@NullableType String, byte @NullableType []> mimeTypeAndInitializationDataBytes =
parseEsdsFromParent(parent, childStartPosition);
mimeType = mimeTypeAndInitializationDataBytes.first;
@Nullable byte[] initializationDataBytes = mimeTypeAndInitializationDataBytes.second;
if (initializationDataBytes != null) {
initializationData = Collections.singletonList(initializationDataBytes);
}
} else if (childAtomType == Atom.TYPE_pasp) {
pixelWidthHeightRatio = parsePaspFromParent(parent, childStartPosition);
pixelWidthHeightRatioFromPasp = true;
} else if (childAtomType == Atom.TYPE_sv3d) {
projectionData = parseProjFromParent(parent, childStartPosition, childAtomSize);
} else if (childAtomType == Atom.TYPE_st3d) {
int version = parent.readUnsignedByte();
parent.skipBytes(3); // Flags.
if (version == 0) {
int layout = parent.readUnsignedByte();
switch (layout) {
case 0:
stereoMode = C.STEREO_MODE_MONO;
break;
case 1:
stereoMode = C.STEREO_MODE_TOP_BOTTOM;
break;
case 2:
stereoMode = C.STEREO_MODE_LEFT_RIGHT;
break;
case 3:
stereoMode = C.STEREO_MODE_STEREO_MESH;
break;
default:
break;
}
}
}
childPosition += childAtomSize;
}
// If the media type was not recognized, ignore the track.
if (mimeType == null) {
return;
}
out.format =
new Format.Builder()
.setId(trackId)
.setSampleMimeType(mimeType)
.setCodecs(codecs)
.setWidth(width)
.setHeight(height)
.setPixelWidthHeightRatio(pixelWidthHeightRatio)
.setRotationDegrees(rotationDegrees)
.setProjectionData(projectionData)
.setStereoMode(stereoMode)
.setInitializationData(initializationData)
.setDrmInitData(drmInitData)
.build();
}
/**
* Parses the edts atom (defined in ISO/IEC 14496-12 subsection 8.6.5).
*
* @param edtsAtom edts (edit box) atom to decode.
* @return Pair of edit list durations and edit list media times, or {@code null} if they are not
* present.
*/
@Nullable
private static Pair<long[], long[]> parseEdts(Atom.ContainerAtom edtsAtom) {
@Nullable Atom.LeafAtom elstAtom = edtsAtom.getLeafAtomOfType(Atom.TYPE_elst);
if (elstAtom == null) {
return null;
}
ParsableByteArray elstData = elstAtom.data;
elstData.setPosition(Atom.HEADER_SIZE);
int fullAtom = elstData.readInt();
int version = Atom.parseFullAtomVersion(fullAtom);
int entryCount = elstData.readUnsignedIntToInt();
long[] editListDurations = new long[entryCount];
long[] editListMediaTimes = new long[entryCount];
for (int i = 0; i < entryCount; i++) {
editListDurations[i] =
version == 1 ? elstData.readUnsignedLongToLong() : elstData.readUnsignedInt();
editListMediaTimes[i] = version == 1 ? elstData.readLong() : elstData.readInt();
int mediaRateInteger = elstData.readShort();
if (mediaRateInteger != 1) {
// The extractor does not handle dwell edits (mediaRateInteger == 0).
throw new IllegalArgumentException("Unsupported media rate.");
}
elstData.skipBytes(2);
}
return Pair.create(editListDurations, editListMediaTimes);
}
private static float parsePaspFromParent(ParsableByteArray parent, int position) {
parent.setPosition(position + Atom.HEADER_SIZE);
int hSpacing = parent.readUnsignedIntToInt();
int vSpacing = parent.readUnsignedIntToInt();
return (float) hSpacing / vSpacing;
}
private static void parseAudioSampleEntry(
ParsableByteArray parent,
int atomType,
int position,
int size,
int trackId,
String language,
boolean isQuickTime,
@Nullable DrmInitData drmInitData,
StsdData out,
int entryIndex)
throws ParserException {
parent.setPosition(position + Atom.HEADER_SIZE + StsdData.STSD_HEADER_SIZE);
int quickTimeSoundDescriptionVersion = 0;
if (isQuickTime) {
quickTimeSoundDescriptionVersion = parent.readUnsignedShort();
parent.skipBytes(6);
} else {
parent.skipBytes(8);
}
int channelCount;
int sampleRate;
@C.PcmEncoding int pcmEncoding = Format.NO_VALUE;
@Nullable String codecs = null;
if (quickTimeSoundDescriptionVersion == 0 || quickTimeSoundDescriptionVersion == 1) {
channelCount = parent.readUnsignedShort();
parent.skipBytes(6); // sampleSize, compressionId, packetSize.
sampleRate = parent.readUnsignedFixedPoint1616();
if (quickTimeSoundDescriptionVersion == 1) {
parent.skipBytes(16);
}
} else if (quickTimeSoundDescriptionVersion == 2) {
parent.skipBytes(16); // always[3,16,Minus2,0,65536], sizeOfStructOnly
sampleRate = (int) Math.round(parent.readDouble());
channelCount = parent.readUnsignedIntToInt();
// Skip always7F000000, sampleSize, formatSpecificFlags, constBytesPerAudioPacket,
// constLPCMFramesPerAudioPacket.
parent.skipBytes(20);
} else {
// Unsupported version.
return;
}
int childPosition = parent.getPosition();
if (atomType == Atom.TYPE_enca) {
@Nullable
Pair<Integer, TrackEncryptionBox> sampleEntryEncryptionData =
parseSampleEntryEncryptionData(parent, position, size);
if (sampleEntryEncryptionData != null) {
atomType = sampleEntryEncryptionData.first;
drmInitData = drmInitData == null ? null
: drmInitData.copyWithSchemeType(sampleEntryEncryptionData.second.schemeType);
out.trackEncryptionBoxes[entryIndex] = sampleEntryEncryptionData.second;
}
parent.setPosition(childPosition);
}
// TODO: Uncomment when [Internal: b/63092960] is fixed.
// else {
// drmInitData = null;
// }
// If the atom type determines a MIME type, set it immediately.
@Nullable String mimeType = null;
if (atomType == Atom.TYPE_ac_3) {
mimeType = MimeTypes.AUDIO_AC3;
} else if (atomType == Atom.TYPE_ec_3) {
mimeType = MimeTypes.AUDIO_E_AC3;
} else if (atomType == Atom.TYPE_ac_4) {
mimeType = MimeTypes.AUDIO_AC4;
} else if (atomType == Atom.TYPE_dtsc) {
mimeType = MimeTypes.AUDIO_DTS;
} else if (atomType == Atom.TYPE_dtsh || atomType == Atom.TYPE_dtsl) {
mimeType = MimeTypes.AUDIO_DTS_HD;
} else if (atomType == Atom.TYPE_dtse) {
mimeType = MimeTypes.AUDIO_DTS_EXPRESS;
} else if (atomType == Atom.TYPE_samr) {
mimeType = MimeTypes.AUDIO_AMR_NB;
} else if (atomType == Atom.TYPE_sawb) {
mimeType = MimeTypes.AUDIO_AMR_WB;
} else if (atomType == Atom.TYPE_lpcm || atomType == Atom.TYPE_sowt) {
mimeType = MimeTypes.AUDIO_RAW;
pcmEncoding = C.ENCODING_PCM_16BIT;
} else if (atomType == Atom.TYPE_twos) {
mimeType = MimeTypes.AUDIO_RAW;
pcmEncoding = C.ENCODING_PCM_16BIT_BIG_ENDIAN;
} else if (atomType == Atom.TYPE__mp3) {
mimeType = MimeTypes.AUDIO_MPEG;
} else if (atomType == Atom.TYPE_alac) {
mimeType = MimeTypes.AUDIO_ALAC;
} else if (atomType == Atom.TYPE_alaw) {
mimeType = MimeTypes.AUDIO_ALAW;
} else if (atomType == Atom.TYPE_ulaw) {
mimeType = MimeTypes.AUDIO_MLAW;
} else if (atomType == Atom.TYPE_Opus) {
mimeType = MimeTypes.AUDIO_OPUS;
} else if (atomType == Atom.TYPE_fLaC) {
mimeType = MimeTypes.AUDIO_FLAC;
}
@Nullable byte[] initializationData = null;
while (childPosition - position < size) {
parent.setPosition(childPosition);
int childAtomSize = parent.readInt();
Assertions.checkState(childAtomSize > 0, "childAtomSize should be positive");
int childAtomType = parent.readInt();
if (childAtomType == Atom.TYPE_esds || (isQuickTime && childAtomType == Atom.TYPE_wave)) {
int esdsAtomPosition = childAtomType == Atom.TYPE_esds ? childPosition
: findEsdsPosition(parent, childPosition, childAtomSize);
if (esdsAtomPosition != C.POSITION_UNSET) {
Pair<@NullableType String, byte @NullableType []> mimeTypeAndInitializationData =
parseEsdsFromParent(parent, esdsAtomPosition);
mimeType = mimeTypeAndInitializationData.first;
initializationData = mimeTypeAndInitializationData.second;
if (MimeTypes.AUDIO_AAC.equals(mimeType) && initializationData != null) {
// Update sampleRate and channelCount from the AudioSpecificConfig initialization data,
// which is more reliable. See [Internal: b/10903778].
AacUtil.Config aacConfig = AacUtil.parseAudioSpecificConfig(initializationData);
sampleRate = aacConfig.sampleRateHz;
channelCount = aacConfig.channelCount;
codecs = aacConfig.codecs;
}
}
} else if (childAtomType == Atom.TYPE_dac3) {
parent.setPosition(Atom.HEADER_SIZE + childPosition);
out.format = Ac3Util.parseAc3AnnexFFormat(parent, Integer.toString(trackId), language,
drmInitData);
} else if (childAtomType == Atom.TYPE_dec3) {
parent.setPosition(Atom.HEADER_SIZE + childPosition);
out.format = Ac3Util.parseEAc3AnnexFFormat(parent, Integer.toString(trackId), language,
drmInitData);
} else if (childAtomType == Atom.TYPE_dac4) {
parent.setPosition(Atom.HEADER_SIZE + childPosition);
out.format =
Ac4Util.parseAc4AnnexEFormat(parent, Integer.toString(trackId), language, drmInitData);
} else if (childAtomType == Atom.TYPE_ddts) {
out.format =
new Format.Builder()
.setId(trackId)
.setSampleMimeType(mimeType)
.setChannelCount(channelCount)
.setSampleRate(sampleRate)
.setDrmInitData(drmInitData)
.setLanguage(language)
.build();
} else if (childAtomType == Atom.TYPE_dOps) {
// Build an Opus Identification Header (defined in RFC-7845) by concatenating the Opus Magic
// Signature and the body of the dOps atom.
int childAtomBodySize = childAtomSize - Atom.HEADER_SIZE;
initializationData = new byte[opusMagic.length + childAtomBodySize];
System.arraycopy(opusMagic, 0, initializationData, 0, opusMagic.length);
parent.setPosition(childPosition + Atom.HEADER_SIZE);
parent.readBytes(initializationData, opusMagic.length, childAtomBodySize);
} else if (childAtomType == Atom.TYPE_dfLa) {
int childAtomBodySize = childAtomSize - Atom.FULL_HEADER_SIZE;
initializationData = new byte[4 + childAtomBodySize];
initializationData[0] = 0x66; // f
initializationData[1] = 0x4C; // L
initializationData[2] = 0x61; // a
initializationData[3] = 0x43; // C
parent.setPosition(childPosition + Atom.FULL_HEADER_SIZE);
parent.readBytes(initializationData, /* offset= */ 4, childAtomBodySize);
} else if (childAtomType == Atom.TYPE_alac) {
int childAtomBodySize = childAtomSize - Atom.FULL_HEADER_SIZE;
initializationData = new byte[childAtomBodySize];
parent.setPosition(childPosition + Atom.FULL_HEADER_SIZE);
parent.readBytes(initializationData, /* offset= */ 0, childAtomBodySize);
// Update sampleRate and channelCount from the AudioSpecificConfig initialization data,
// which is more reliable. See https://github.com/google/ExoPlayer/pull/6629.
Pair<Integer, Integer> audioSpecificConfig =
CodecSpecificDataUtil.parseAlacAudioSpecificConfig(initializationData);
sampleRate = audioSpecificConfig.first;
channelCount = audioSpecificConfig.second;
}
childPosition += childAtomSize;
}
if (out.format == null && mimeType != null) {
out.format =
new Format.Builder()
.setId(trackId)
.setSampleMimeType(mimeType)
.setCodecs(codecs)
.setChannelCount(channelCount)
.setSampleRate(sampleRate)
.setEncoding(pcmEncoding)
.setInitializationData(
initializationData == null ? null : Collections.singletonList(initializationData))
.setDrmInitData(drmInitData)
.setLanguage(language)
.build();
}
}
/**
* Returns the position of the esds box within a parent, or {@link C#POSITION_UNSET} if no esds
* box is found
*/
private static int findEsdsPosition(ParsableByteArray parent, int position, int size) {
int childAtomPosition = parent.getPosition();
while (childAtomPosition - position < size) {
parent.setPosition(childAtomPosition);
int childAtomSize = parent.readInt();
Assertions.checkState(childAtomSize > 0, "childAtomSize should be positive");
int childType = parent.readInt();
if (childType == Atom.TYPE_esds) {
return childAtomPosition;
}
childAtomPosition += childAtomSize;
}
return C.POSITION_UNSET;
}
/** Returns codec-specific initialization data contained in an esds box. */
private static Pair<@NullableType String, byte @NullableType []> parseEsdsFromParent(
ParsableByteArray parent, int position) {
parent.setPosition(position + Atom.HEADER_SIZE + 4);
// Start of the ES_Descriptor (defined in ISO/IEC 14496-1)
parent.skipBytes(1); // ES_Descriptor tag
parseExpandableClassSize(parent);
parent.skipBytes(2); // ES_ID
int flags = parent.readUnsignedByte();
if ((flags & 0x80 /* streamDependenceFlag */) != 0) {
parent.skipBytes(2);
}
if ((flags & 0x40 /* URL_Flag */) != 0) {
parent.skipBytes(parent.readUnsignedShort());
}
if ((flags & 0x20 /* OCRstreamFlag */) != 0) {
parent.skipBytes(2);
}
// Start of the DecoderConfigDescriptor (defined in ISO/IEC 14496-1)
parent.skipBytes(1); // DecoderConfigDescriptor tag
parseExpandableClassSize(parent);
// Set the MIME type based on the object type indication (ISO/IEC 14496-1 table 5).
int objectTypeIndication = parent.readUnsignedByte();
@Nullable String mimeType = getMimeTypeFromMp4ObjectType(objectTypeIndication);
if (MimeTypes.AUDIO_MPEG.equals(mimeType)
|| MimeTypes.AUDIO_DTS.equals(mimeType)
|| MimeTypes.AUDIO_DTS_HD.equals(mimeType)) {
return Pair.create(mimeType, null);
}
parent.skipBytes(12);
// Start of the DecoderSpecificInfo.
parent.skipBytes(1); // DecoderSpecificInfo tag
int initializationDataSize = parseExpandableClassSize(parent);
byte[] initializationData = new byte[initializationDataSize];
parent.readBytes(initializationData, 0, initializationDataSize);
return Pair.create(mimeType, initializationData);
}
/**
* Parses encryption data from an audio/video sample entry, returning a pair consisting of the
* unencrypted atom type and a {@link TrackEncryptionBox}. Null is returned if no common
* encryption sinf atom was present.
*/
@Nullable
private static Pair<Integer, TrackEncryptionBox> parseSampleEntryEncryptionData(
ParsableByteArray parent, int position, int size) {
int childPosition = parent.getPosition();
while (childPosition - position < size) {
parent.setPosition(childPosition);
int childAtomSize = parent.readInt();
Assertions.checkState(childAtomSize > 0, "childAtomSize should be positive");
int childAtomType = parent.readInt();
if (childAtomType == Atom.TYPE_sinf) {
@Nullable
Pair<Integer, TrackEncryptionBox> result =
parseCommonEncryptionSinfFromParent(parent, childPosition, childAtomSize);
if (result != null) {
return result;
}
}
childPosition += childAtomSize;
}
return null;
}
@Nullable
/* package */ static Pair<Integer, TrackEncryptionBox> parseCommonEncryptionSinfFromParent(
ParsableByteArray parent, int position, int size) {
int childPosition = position + Atom.HEADER_SIZE;
int schemeInformationBoxPosition = C.POSITION_UNSET;
int schemeInformationBoxSize = 0;
@Nullable String schemeType = null;
@Nullable Integer dataFormat = null;
while (childPosition - position < size) {
parent.setPosition(childPosition);
int childAtomSize = parent.readInt();
int childAtomType = parent.readInt();
if (childAtomType == Atom.TYPE_frma) {
dataFormat = parent.readInt();
} else if (childAtomType == Atom.TYPE_schm) {
parent.skipBytes(4);
// Common encryption scheme_type values are defined in ISO/IEC 23001-7:2016, section 4.1.
schemeType = parent.readString(4);
} else if (childAtomType == Atom.TYPE_schi) {
schemeInformationBoxPosition = childPosition;
schemeInformationBoxSize = childAtomSize;
}
childPosition += childAtomSize;
}
if (C.CENC_TYPE_cenc.equals(schemeType) || C.CENC_TYPE_cbc1.equals(schemeType)
|| C.CENC_TYPE_cens.equals(schemeType) || C.CENC_TYPE_cbcs.equals(schemeType)) {
Assertions.checkStateNotNull(dataFormat, "frma atom is mandatory");
Assertions.checkState(
schemeInformationBoxPosition != C.POSITION_UNSET, "schi atom is mandatory");
TrackEncryptionBox encryptionBox =
Assertions.checkStateNotNull(
parseSchiFromParent(
parent, schemeInformationBoxPosition, schemeInformationBoxSize, schemeType),
"tenc atom is mandatory");
return Pair.create(dataFormat, encryptionBox);
} else {
return null;
}
}
@Nullable
private static TrackEncryptionBox parseSchiFromParent(
ParsableByteArray parent, int position, int size, String schemeType) {
int childPosition = position + Atom.HEADER_SIZE;
while (childPosition - position < size) {
parent.setPosition(childPosition);
int childAtomSize = parent.readInt();
int childAtomType = parent.readInt();
if (childAtomType == Atom.TYPE_tenc) {
int fullAtom = parent.readInt();
int version = Atom.parseFullAtomVersion(fullAtom);
parent.skipBytes(1); // reserved = 0.
int defaultCryptByteBlock = 0;
int defaultSkipByteBlock = 0;
if (version == 0) {
parent.skipBytes(1); // reserved = 0.
} else /* version 1 or greater */ {
int patternByte = parent.readUnsignedByte();
defaultCryptByteBlock = (patternByte & 0xF0) >> 4;
defaultSkipByteBlock = patternByte & 0x0F;
}
boolean defaultIsProtected = parent.readUnsignedByte() == 1;
int defaultPerSampleIvSize = parent.readUnsignedByte();
byte[] defaultKeyId = new byte[16];
parent.readBytes(defaultKeyId, 0, defaultKeyId.length);
byte[] constantIv = null;
if (defaultIsProtected && defaultPerSampleIvSize == 0) {
int constantIvSize = parent.readUnsignedByte();
constantIv = new byte[constantIvSize];
parent.readBytes(constantIv, 0, constantIvSize);
}
return new TrackEncryptionBox(defaultIsProtected, schemeType, defaultPerSampleIvSize,
defaultKeyId, defaultCryptByteBlock, defaultSkipByteBlock, constantIv);
}
childPosition += childAtomSize;
}
return null;
}
/** Parses the proj box from sv3d box, as specified by https://github.com/google/spatial-media. */
@Nullable
private static byte[] parseProjFromParent(ParsableByteArray parent, int position, int size) {
int childPosition = position + Atom.HEADER_SIZE;
while (childPosition - position < size) {
parent.setPosition(childPosition);
int childAtomSize = parent.readInt();
int childAtomType = parent.readInt();
if (childAtomType == Atom.TYPE_proj) {
return Arrays.copyOfRange(parent.data, childPosition, childPosition + childAtomSize);
}
childPosition += childAtomSize;
}
return null;
}
/** Parses the size of an expandable class, as specified by ISO/IEC 14496-1 subsection 8.3.3. */
private static int parseExpandableClassSize(ParsableByteArray data) {
int currentByte = data.readUnsignedByte();
int size = currentByte & 0x7F;
while ((currentByte & 0x80) == 0x80) {
currentByte = data.readUnsignedByte();
size = (size << 7) | (currentByte & 0x7F);
}
return size;
}
/** Returns whether it's possible to apply the specified edit using gapless playback info. */
private static boolean canApplyEditWithGaplessInfo(
long[] timestamps, long duration, long editStartTime, long editEndTime) {
int lastIndex = timestamps.length - 1;
int latestDelayIndex = Util.constrainValue(MAX_GAPLESS_TRIM_SIZE_SAMPLES, 0, lastIndex);
int earliestPaddingIndex =
Util.constrainValue(timestamps.length - MAX_GAPLESS_TRIM_SIZE_SAMPLES, 0, lastIndex);
return timestamps[0] <= editStartTime
&& editStartTime < timestamps[latestDelayIndex]
&& timestamps[earliestPaddingIndex] < editEndTime
&& editEndTime <= duration;
}
private AtomParsers() {
// Prevent instantiation.
}
private static final class ChunkIterator {
public final int length;
public int index;
public int numSamples;
public long offset;
private final boolean chunkOffsetsAreLongs;
private final ParsableByteArray chunkOffsets;
private final ParsableByteArray stsc;
private int nextSamplesPerChunkChangeIndex;
private int remainingSamplesPerChunkChanges;
public ChunkIterator(ParsableByteArray stsc, ParsableByteArray chunkOffsets,
boolean chunkOffsetsAreLongs) {
this.stsc = stsc;
this.chunkOffsets = chunkOffsets;
this.chunkOffsetsAreLongs = chunkOffsetsAreLongs;
chunkOffsets.setPosition(Atom.FULL_HEADER_SIZE);
length = chunkOffsets.readUnsignedIntToInt();
stsc.setPosition(Atom.FULL_HEADER_SIZE);
remainingSamplesPerChunkChanges = stsc.readUnsignedIntToInt();
Assertions.checkState(stsc.readInt() == 1, "first_chunk must be 1");
index = -1;
}
public boolean moveNext() {
if (++index == length) {
return false;
}
offset = chunkOffsetsAreLongs ? chunkOffsets.readUnsignedLongToLong()
: chunkOffsets.readUnsignedInt();
if (index == nextSamplesPerChunkChangeIndex) {
numSamples = stsc.readUnsignedIntToInt();
stsc.skipBytes(4); // Skip sample_description_index
nextSamplesPerChunkChangeIndex = --remainingSamplesPerChunkChanges > 0
? (stsc.readUnsignedIntToInt() - 1) : C.INDEX_UNSET;
}
return true;
}
}
/**
* Holds data parsed from a tkhd atom.
*/
private static final class TkhdData {
private final int id;
private final long duration;
private final int rotationDegrees;
public TkhdData(int id, long duration, int rotationDegrees) {
this.id = id;
this.duration = duration;
this.rotationDegrees = rotationDegrees;
}
}
/**
* Holds data parsed from an stsd atom and its children.
*/
private static final class StsdData {
public static final int STSD_HEADER_SIZE = 8;
public final TrackEncryptionBox[] trackEncryptionBoxes;
@Nullable public Format format;
public int nalUnitLengthFieldLength;
@Track.Transformation public int requiredSampleTransformation;
public StsdData(int numberOfEntries) {
trackEncryptionBoxes = new TrackEncryptionBox[numberOfEntries];
requiredSampleTransformation = Track.TRANSFORMATION_NONE;
}
}
/**
* A box containing sample sizes (e.g. stsz, stz2).
*/
private interface SampleSizeBox {
/**
* Returns the number of samples.
*/
int getSampleCount();
/**
* Returns the size for the next sample.
*/
int readNextSampleSize();
/**
* Returns whether samples have a fixed size.
*/
boolean isFixedSampleSize();
}
/**
* An stsz sample size box.
*/
/* package */ static final class StszSampleSizeBox implements SampleSizeBox {
private final int fixedSampleSize;
private final int sampleCount;
private final ParsableByteArray data;
public StszSampleSizeBox(Atom.LeafAtom stszAtom) {
data = stszAtom.data;
data.setPosition(Atom.FULL_HEADER_SIZE);
fixedSampleSize = data.readUnsignedIntToInt();
sampleCount = data.readUnsignedIntToInt();
}
@Override
public int getSampleCount() {
return sampleCount;
}
@Override
public int readNextSampleSize() {
return fixedSampleSize == 0 ? data.readUnsignedIntToInt() : fixedSampleSize;
}
@Override
public boolean isFixedSampleSize() {
return fixedSampleSize != 0;
}
}
/**
* An stz2 sample size box.
*/
/* package */ static final class Stz2SampleSizeBox implements SampleSizeBox {
private final ParsableByteArray data;
private final int sampleCount;
private final int fieldSize; // Can be 4, 8, or 16.
// Used only if fieldSize == 4.
private int sampleIndex;
private int currentByte;
public Stz2SampleSizeBox(Atom.LeafAtom stz2Atom) {
data = stz2Atom.data;
data.setPosition(Atom.FULL_HEADER_SIZE);
fieldSize = data.readUnsignedIntToInt() & 0x000000FF;
sampleCount = data.readUnsignedIntToInt();
}
@Override
public int getSampleCount() {
return sampleCount;
}
@Override
public int readNextSampleSize() {
if (fieldSize == 8) {
return data.readUnsignedByte();
} else if (fieldSize == 16) {
return data.readUnsignedShort();
} else {
// fieldSize == 4.
if ((sampleIndex++ % 2) == 0) {
// Read the next byte into our cached byte when we are reading the upper bits.
currentByte = data.readUnsignedByte();
// Read the upper bits from the byte and shift them to the lower 4 bits.
return (currentByte & 0xF0) >> 4;
} else {
// Mask out the upper 4 bits of the last byte we read.
return currentByte & 0x0F;
}
}
}
@Override
public boolean isFixedSampleSize() {
return false;
}
}
}
| library/extractor/src/main/java/com/google/android/exoplayer2/extractor/mp4/AtomParsers.java | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.extractor.mp4;
import static com.google.android.exoplayer2.util.MimeTypes.getMimeTypeFromMp4ObjectType;
import android.util.Pair;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.audio.AacUtil;
import com.google.android.exoplayer2.audio.Ac3Util;
import com.google.android.exoplayer2.audio.Ac4Util;
import com.google.android.exoplayer2.drm.DrmInitData;
import com.google.android.exoplayer2.extractor.GaplessInfoHolder;
import com.google.android.exoplayer2.metadata.Metadata;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.CodecSpecificDataUtil;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.ParsableByteArray;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.AvcConfig;
import com.google.android.exoplayer2.video.DolbyVisionConfig;
import com.google.android.exoplayer2.video.HevcConfig;
import com.google.common.base.Function;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.checkerframework.checker.nullness.compatqual.NullableType;
/** Utility methods for parsing MP4 format atom payloads according to ISO/IEC 14496-12. */
@SuppressWarnings({"ConstantField"})
/* package */ final class AtomParsers {
private static final String TAG = "AtomParsers";
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_vide = 0x76696465;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_soun = 0x736f756e;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_text = 0x74657874;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_sbtl = 0x7362746c;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_subt = 0x73756274;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_clcp = 0x636c6370;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_meta = 0x6d657461;
@SuppressWarnings("ConstantCaseForConstants")
private static final int TYPE_mdta = 0x6d647461;
/**
* The threshold number of samples to trim from the start/end of an audio track when applying an
* edit below which gapless info can be used (rather than removing samples from the sample table).
*/
private static final int MAX_GAPLESS_TRIM_SIZE_SAMPLES = 4;
/** The magic signature for an Opus Identification header, as defined in RFC-7845. */
private static final byte[] opusMagic = Util.getUtf8Bytes("OpusHead");
/**
* Parse the trak atoms in a moov atom (defined in ISO/IEC 14496-12).
*
* @param moov Moov atom to decode.
* @param gaplessInfoHolder Holder to populate with gapless playback information.
* @param duration The duration in units of the timescale declared in the mvhd atom, or {@link
* C#TIME_UNSET} if the duration should be parsed from the tkhd atom.
* @param drmInitData {@link DrmInitData} to be included in the format, or {@code null}.
* @param ignoreEditLists Whether to ignore any edit lists in the trak boxes.
* @param isQuickTime True for QuickTime media. False otherwise.
* @param modifyTrackFunction A function to apply to the {@link Track Tracks} in the result.
* @return A list of {@link TrackSampleTable} instances.
* @throws ParserException Thrown if the trak atoms can't be parsed.
*/
public static List<TrackSampleTable> parseTraks(
Atom.ContainerAtom moov,
GaplessInfoHolder gaplessInfoHolder,
long duration,
@Nullable DrmInitData drmInitData,
boolean ignoreEditLists,
boolean isQuickTime,
Function<Track, Track> modifyTrackFunction)
throws ParserException {
List<TrackSampleTable> trackSampleTables = new ArrayList<>();
for (int i = 0; i < moov.containerChildren.size(); i++) {
Atom.ContainerAtom atom = moov.containerChildren.get(i);
if (atom.type != Atom.TYPE_trak) {
continue;
}
@Nullable
Track track =
modifyTrackFunction.apply(
parseTrak(
atom,
moov.getLeafAtomOfType(Atom.TYPE_mvhd),
duration,
drmInitData,
ignoreEditLists,
isQuickTime));
if (track == null) {
continue;
}
Atom.ContainerAtom stblAtom =
atom.getContainerAtomOfType(Atom.TYPE_mdia)
.getContainerAtomOfType(Atom.TYPE_minf)
.getContainerAtomOfType(Atom.TYPE_stbl);
TrackSampleTable trackSampleTable = parseStbl(track, stblAtom, gaplessInfoHolder);
trackSampleTables.add(trackSampleTable);
}
return trackSampleTables;
}
/**
* Parses a udta atom.
*
* @param udtaAtom The udta (user data) atom to decode.
* @param isQuickTime True for QuickTime media. False otherwise.
* @return Parsed metadata, or null.
*/
@Nullable
public static Metadata parseUdta(Atom.LeafAtom udtaAtom, boolean isQuickTime) {
if (isQuickTime) {
// Meta boxes are regular boxes rather than full boxes in QuickTime. For now, don't try and
// decode one.
return null;
}
ParsableByteArray udtaData = udtaAtom.data;
udtaData.setPosition(Atom.HEADER_SIZE);
while (udtaData.bytesLeft() >= Atom.HEADER_SIZE) {
int atomPosition = udtaData.getPosition();
int atomSize = udtaData.readInt();
int atomType = udtaData.readInt();
if (atomType == Atom.TYPE_meta) {
udtaData.setPosition(atomPosition);
return parseUdtaMeta(udtaData, atomPosition + atomSize);
}
udtaData.setPosition(atomPosition + atomSize);
}
return null;
}
/**
* Parses a metadata meta atom if it contains metadata with handler 'mdta'.
*
* @param meta The metadata atom to decode.
* @return Parsed metadata, or null.
*/
@Nullable
public static Metadata parseMdtaFromMeta(Atom.ContainerAtom meta) {
@Nullable Atom.LeafAtom hdlrAtom = meta.getLeafAtomOfType(Atom.TYPE_hdlr);
@Nullable Atom.LeafAtom keysAtom = meta.getLeafAtomOfType(Atom.TYPE_keys);
@Nullable Atom.LeafAtom ilstAtom = meta.getLeafAtomOfType(Atom.TYPE_ilst);
if (hdlrAtom == null
|| keysAtom == null
|| ilstAtom == null
|| parseHdlr(hdlrAtom.data) != TYPE_mdta) {
// There isn't enough information to parse the metadata, or the handler type is unexpected.
return null;
}
// Parse metadata keys.
ParsableByteArray keys = keysAtom.data;
keys.setPosition(Atom.FULL_HEADER_SIZE);
int entryCount = keys.readInt();
String[] keyNames = new String[entryCount];
for (int i = 0; i < entryCount; i++) {
int entrySize = keys.readInt();
keys.skipBytes(4); // keyNamespace
int keySize = entrySize - 8;
keyNames[i] = keys.readString(keySize);
}
// Parse metadata items.
ParsableByteArray ilst = ilstAtom.data;
ilst.setPosition(Atom.HEADER_SIZE);
ArrayList<Metadata.Entry> entries = new ArrayList<>();
while (ilst.bytesLeft() > Atom.HEADER_SIZE) {
int atomPosition = ilst.getPosition();
int atomSize = ilst.readInt();
int keyIndex = ilst.readInt() - 1;
if (keyIndex >= 0 && keyIndex < keyNames.length) {
String key = keyNames[keyIndex];
@Nullable
Metadata.Entry entry =
MetadataUtil.parseMdtaMetadataEntryFromIlst(ilst, atomPosition + atomSize, key);
if (entry != null) {
entries.add(entry);
}
} else {
Log.w(TAG, "Skipped metadata with unknown key index: " + keyIndex);
}
ilst.setPosition(atomPosition + atomSize);
}
return entries.isEmpty() ? null : new Metadata(entries);
}
/**
* Parses a trak atom (defined in ISO/IEC 14496-12).
*
* @param trak Atom to decode.
* @param mvhd Movie header atom, used to get the timescale.
* @param duration The duration in units of the timescale declared in the mvhd atom, or {@link
* C#TIME_UNSET} if the duration should be parsed from the tkhd atom.
* @param drmInitData {@link DrmInitData} to be included in the format, or {@code null}.
* @param ignoreEditLists Whether to ignore any edit lists in the trak box.
* @param isQuickTime True for QuickTime media. False otherwise.
* @return A {@link Track} instance, or {@code null} if the track's type isn't supported.
* @throws ParserException Thrown if the trak atom can't be parsed.
*/
@Nullable
private static Track parseTrak(
Atom.ContainerAtom trak,
Atom.LeafAtom mvhd,
long duration,
@Nullable DrmInitData drmInitData,
boolean ignoreEditLists,
boolean isQuickTime)
throws ParserException {
Atom.ContainerAtom mdia = trak.getContainerAtomOfType(Atom.TYPE_mdia);
int trackType = getTrackTypeForHdlr(parseHdlr(mdia.getLeafAtomOfType(Atom.TYPE_hdlr).data));
if (trackType == C.TRACK_TYPE_UNKNOWN) {
return null;
}
TkhdData tkhdData = parseTkhd(trak.getLeafAtomOfType(Atom.TYPE_tkhd).data);
if (duration == C.TIME_UNSET) {
duration = tkhdData.duration;
}
long movieTimescale = parseMvhd(mvhd.data);
long durationUs;
if (duration == C.TIME_UNSET) {
durationUs = C.TIME_UNSET;
} else {
durationUs = Util.scaleLargeTimestamp(duration, C.MICROS_PER_SECOND, movieTimescale);
}
Atom.ContainerAtom stbl = mdia.getContainerAtomOfType(Atom.TYPE_minf)
.getContainerAtomOfType(Atom.TYPE_stbl);
Pair<Long, String> mdhdData = parseMdhd(mdia.getLeafAtomOfType(Atom.TYPE_mdhd).data);
StsdData stsdData = parseStsd(stbl.getLeafAtomOfType(Atom.TYPE_stsd).data, tkhdData.id,
tkhdData.rotationDegrees, mdhdData.second, drmInitData, isQuickTime);
@Nullable long[] editListDurations = null;
@Nullable long[] editListMediaTimes = null;
if (!ignoreEditLists) {
@Nullable Atom.ContainerAtom edtsAtom = trak.getContainerAtomOfType(Atom.TYPE_edts);
if (edtsAtom != null) {
@Nullable Pair<long[], long[]> edtsData = parseEdts(edtsAtom);
if (edtsData != null) {
editListDurations = edtsData.first;
editListMediaTimes = edtsData.second;
}
}
}
return stsdData.format == null ? null
: new Track(tkhdData.id, trackType, mdhdData.first, movieTimescale, durationUs,
stsdData.format, stsdData.requiredSampleTransformation, stsdData.trackEncryptionBoxes,
stsdData.nalUnitLengthFieldLength, editListDurations, editListMediaTimes);
}
/**
* Parses an stbl atom (defined in ISO/IEC 14496-12).
*
* @param track Track to which this sample table corresponds.
* @param stblAtom stbl (sample table) atom to decode.
* @param gaplessInfoHolder Holder to populate with gapless playback information.
* @return Sample table described by the stbl atom.
* @throws ParserException Thrown if the stbl atom can't be parsed.
*/
private static TrackSampleTable parseStbl(
Track track, Atom.ContainerAtom stblAtom, GaplessInfoHolder gaplessInfoHolder)
throws ParserException {
SampleSizeBox sampleSizeBox;
@Nullable Atom.LeafAtom stszAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stsz);
if (stszAtom != null) {
sampleSizeBox = new StszSampleSizeBox(stszAtom);
} else {
@Nullable Atom.LeafAtom stz2Atom = stblAtom.getLeafAtomOfType(Atom.TYPE_stz2);
if (stz2Atom == null) {
throw new ParserException("Track has no sample table size information");
}
sampleSizeBox = new Stz2SampleSizeBox(stz2Atom);
}
int sampleCount = sampleSizeBox.getSampleCount();
if (sampleCount == 0) {
return new TrackSampleTable(
track,
/* offsets= */ new long[0],
/* sizes= */ new int[0],
/* maximumSize= */ 0,
/* timestampsUs= */ new long[0],
/* flags= */ new int[0],
/* durationUs= */ 0);
}
// Entries are byte offsets of chunks.
boolean chunkOffsetsAreLongs = false;
@Nullable Atom.LeafAtom chunkOffsetsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stco);
if (chunkOffsetsAtom == null) {
chunkOffsetsAreLongs = true;
chunkOffsetsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_co64);
}
ParsableByteArray chunkOffsets = chunkOffsetsAtom.data;
// Entries are (chunk number, number of samples per chunk, sample description index).
ParsableByteArray stsc = stblAtom.getLeafAtomOfType(Atom.TYPE_stsc).data;
// Entries are (number of samples, timestamp delta between those samples).
ParsableByteArray stts = stblAtom.getLeafAtomOfType(Atom.TYPE_stts).data;
// Entries are the indices of samples that are synchronization samples.
@Nullable Atom.LeafAtom stssAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stss);
@Nullable ParsableByteArray stss = stssAtom != null ? stssAtom.data : null;
// Entries are (number of samples, timestamp offset).
@Nullable Atom.LeafAtom cttsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_ctts);
@Nullable ParsableByteArray ctts = cttsAtom != null ? cttsAtom.data : null;
// Prepare to read chunk information.
ChunkIterator chunkIterator = new ChunkIterator(stsc, chunkOffsets, chunkOffsetsAreLongs);
// Prepare to read sample timestamps.
stts.setPosition(Atom.FULL_HEADER_SIZE);
int remainingTimestampDeltaChanges = stts.readUnsignedIntToInt() - 1;
int remainingSamplesAtTimestampDelta = stts.readUnsignedIntToInt();
int timestampDeltaInTimeUnits = stts.readUnsignedIntToInt();
// Prepare to read sample timestamp offsets, if ctts is present.
int remainingSamplesAtTimestampOffset = 0;
int remainingTimestampOffsetChanges = 0;
int timestampOffset = 0;
if (ctts != null) {
ctts.setPosition(Atom.FULL_HEADER_SIZE);
remainingTimestampOffsetChanges = ctts.readUnsignedIntToInt();
}
int nextSynchronizationSampleIndex = C.INDEX_UNSET;
int remainingSynchronizationSamples = 0;
if (stss != null) {
stss.setPosition(Atom.FULL_HEADER_SIZE);
remainingSynchronizationSamples = stss.readUnsignedIntToInt();
if (remainingSynchronizationSamples > 0) {
nextSynchronizationSampleIndex = stss.readUnsignedIntToInt() - 1;
} else {
// Ignore empty stss boxes, which causes all samples to be treated as sync samples.
stss = null;
}
}
// Fixed sample size raw audio may need to be rechunked.
boolean isFixedSampleSizeRawAudio =
sampleSizeBox.isFixedSampleSize()
&& MimeTypes.AUDIO_RAW.equals(track.format.sampleMimeType)
&& remainingTimestampDeltaChanges == 0
&& remainingTimestampOffsetChanges == 0
&& remainingSynchronizationSamples == 0;
long[] offsets;
int[] sizes;
int maximumSize = 0;
long[] timestamps;
int[] flags;
long timestampTimeUnits = 0;
long duration;
if (isFixedSampleSizeRawAudio) {
long[] chunkOffsetsBytes = new long[chunkIterator.length];
int[] chunkSampleCounts = new int[chunkIterator.length];
while (chunkIterator.moveNext()) {
chunkOffsetsBytes[chunkIterator.index] = chunkIterator.offset;
chunkSampleCounts[chunkIterator.index] = chunkIterator.numSamples;
}
int fixedSampleSize = Util.getPcmFrameSize(track.format.encoding, track.format.channelCount);
FixedSampleSizeRechunker.Results rechunkedResults =
FixedSampleSizeRechunker.rechunk(
fixedSampleSize, chunkOffsetsBytes, chunkSampleCounts, timestampDeltaInTimeUnits);
offsets = rechunkedResults.offsets;
sizes = rechunkedResults.sizes;
maximumSize = rechunkedResults.maximumSize;
timestamps = rechunkedResults.timestamps;
flags = rechunkedResults.flags;
duration = rechunkedResults.duration;
} else {
offsets = new long[sampleCount];
sizes = new int[sampleCount];
timestamps = new long[sampleCount];
flags = new int[sampleCount];
long offset = 0;
int remainingSamplesInChunk = 0;
for (int i = 0; i < sampleCount; i++) {
// Advance to the next chunk if necessary.
boolean chunkDataComplete = true;
while (remainingSamplesInChunk == 0 && (chunkDataComplete = chunkIterator.moveNext())) {
offset = chunkIterator.offset;
remainingSamplesInChunk = chunkIterator.numSamples;
}
if (!chunkDataComplete) {
Log.w(TAG, "Unexpected end of chunk data");
sampleCount = i;
offsets = Arrays.copyOf(offsets, sampleCount);
sizes = Arrays.copyOf(sizes, sampleCount);
timestamps = Arrays.copyOf(timestamps, sampleCount);
flags = Arrays.copyOf(flags, sampleCount);
break;
}
// Add on the timestamp offset if ctts is present.
if (ctts != null) {
while (remainingSamplesAtTimestampOffset == 0 && remainingTimestampOffsetChanges > 0) {
remainingSamplesAtTimestampOffset = ctts.readUnsignedIntToInt();
// The BMFF spec (ISO/IEC 14496-12) states that sample offsets should be unsigned
// integers in version 0 ctts boxes, however some streams violate the spec and use
// signed integers instead. It's safe to always decode sample offsets as signed integers
// here, because unsigned integers will still be parsed correctly (unless their top bit
// is set, which is never true in practice because sample offsets are always small).
timestampOffset = ctts.readInt();
remainingTimestampOffsetChanges--;
}
remainingSamplesAtTimestampOffset--;
}
offsets[i] = offset;
sizes[i] = sampleSizeBox.readNextSampleSize();
if (sizes[i] > maximumSize) {
maximumSize = sizes[i];
}
timestamps[i] = timestampTimeUnits + timestampOffset;
// All samples are synchronization samples if the stss is not present.
flags[i] = stss == null ? C.BUFFER_FLAG_KEY_FRAME : 0;
if (i == nextSynchronizationSampleIndex) {
flags[i] = C.BUFFER_FLAG_KEY_FRAME;
remainingSynchronizationSamples--;
if (remainingSynchronizationSamples > 0) {
nextSynchronizationSampleIndex = stss.readUnsignedIntToInt() - 1;
}
}
// Add on the duration of this sample.
timestampTimeUnits += timestampDeltaInTimeUnits;
remainingSamplesAtTimestampDelta--;
if (remainingSamplesAtTimestampDelta == 0 && remainingTimestampDeltaChanges > 0) {
remainingSamplesAtTimestampDelta = stts.readUnsignedIntToInt();
// The BMFF spec (ISO/IEC 14496-12) states that sample deltas should be unsigned integers
// in stts boxes, however some streams violate the spec and use signed integers instead.
// See https://github.com/google/ExoPlayer/issues/3384. It's safe to always decode sample
// deltas as signed integers here, because unsigned integers will still be parsed
// correctly (unless their top bit is set, which is never true in practice because sample
// deltas are always small).
timestampDeltaInTimeUnits = stts.readInt();
remainingTimestampDeltaChanges--;
}
offset += sizes[i];
remainingSamplesInChunk--;
}
duration = timestampTimeUnits + timestampOffset;
// If the stbl's child boxes are not consistent the container is malformed, but the stream may
// still be playable.
boolean isCttsValid = true;
while (remainingTimestampOffsetChanges > 0) {
if (ctts.readUnsignedIntToInt() != 0) {
isCttsValid = false;
break;
}
ctts.readInt(); // Ignore offset.
remainingTimestampOffsetChanges--;
}
if (remainingSynchronizationSamples != 0
|| remainingSamplesAtTimestampDelta != 0
|| remainingSamplesInChunk != 0
|| remainingTimestampDeltaChanges != 0
|| remainingSamplesAtTimestampOffset != 0
|| !isCttsValid) {
Log.w(
TAG,
"Inconsistent stbl box for track "
+ track.id
+ ": remainingSynchronizationSamples "
+ remainingSynchronizationSamples
+ ", remainingSamplesAtTimestampDelta "
+ remainingSamplesAtTimestampDelta
+ ", remainingSamplesInChunk "
+ remainingSamplesInChunk
+ ", remainingTimestampDeltaChanges "
+ remainingTimestampDeltaChanges
+ ", remainingSamplesAtTimestampOffset "
+ remainingSamplesAtTimestampOffset
+ (!isCttsValid ? ", ctts invalid" : ""));
}
}
long durationUs = Util.scaleLargeTimestamp(duration, C.MICROS_PER_SECOND, track.timescale);
if (track.editListDurations == null) {
Util.scaleLargeTimestampsInPlace(timestamps, C.MICROS_PER_SECOND, track.timescale);
return new TrackSampleTable(
track, offsets, sizes, maximumSize, timestamps, flags, durationUs);
}
// See the BMFF spec (ISO/IEC 14496-12) subsection 8.6.6. Edit lists that require prerolling
// from a sync sample after reordering are not supported. Partial audio sample truncation is
// only supported in edit lists with one edit that removes less than
// MAX_GAPLESS_TRIM_SIZE_SAMPLES samples from the start/end of the track. This implementation
// handles simple discarding/delaying of samples. The extractor may place further restrictions
// on what edited streams are playable.
if (track.editListDurations.length == 1
&& track.type == C.TRACK_TYPE_AUDIO
&& timestamps.length >= 2) {
long editStartTime = track.editListMediaTimes[0];
long editEndTime = editStartTime + Util.scaleLargeTimestamp(track.editListDurations[0],
track.timescale, track.movieTimescale);
if (canApplyEditWithGaplessInfo(timestamps, duration, editStartTime, editEndTime)) {
long paddingTimeUnits = duration - editEndTime;
long encoderDelay = Util.scaleLargeTimestamp(editStartTime - timestamps[0],
track.format.sampleRate, track.timescale);
long encoderPadding = Util.scaleLargeTimestamp(paddingTimeUnits,
track.format.sampleRate, track.timescale);
if ((encoderDelay != 0 || encoderPadding != 0) && encoderDelay <= Integer.MAX_VALUE
&& encoderPadding <= Integer.MAX_VALUE) {
gaplessInfoHolder.encoderDelay = (int) encoderDelay;
gaplessInfoHolder.encoderPadding = (int) encoderPadding;
Util.scaleLargeTimestampsInPlace(timestamps, C.MICROS_PER_SECOND, track.timescale);
long editedDurationUs =
Util.scaleLargeTimestamp(
track.editListDurations[0], C.MICROS_PER_SECOND, track.movieTimescale);
return new TrackSampleTable(
track, offsets, sizes, maximumSize, timestamps, flags, editedDurationUs);
}
}
}
if (track.editListDurations.length == 1 && track.editListDurations[0] == 0) {
// The current version of the spec leaves handling of an edit with zero segment_duration in
// unfragmented files open to interpretation. We handle this as a special case and include all
// samples in the edit.
long editStartTime = track.editListMediaTimes[0];
for (int i = 0; i < timestamps.length; i++) {
timestamps[i] =
Util.scaleLargeTimestamp(
timestamps[i] - editStartTime, C.MICROS_PER_SECOND, track.timescale);
}
durationUs =
Util.scaleLargeTimestamp(duration - editStartTime, C.MICROS_PER_SECOND, track.timescale);
return new TrackSampleTable(
track, offsets, sizes, maximumSize, timestamps, flags, durationUs);
}
// Omit any sample at the end point of an edit for audio tracks.
boolean omitClippedSample = track.type == C.TRACK_TYPE_AUDIO;
// Count the number of samples after applying edits.
int editedSampleCount = 0;
int nextSampleIndex = 0;
boolean copyMetadata = false;
int[] startIndices = new int[track.editListDurations.length];
int[] endIndices = new int[track.editListDurations.length];
for (int i = 0; i < track.editListDurations.length; i++) {
long editMediaTime = track.editListMediaTimes[i];
if (editMediaTime != -1) {
long editDuration =
Util.scaleLargeTimestamp(
track.editListDurations[i], track.timescale, track.movieTimescale);
startIndices[i] =
Util.binarySearchFloor(
timestamps, editMediaTime, /* inclusive= */ true, /* stayInBounds= */ true);
endIndices[i] =
Util.binarySearchCeil(
timestamps,
editMediaTime + editDuration,
/* inclusive= */ omitClippedSample,
/* stayInBounds= */ false);
while (startIndices[i] < endIndices[i]
&& (flags[startIndices[i]] & C.BUFFER_FLAG_KEY_FRAME) == 0) {
// Applying the edit correctly would require prerolling from the previous sync sample. In
// the current implementation we advance to the next sync sample instead. Only other
// tracks (i.e. audio) will be rendered until the time of the first sync sample.
// See https://github.com/google/ExoPlayer/issues/1659.
startIndices[i]++;
}
editedSampleCount += endIndices[i] - startIndices[i];
copyMetadata |= nextSampleIndex != startIndices[i];
nextSampleIndex = endIndices[i];
}
}
copyMetadata |= editedSampleCount != sampleCount;
// Calculate edited sample timestamps and update the corresponding metadata arrays.
long[] editedOffsets = copyMetadata ? new long[editedSampleCount] : offsets;
int[] editedSizes = copyMetadata ? new int[editedSampleCount] : sizes;
int editedMaximumSize = copyMetadata ? 0 : maximumSize;
int[] editedFlags = copyMetadata ? new int[editedSampleCount] : flags;
long[] editedTimestamps = new long[editedSampleCount];
long pts = 0;
int sampleIndex = 0;
for (int i = 0; i < track.editListDurations.length; i++) {
long editMediaTime = track.editListMediaTimes[i];
int startIndex = startIndices[i];
int endIndex = endIndices[i];
if (copyMetadata) {
int count = endIndex - startIndex;
System.arraycopy(offsets, startIndex, editedOffsets, sampleIndex, count);
System.arraycopy(sizes, startIndex, editedSizes, sampleIndex, count);
System.arraycopy(flags, startIndex, editedFlags, sampleIndex, count);
}
for (int j = startIndex; j < endIndex; j++) {
long ptsUs = Util.scaleLargeTimestamp(pts, C.MICROS_PER_SECOND, track.movieTimescale);
long timeInSegmentUs =
Util.scaleLargeTimestamp(
Math.max(0, timestamps[j] - editMediaTime), C.MICROS_PER_SECOND, track.timescale);
editedTimestamps[sampleIndex] = ptsUs + timeInSegmentUs;
if (copyMetadata && editedSizes[sampleIndex] > editedMaximumSize) {
editedMaximumSize = sizes[j];
}
sampleIndex++;
}
pts += track.editListDurations[i];
}
long editedDurationUs =
Util.scaleLargeTimestamp(pts, C.MICROS_PER_SECOND, track.movieTimescale);
return new TrackSampleTable(
track,
editedOffsets,
editedSizes,
editedMaximumSize,
editedTimestamps,
editedFlags,
editedDurationUs);
}
@Nullable
private static Metadata parseUdtaMeta(ParsableByteArray meta, int limit) {
meta.skipBytes(Atom.FULL_HEADER_SIZE);
while (meta.getPosition() < limit) {
int atomPosition = meta.getPosition();
int atomSize = meta.readInt();
int atomType = meta.readInt();
if (atomType == Atom.TYPE_ilst) {
meta.setPosition(atomPosition);
return parseIlst(meta, atomPosition + atomSize);
}
meta.setPosition(atomPosition + atomSize);
}
return null;
}
@Nullable
private static Metadata parseIlst(ParsableByteArray ilst, int limit) {
ilst.skipBytes(Atom.HEADER_SIZE);
ArrayList<Metadata.Entry> entries = new ArrayList<>();
while (ilst.getPosition() < limit) {
@Nullable Metadata.Entry entry = MetadataUtil.parseIlstElement(ilst);
if (entry != null) {
entries.add(entry);
}
}
return entries.isEmpty() ? null : new Metadata(entries);
}
/**
* Parses a mvhd atom (defined in ISO/IEC 14496-12), returning the timescale for the movie.
*
* @param mvhd Contents of the mvhd atom to be parsed.
* @return Timescale for the movie.
*/
private static long parseMvhd(ParsableByteArray mvhd) {
mvhd.setPosition(Atom.HEADER_SIZE);
int fullAtom = mvhd.readInt();
int version = Atom.parseFullAtomVersion(fullAtom);
mvhd.skipBytes(version == 0 ? 8 : 16);
return mvhd.readUnsignedInt();
}
/**
* Parses a tkhd atom (defined in ISO/IEC 14496-12).
*
* @return An object containing the parsed data.
*/
private static TkhdData parseTkhd(ParsableByteArray tkhd) {
tkhd.setPosition(Atom.HEADER_SIZE);
int fullAtom = tkhd.readInt();
int version = Atom.parseFullAtomVersion(fullAtom);
tkhd.skipBytes(version == 0 ? 8 : 16);
int trackId = tkhd.readInt();
tkhd.skipBytes(4);
boolean durationUnknown = true;
int durationPosition = tkhd.getPosition();
int durationByteCount = version == 0 ? 4 : 8;
for (int i = 0; i < durationByteCount; i++) {
if (tkhd.data[durationPosition + i] != -1) {
durationUnknown = false;
break;
}
}
long duration;
if (durationUnknown) {
tkhd.skipBytes(durationByteCount);
duration = C.TIME_UNSET;
} else {
duration = version == 0 ? tkhd.readUnsignedInt() : tkhd.readUnsignedLongToLong();
if (duration == 0) {
// 0 duration normally indicates that the file is fully fragmented (i.e. all of the media
// samples are in fragments). Treat as unknown.
duration = C.TIME_UNSET;
}
}
tkhd.skipBytes(16);
int a00 = tkhd.readInt();
int a01 = tkhd.readInt();
tkhd.skipBytes(4);
int a10 = tkhd.readInt();
int a11 = tkhd.readInt();
int rotationDegrees;
int fixedOne = 65536;
if (a00 == 0 && a01 == fixedOne && a10 == -fixedOne && a11 == 0) {
rotationDegrees = 90;
} else if (a00 == 0 && a01 == -fixedOne && a10 == fixedOne && a11 == 0) {
rotationDegrees = 270;
} else if (a00 == -fixedOne && a01 == 0 && a10 == 0 && a11 == -fixedOne) {
rotationDegrees = 180;
} else {
// Only 0, 90, 180 and 270 are supported. Treat anything else as 0.
rotationDegrees = 0;
}
return new TkhdData(trackId, duration, rotationDegrees);
}
/**
* Parses an hdlr atom.
*
* @param hdlr The hdlr atom to decode.
* @return The handler value.
*/
private static int parseHdlr(ParsableByteArray hdlr) {
hdlr.setPosition(Atom.FULL_HEADER_SIZE + 4);
return hdlr.readInt();
}
/** Returns the track type for a given handler value. */
private static int getTrackTypeForHdlr(int hdlr) {
if (hdlr == TYPE_soun) {
return C.TRACK_TYPE_AUDIO;
} else if (hdlr == TYPE_vide) {
return C.TRACK_TYPE_VIDEO;
} else if (hdlr == TYPE_text || hdlr == TYPE_sbtl || hdlr == TYPE_subt || hdlr == TYPE_clcp) {
return C.TRACK_TYPE_TEXT;
} else if (hdlr == TYPE_meta) {
return C.TRACK_TYPE_METADATA;
} else {
return C.TRACK_TYPE_UNKNOWN;
}
}
/**
* Parses an mdhd atom (defined in ISO/IEC 14496-12).
*
* @param mdhd The mdhd atom to decode.
* @return A pair consisting of the media timescale defined as the number of time units that pass
* in one second, and the language code.
*/
private static Pair<Long, String> parseMdhd(ParsableByteArray mdhd) {
mdhd.setPosition(Atom.HEADER_SIZE);
int fullAtom = mdhd.readInt();
int version = Atom.parseFullAtomVersion(fullAtom);
mdhd.skipBytes(version == 0 ? 8 : 16);
long timescale = mdhd.readUnsignedInt();
mdhd.skipBytes(version == 0 ? 4 : 8);
int languageCode = mdhd.readUnsignedShort();
String language =
""
+ (char) (((languageCode >> 10) & 0x1F) + 0x60)
+ (char) (((languageCode >> 5) & 0x1F) + 0x60)
+ (char) ((languageCode & 0x1F) + 0x60);
return Pair.create(timescale, language);
}
/**
* Parses a stsd atom (defined in ISO/IEC 14496-12).
*
* @param stsd The stsd atom to decode.
* @param trackId The track's identifier in its container.
* @param rotationDegrees The rotation of the track in degrees.
* @param language The language of the track.
* @param drmInitData {@link DrmInitData} to be included in the format, or {@code null}.
* @param isQuickTime True for QuickTime media. False otherwise.
* @return An object containing the parsed data.
*/
private static StsdData parseStsd(
ParsableByteArray stsd,
int trackId,
int rotationDegrees,
String language,
@Nullable DrmInitData drmInitData,
boolean isQuickTime)
throws ParserException {
stsd.setPosition(Atom.FULL_HEADER_SIZE);
int numberOfEntries = stsd.readInt();
StsdData out = new StsdData(numberOfEntries);
for (int i = 0; i < numberOfEntries; i++) {
int childStartPosition = stsd.getPosition();
int childAtomSize = stsd.readInt();
Assertions.checkState(childAtomSize > 0, "childAtomSize should be positive");
int childAtomType = stsd.readInt();
if (childAtomType == Atom.TYPE_avc1
|| childAtomType == Atom.TYPE_avc3
|| childAtomType == Atom.TYPE_encv
|| childAtomType == Atom.TYPE_mp4v
|| childAtomType == Atom.TYPE_hvc1
|| childAtomType == Atom.TYPE_hev1
|| childAtomType == Atom.TYPE_s263
|| childAtomType == Atom.TYPE_vp08
|| childAtomType == Atom.TYPE_vp09
|| childAtomType == Atom.TYPE_av01
|| childAtomType == Atom.TYPE_dvav
|| childAtomType == Atom.TYPE_dva1
|| childAtomType == Atom.TYPE_dvhe
|| childAtomType == Atom.TYPE_dvh1) {
parseVideoSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId,
rotationDegrees, drmInitData, out, i);
} else if (childAtomType == Atom.TYPE_mp4a
|| childAtomType == Atom.TYPE_enca
|| childAtomType == Atom.TYPE_ac_3
|| childAtomType == Atom.TYPE_ec_3
|| childAtomType == Atom.TYPE_ac_4
|| childAtomType == Atom.TYPE_dtsc
|| childAtomType == Atom.TYPE_dtse
|| childAtomType == Atom.TYPE_dtsh
|| childAtomType == Atom.TYPE_dtsl
|| childAtomType == Atom.TYPE_samr
|| childAtomType == Atom.TYPE_sawb
|| childAtomType == Atom.TYPE_lpcm
|| childAtomType == Atom.TYPE_sowt
|| childAtomType == Atom.TYPE_twos
|| childAtomType == Atom.TYPE__mp3
|| childAtomType == Atom.TYPE_alac
|| childAtomType == Atom.TYPE_alaw
|| childAtomType == Atom.TYPE_ulaw
|| childAtomType == Atom.TYPE_Opus
|| childAtomType == Atom.TYPE_fLaC) {
parseAudioSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId,
language, isQuickTime, drmInitData, out, i);
} else if (childAtomType == Atom.TYPE_TTML || childAtomType == Atom.TYPE_tx3g
|| childAtomType == Atom.TYPE_wvtt || childAtomType == Atom.TYPE_stpp
|| childAtomType == Atom.TYPE_c608) {
parseTextSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId,
language, out);
} else if (childAtomType == Atom.TYPE_camm) {
out.format =
new Format.Builder()
.setId(trackId)
.setSampleMimeType(MimeTypes.APPLICATION_CAMERA_MOTION)
.build();
}
stsd.setPosition(childStartPosition + childAtomSize);
}
return out;
}
private static void parseTextSampleEntry(
ParsableByteArray parent,
int atomType,
int position,
int atomSize,
int trackId,
String language,
StsdData out) {
parent.setPosition(position + Atom.HEADER_SIZE + StsdData.STSD_HEADER_SIZE);
// Default values.
@Nullable List<byte[]> initializationData = null;
long subsampleOffsetUs = Format.OFFSET_SAMPLE_RELATIVE;
String mimeType;
if (atomType == Atom.TYPE_TTML) {
mimeType = MimeTypes.APPLICATION_TTML;
} else if (atomType == Atom.TYPE_tx3g) {
mimeType = MimeTypes.APPLICATION_TX3G;
int sampleDescriptionLength = atomSize - Atom.HEADER_SIZE - 8;
byte[] sampleDescriptionData = new byte[sampleDescriptionLength];
parent.readBytes(sampleDescriptionData, 0, sampleDescriptionLength);
initializationData = Collections.singletonList(sampleDescriptionData);
} else if (atomType == Atom.TYPE_wvtt) {
mimeType = MimeTypes.APPLICATION_MP4VTT;
} else if (atomType == Atom.TYPE_stpp) {
mimeType = MimeTypes.APPLICATION_TTML;
subsampleOffsetUs = 0; // Subsample timing is absolute.
} else if (atomType == Atom.TYPE_c608) {
// Defined by the QuickTime File Format specification.
mimeType = MimeTypes.APPLICATION_MP4CEA608;
out.requiredSampleTransformation = Track.TRANSFORMATION_CEA608_CDAT;
} else {
// Never happens.
throw new IllegalStateException();
}
out.format =
new Format.Builder()
.setId(trackId)
.setSampleMimeType(mimeType)
.setLanguage(language)
.setSubsampleOffsetUs(subsampleOffsetUs)
.setInitializationData(initializationData)
.build();
}
private static void parseVideoSampleEntry(
ParsableByteArray parent,
int atomType,
int position,
int size,
int trackId,
int rotationDegrees,
@Nullable DrmInitData drmInitData,
StsdData out,
int entryIndex)
throws ParserException {
parent.setPosition(position + Atom.HEADER_SIZE + StsdData.STSD_HEADER_SIZE);
parent.skipBytes(16);
int width = parent.readUnsignedShort();
int height = parent.readUnsignedShort();
boolean pixelWidthHeightRatioFromPasp = false;
float pixelWidthHeightRatio = 1;
parent.skipBytes(50);
int childPosition = parent.getPosition();
if (atomType == Atom.TYPE_encv) {
@Nullable
Pair<Integer, TrackEncryptionBox> sampleEntryEncryptionData =
parseSampleEntryEncryptionData(parent, position, size);
if (sampleEntryEncryptionData != null) {
atomType = sampleEntryEncryptionData.first;
drmInitData = drmInitData == null ? null
: drmInitData.copyWithSchemeType(sampleEntryEncryptionData.second.schemeType);
out.trackEncryptionBoxes[entryIndex] = sampleEntryEncryptionData.second;
}
parent.setPosition(childPosition);
}
// TODO: Uncomment when [Internal: b/63092960] is fixed.
// else {
// drmInitData = null;
// }
@Nullable List<byte[]> initializationData = null;
@Nullable String mimeType = null;
@Nullable String codecs = null;
@Nullable byte[] projectionData = null;
@C.StereoMode
int stereoMode = Format.NO_VALUE;
while (childPosition - position < size) {
parent.setPosition(childPosition);
int childStartPosition = parent.getPosition();
int childAtomSize = parent.readInt();
if (childAtomSize == 0 && parent.getPosition() - position == size) {
// Handle optional terminating four zero bytes in MOV files.
break;
}
Assertions.checkState(childAtomSize > 0, "childAtomSize should be positive");
int childAtomType = parent.readInt();
if (childAtomType == Atom.TYPE_avcC) {
Assertions.checkState(mimeType == null);
mimeType = MimeTypes.VIDEO_H264;
parent.setPosition(childStartPosition + Atom.HEADER_SIZE);
AvcConfig avcConfig = AvcConfig.parse(parent);
initializationData = avcConfig.initializationData;
out.nalUnitLengthFieldLength = avcConfig.nalUnitLengthFieldLength;
if (!pixelWidthHeightRatioFromPasp) {
pixelWidthHeightRatio = avcConfig.pixelWidthAspectRatio;
}
} else if (childAtomType == Atom.TYPE_hvcC) {
Assertions.checkState(mimeType == null);
mimeType = MimeTypes.VIDEO_H265;
parent.setPosition(childStartPosition + Atom.HEADER_SIZE);
HevcConfig hevcConfig = HevcConfig.parse(parent);
initializationData = hevcConfig.initializationData;
out.nalUnitLengthFieldLength = hevcConfig.nalUnitLengthFieldLength;
} else if (childAtomType == Atom.TYPE_dvcC || childAtomType == Atom.TYPE_dvvC) {
@Nullable DolbyVisionConfig dolbyVisionConfig = DolbyVisionConfig.parse(parent);
if (dolbyVisionConfig != null) {
codecs = dolbyVisionConfig.codecs;
mimeType = MimeTypes.VIDEO_DOLBY_VISION;
}
} else if (childAtomType == Atom.TYPE_vpcC) {
Assertions.checkState(mimeType == null);
mimeType = (atomType == Atom.TYPE_vp08) ? MimeTypes.VIDEO_VP8 : MimeTypes.VIDEO_VP9;
} else if (childAtomType == Atom.TYPE_av1C) {
Assertions.checkState(mimeType == null);
mimeType = MimeTypes.VIDEO_AV1;
} else if (childAtomType == Atom.TYPE_d263) {
Assertions.checkState(mimeType == null);
mimeType = MimeTypes.VIDEO_H263;
} else if (childAtomType == Atom.TYPE_esds) {
Assertions.checkState(mimeType == null);
Pair<@NullableType String, byte @NullableType []> mimeTypeAndInitializationDataBytes =
parseEsdsFromParent(parent, childStartPosition);
mimeType = mimeTypeAndInitializationDataBytes.first;
@Nullable byte[] initializationDataBytes = mimeTypeAndInitializationDataBytes.second;
if (initializationDataBytes != null) {
initializationData = Collections.singletonList(initializationDataBytes);
}
} else if (childAtomType == Atom.TYPE_pasp) {
pixelWidthHeightRatio = parsePaspFromParent(parent, childStartPosition);
pixelWidthHeightRatioFromPasp = true;
} else if (childAtomType == Atom.TYPE_sv3d) {
projectionData = parseProjFromParent(parent, childStartPosition, childAtomSize);
} else if (childAtomType == Atom.TYPE_st3d) {
int version = parent.readUnsignedByte();
parent.skipBytes(3); // Flags.
if (version == 0) {
int layout = parent.readUnsignedByte();
switch (layout) {
case 0:
stereoMode = C.STEREO_MODE_MONO;
break;
case 1:
stereoMode = C.STEREO_MODE_TOP_BOTTOM;
break;
case 2:
stereoMode = C.STEREO_MODE_LEFT_RIGHT;
break;
case 3:
stereoMode = C.STEREO_MODE_STEREO_MESH;
break;
default:
break;
}
}
}
childPosition += childAtomSize;
}
// If the media type was not recognized, ignore the track.
if (mimeType == null) {
return;
}
out.format =
new Format.Builder()
.setId(trackId)
.setSampleMimeType(mimeType)
.setCodecs(codecs)
.setWidth(width)
.setHeight(height)
.setPixelWidthHeightRatio(pixelWidthHeightRatio)
.setRotationDegrees(rotationDegrees)
.setProjectionData(projectionData)
.setStereoMode(stereoMode)
.setInitializationData(initializationData)
.setDrmInitData(drmInitData)
.build();
}
/**
* Parses the edts atom (defined in ISO/IEC 14496-12 subsection 8.6.5).
*
* @param edtsAtom edts (edit box) atom to decode.
* @return Pair of edit list durations and edit list media times, or {@code null} if they are not
* present.
*/
@Nullable
private static Pair<long[], long[]> parseEdts(Atom.ContainerAtom edtsAtom) {
@Nullable Atom.LeafAtom elstAtom = edtsAtom.getLeafAtomOfType(Atom.TYPE_elst);
if (elstAtom == null) {
return null;
}
ParsableByteArray elstData = elstAtom.data;
elstData.setPosition(Atom.HEADER_SIZE);
int fullAtom = elstData.readInt();
int version = Atom.parseFullAtomVersion(fullAtom);
int entryCount = elstData.readUnsignedIntToInt();
long[] editListDurations = new long[entryCount];
long[] editListMediaTimes = new long[entryCount];
for (int i = 0; i < entryCount; i++) {
editListDurations[i] =
version == 1 ? elstData.readUnsignedLongToLong() : elstData.readUnsignedInt();
editListMediaTimes[i] = version == 1 ? elstData.readLong() : elstData.readInt();
int mediaRateInteger = elstData.readShort();
if (mediaRateInteger != 1) {
// The extractor does not handle dwell edits (mediaRateInteger == 0).
throw new IllegalArgumentException("Unsupported media rate.");
}
elstData.skipBytes(2);
}
return Pair.create(editListDurations, editListMediaTimes);
}
private static float parsePaspFromParent(ParsableByteArray parent, int position) {
parent.setPosition(position + Atom.HEADER_SIZE);
int hSpacing = parent.readUnsignedIntToInt();
int vSpacing = parent.readUnsignedIntToInt();
return (float) hSpacing / vSpacing;
}
private static void parseAudioSampleEntry(
ParsableByteArray parent,
int atomType,
int position,
int size,
int trackId,
String language,
boolean isQuickTime,
@Nullable DrmInitData drmInitData,
StsdData out,
int entryIndex)
throws ParserException {
parent.setPosition(position + Atom.HEADER_SIZE + StsdData.STSD_HEADER_SIZE);
int quickTimeSoundDescriptionVersion = 0;
if (isQuickTime) {
quickTimeSoundDescriptionVersion = parent.readUnsignedShort();
parent.skipBytes(6);
} else {
parent.skipBytes(8);
}
int channelCount;
int sampleRate;
@C.PcmEncoding int pcmEncoding = Format.NO_VALUE;
@Nullable String codecs = null;
if (quickTimeSoundDescriptionVersion == 0 || quickTimeSoundDescriptionVersion == 1) {
channelCount = parent.readUnsignedShort();
parent.skipBytes(6); // sampleSize, compressionId, packetSize.
sampleRate = parent.readUnsignedFixedPoint1616();
if (quickTimeSoundDescriptionVersion == 1) {
parent.skipBytes(16);
}
} else if (quickTimeSoundDescriptionVersion == 2) {
parent.skipBytes(16); // always[3,16,Minus2,0,65536], sizeOfStructOnly
sampleRate = (int) Math.round(parent.readDouble());
channelCount = parent.readUnsignedIntToInt();
// Skip always7F000000, sampleSize, formatSpecificFlags, constBytesPerAudioPacket,
// constLPCMFramesPerAudioPacket.
parent.skipBytes(20);
} else {
// Unsupported version.
return;
}
int childPosition = parent.getPosition();
if (atomType == Atom.TYPE_enca) {
@Nullable
Pair<Integer, TrackEncryptionBox> sampleEntryEncryptionData =
parseSampleEntryEncryptionData(parent, position, size);
if (sampleEntryEncryptionData != null) {
atomType = sampleEntryEncryptionData.first;
drmInitData = drmInitData == null ? null
: drmInitData.copyWithSchemeType(sampleEntryEncryptionData.second.schemeType);
out.trackEncryptionBoxes[entryIndex] = sampleEntryEncryptionData.second;
}
parent.setPosition(childPosition);
}
// TODO: Uncomment when [Internal: b/63092960] is fixed.
// else {
// drmInitData = null;
// }
// If the atom type determines a MIME type, set it immediately.
@Nullable String mimeType = null;
if (atomType == Atom.TYPE_ac_3) {
mimeType = MimeTypes.AUDIO_AC3;
} else if (atomType == Atom.TYPE_ec_3) {
mimeType = MimeTypes.AUDIO_E_AC3;
} else if (atomType == Atom.TYPE_ac_4) {
mimeType = MimeTypes.AUDIO_AC4;
} else if (atomType == Atom.TYPE_dtsc) {
mimeType = MimeTypes.AUDIO_DTS;
} else if (atomType == Atom.TYPE_dtsh || atomType == Atom.TYPE_dtsl) {
mimeType = MimeTypes.AUDIO_DTS_HD;
} else if (atomType == Atom.TYPE_dtse) {
mimeType = MimeTypes.AUDIO_DTS_EXPRESS;
} else if (atomType == Atom.TYPE_samr) {
mimeType = MimeTypes.AUDIO_AMR_NB;
} else if (atomType == Atom.TYPE_sawb) {
mimeType = MimeTypes.AUDIO_AMR_WB;
} else if (atomType == Atom.TYPE_lpcm || atomType == Atom.TYPE_sowt) {
mimeType = MimeTypes.AUDIO_RAW;
pcmEncoding = C.ENCODING_PCM_16BIT;
} else if (atomType == Atom.TYPE_twos) {
mimeType = MimeTypes.AUDIO_RAW;
pcmEncoding = C.ENCODING_PCM_16BIT_BIG_ENDIAN;
} else if (atomType == Atom.TYPE__mp3) {
mimeType = MimeTypes.AUDIO_MPEG;
} else if (atomType == Atom.TYPE_alac) {
mimeType = MimeTypes.AUDIO_ALAC;
} else if (atomType == Atom.TYPE_alaw) {
mimeType = MimeTypes.AUDIO_ALAW;
} else if (atomType == Atom.TYPE_ulaw) {
mimeType = MimeTypes.AUDIO_MLAW;
} else if (atomType == Atom.TYPE_Opus) {
mimeType = MimeTypes.AUDIO_OPUS;
} else if (atomType == Atom.TYPE_fLaC) {
mimeType = MimeTypes.AUDIO_FLAC;
}
@Nullable byte[] initializationData = null;
while (childPosition - position < size) {
parent.setPosition(childPosition);
int childAtomSize = parent.readInt();
Assertions.checkState(childAtomSize > 0, "childAtomSize should be positive");
int childAtomType = parent.readInt();
if (childAtomType == Atom.TYPE_esds || (isQuickTime && childAtomType == Atom.TYPE_wave)) {
int esdsAtomPosition = childAtomType == Atom.TYPE_esds ? childPosition
: findEsdsPosition(parent, childPosition, childAtomSize);
if (esdsAtomPosition != C.POSITION_UNSET) {
Pair<@NullableType String, byte @NullableType []> mimeTypeAndInitializationData =
parseEsdsFromParent(parent, esdsAtomPosition);
mimeType = mimeTypeAndInitializationData.first;
initializationData = mimeTypeAndInitializationData.second;
if (MimeTypes.AUDIO_AAC.equals(mimeType) && initializationData != null) {
// Update sampleRate and channelCount from the AudioSpecificConfig initialization data,
// which is more reliable. See [Internal: b/10903778].
AacUtil.Config aacConfig = AacUtil.parseAudioSpecificConfig(initializationData);
sampleRate = aacConfig.sampleRateHz;
channelCount = aacConfig.channelCount;
codecs = aacConfig.codecs;
}
}
} else if (childAtomType == Atom.TYPE_dac3) {
parent.setPosition(Atom.HEADER_SIZE + childPosition);
out.format = Ac3Util.parseAc3AnnexFFormat(parent, Integer.toString(trackId), language,
drmInitData);
} else if (childAtomType == Atom.TYPE_dec3) {
parent.setPosition(Atom.HEADER_SIZE + childPosition);
out.format = Ac3Util.parseEAc3AnnexFFormat(parent, Integer.toString(trackId), language,
drmInitData);
} else if (childAtomType == Atom.TYPE_dac4) {
parent.setPosition(Atom.HEADER_SIZE + childPosition);
out.format =
Ac4Util.parseAc4AnnexEFormat(parent, Integer.toString(trackId), language, drmInitData);
} else if (childAtomType == Atom.TYPE_ddts) {
out.format =
new Format.Builder()
.setId(trackId)
.setSampleMimeType(mimeType)
.setChannelCount(channelCount)
.setSampleRate(sampleRate)
.setDrmInitData(drmInitData)
.setLanguage(language)
.build();
} else if (childAtomType == Atom.TYPE_dOps) {
// Build an Opus Identification Header (defined in RFC-7845) by concatenating the Opus Magic
// Signature and the body of the dOps atom.
int childAtomBodySize = childAtomSize - Atom.HEADER_SIZE;
initializationData = new byte[opusMagic.length + childAtomBodySize];
System.arraycopy(opusMagic, 0, initializationData, 0, opusMagic.length);
parent.setPosition(childPosition + Atom.HEADER_SIZE);
parent.readBytes(initializationData, opusMagic.length, childAtomBodySize);
} else if (childAtomType == Atom.TYPE_dfLa) {
int childAtomBodySize = childAtomSize - Atom.FULL_HEADER_SIZE;
initializationData = new byte[4 + childAtomBodySize];
initializationData[0] = 0x66; // f
initializationData[1] = 0x4C; // L
initializationData[2] = 0x61; // a
initializationData[3] = 0x43; // C
parent.setPosition(childPosition + Atom.FULL_HEADER_SIZE);
parent.readBytes(initializationData, /* offset= */ 4, childAtomBodySize);
} else if (childAtomType == Atom.TYPE_alac) {
int childAtomBodySize = childAtomSize - Atom.FULL_HEADER_SIZE;
initializationData = new byte[childAtomBodySize];
parent.setPosition(childPosition + Atom.FULL_HEADER_SIZE);
parent.readBytes(initializationData, /* offset= */ 0, childAtomBodySize);
// Update sampleRate and channelCount from the AudioSpecificConfig initialization data,
// which is more reliable. See https://github.com/google/ExoPlayer/pull/6629.
Pair<Integer, Integer> audioSpecificConfig =
CodecSpecificDataUtil.parseAlacAudioSpecificConfig(initializationData);
sampleRate = audioSpecificConfig.first;
channelCount = audioSpecificConfig.second;
}
childPosition += childAtomSize;
}
if (out.format == null && mimeType != null) {
out.format =
new Format.Builder()
.setId(trackId)
.setSampleMimeType(mimeType)
.setCodecs(codecs)
.setChannelCount(channelCount)
.setSampleRate(sampleRate)
.setEncoding(pcmEncoding)
.setInitializationData(
initializationData == null ? null : Collections.singletonList(initializationData))
.setDrmInitData(drmInitData)
.setLanguage(language)
.build();
}
}
/**
* Returns the position of the esds box within a parent, or {@link C#POSITION_UNSET} if no esds
* box is found
*/
private static int findEsdsPosition(ParsableByteArray parent, int position, int size) {
int childAtomPosition = parent.getPosition();
while (childAtomPosition - position < size) {
parent.setPosition(childAtomPosition);
int childAtomSize = parent.readInt();
Assertions.checkState(childAtomSize > 0, "childAtomSize should be positive");
int childType = parent.readInt();
if (childType == Atom.TYPE_esds) {
return childAtomPosition;
}
childAtomPosition += childAtomSize;
}
return C.POSITION_UNSET;
}
/** Returns codec-specific initialization data contained in an esds box. */
private static Pair<@NullableType String, byte @NullableType []> parseEsdsFromParent(
ParsableByteArray parent, int position) {
parent.setPosition(position + Atom.HEADER_SIZE + 4);
// Start of the ES_Descriptor (defined in ISO/IEC 14496-1)
parent.skipBytes(1); // ES_Descriptor tag
parseExpandableClassSize(parent);
parent.skipBytes(2); // ES_ID
int flags = parent.readUnsignedByte();
if ((flags & 0x80 /* streamDependenceFlag */) != 0) {
parent.skipBytes(2);
}
if ((flags & 0x40 /* URL_Flag */) != 0) {
parent.skipBytes(parent.readUnsignedShort());
}
if ((flags & 0x20 /* OCRstreamFlag */) != 0) {
parent.skipBytes(2);
}
// Start of the DecoderConfigDescriptor (defined in ISO/IEC 14496-1)
parent.skipBytes(1); // DecoderConfigDescriptor tag
parseExpandableClassSize(parent);
// Set the MIME type based on the object type indication (ISO/IEC 14496-1 table 5).
int objectTypeIndication = parent.readUnsignedByte();
String mimeType = getMimeTypeFromMp4ObjectType(objectTypeIndication);
if (MimeTypes.AUDIO_MPEG.equals(mimeType)
|| MimeTypes.AUDIO_DTS.equals(mimeType)
|| MimeTypes.AUDIO_DTS_HD.equals(mimeType)) {
return Pair.create(mimeType, null);
}
parent.skipBytes(12);
// Start of the DecoderSpecificInfo.
parent.skipBytes(1); // DecoderSpecificInfo tag
int initializationDataSize = parseExpandableClassSize(parent);
byte[] initializationData = new byte[initializationDataSize];
parent.readBytes(initializationData, 0, initializationDataSize);
return Pair.create(mimeType, initializationData);
}
/**
* Parses encryption data from an audio/video sample entry, returning a pair consisting of the
* unencrypted atom type and a {@link TrackEncryptionBox}. Null is returned if no common
* encryption sinf atom was present.
*/
@Nullable
private static Pair<Integer, TrackEncryptionBox> parseSampleEntryEncryptionData(
ParsableByteArray parent, int position, int size) {
int childPosition = parent.getPosition();
while (childPosition - position < size) {
parent.setPosition(childPosition);
int childAtomSize = parent.readInt();
Assertions.checkState(childAtomSize > 0, "childAtomSize should be positive");
int childAtomType = parent.readInt();
if (childAtomType == Atom.TYPE_sinf) {
Pair<Integer, TrackEncryptionBox> result = parseCommonEncryptionSinfFromParent(parent,
childPosition, childAtomSize);
if (result != null) {
return result;
}
}
childPosition += childAtomSize;
}
return null;
}
@Nullable
/* package */ static Pair<Integer, TrackEncryptionBox> parseCommonEncryptionSinfFromParent(
ParsableByteArray parent, int position, int size) {
int childPosition = position + Atom.HEADER_SIZE;
int schemeInformationBoxPosition = C.POSITION_UNSET;
int schemeInformationBoxSize = 0;
@Nullable String schemeType = null;
@Nullable Integer dataFormat = null;
while (childPosition - position < size) {
parent.setPosition(childPosition);
int childAtomSize = parent.readInt();
int childAtomType = parent.readInt();
if (childAtomType == Atom.TYPE_frma) {
dataFormat = parent.readInt();
} else if (childAtomType == Atom.TYPE_schm) {
parent.skipBytes(4);
// Common encryption scheme_type values are defined in ISO/IEC 23001-7:2016, section 4.1.
schemeType = parent.readString(4);
} else if (childAtomType == Atom.TYPE_schi) {
schemeInformationBoxPosition = childPosition;
schemeInformationBoxSize = childAtomSize;
}
childPosition += childAtomSize;
}
if (C.CENC_TYPE_cenc.equals(schemeType) || C.CENC_TYPE_cbc1.equals(schemeType)
|| C.CENC_TYPE_cens.equals(schemeType) || C.CENC_TYPE_cbcs.equals(schemeType)) {
Assertions.checkStateNotNull(dataFormat, "frma atom is mandatory");
Assertions.checkState(
schemeInformationBoxPosition != C.POSITION_UNSET, "schi atom is mandatory");
TrackEncryptionBox encryptionBox =
Assertions.checkStateNotNull(
parseSchiFromParent(
parent, schemeInformationBoxPosition, schemeInformationBoxSize, schemeType),
"tenc atom is mandatory");
return Pair.create(dataFormat, encryptionBox);
} else {
return null;
}
}
@Nullable
private static TrackEncryptionBox parseSchiFromParent(
ParsableByteArray parent, int position, int size, String schemeType) {
int childPosition = position + Atom.HEADER_SIZE;
while (childPosition - position < size) {
parent.setPosition(childPosition);
int childAtomSize = parent.readInt();
int childAtomType = parent.readInt();
if (childAtomType == Atom.TYPE_tenc) {
int fullAtom = parent.readInt();
int version = Atom.parseFullAtomVersion(fullAtom);
parent.skipBytes(1); // reserved = 0.
int defaultCryptByteBlock = 0;
int defaultSkipByteBlock = 0;
if (version == 0) {
parent.skipBytes(1); // reserved = 0.
} else /* version 1 or greater */ {
int patternByte = parent.readUnsignedByte();
defaultCryptByteBlock = (patternByte & 0xF0) >> 4;
defaultSkipByteBlock = patternByte & 0x0F;
}
boolean defaultIsProtected = parent.readUnsignedByte() == 1;
int defaultPerSampleIvSize = parent.readUnsignedByte();
byte[] defaultKeyId = new byte[16];
parent.readBytes(defaultKeyId, 0, defaultKeyId.length);
byte[] constantIv = null;
if (defaultIsProtected && defaultPerSampleIvSize == 0) {
int constantIvSize = parent.readUnsignedByte();
constantIv = new byte[constantIvSize];
parent.readBytes(constantIv, 0, constantIvSize);
}
return new TrackEncryptionBox(defaultIsProtected, schemeType, defaultPerSampleIvSize,
defaultKeyId, defaultCryptByteBlock, defaultSkipByteBlock, constantIv);
}
childPosition += childAtomSize;
}
return null;
}
/** Parses the proj box from sv3d box, as specified by https://github.com/google/spatial-media. */
@Nullable
private static byte[] parseProjFromParent(ParsableByteArray parent, int position, int size) {
int childPosition = position + Atom.HEADER_SIZE;
while (childPosition - position < size) {
parent.setPosition(childPosition);
int childAtomSize = parent.readInt();
int childAtomType = parent.readInt();
if (childAtomType == Atom.TYPE_proj) {
return Arrays.copyOfRange(parent.data, childPosition, childPosition + childAtomSize);
}
childPosition += childAtomSize;
}
return null;
}
/** Parses the size of an expandable class, as specified by ISO/IEC 14496-1 subsection 8.3.3. */
private static int parseExpandableClassSize(ParsableByteArray data) {
int currentByte = data.readUnsignedByte();
int size = currentByte & 0x7F;
while ((currentByte & 0x80) == 0x80) {
currentByte = data.readUnsignedByte();
size = (size << 7) | (currentByte & 0x7F);
}
return size;
}
/** Returns whether it's possible to apply the specified edit using gapless playback info. */
private static boolean canApplyEditWithGaplessInfo(
long[] timestamps, long duration, long editStartTime, long editEndTime) {
int lastIndex = timestamps.length - 1;
int latestDelayIndex = Util.constrainValue(MAX_GAPLESS_TRIM_SIZE_SAMPLES, 0, lastIndex);
int earliestPaddingIndex =
Util.constrainValue(timestamps.length - MAX_GAPLESS_TRIM_SIZE_SAMPLES, 0, lastIndex);
return timestamps[0] <= editStartTime
&& editStartTime < timestamps[latestDelayIndex]
&& timestamps[earliestPaddingIndex] < editEndTime
&& editEndTime <= duration;
}
private AtomParsers() {
// Prevent instantiation.
}
private static final class ChunkIterator {
public final int length;
public int index;
public int numSamples;
public long offset;
private final boolean chunkOffsetsAreLongs;
private final ParsableByteArray chunkOffsets;
private final ParsableByteArray stsc;
private int nextSamplesPerChunkChangeIndex;
private int remainingSamplesPerChunkChanges;
public ChunkIterator(ParsableByteArray stsc, ParsableByteArray chunkOffsets,
boolean chunkOffsetsAreLongs) {
this.stsc = stsc;
this.chunkOffsets = chunkOffsets;
this.chunkOffsetsAreLongs = chunkOffsetsAreLongs;
chunkOffsets.setPosition(Atom.FULL_HEADER_SIZE);
length = chunkOffsets.readUnsignedIntToInt();
stsc.setPosition(Atom.FULL_HEADER_SIZE);
remainingSamplesPerChunkChanges = stsc.readUnsignedIntToInt();
Assertions.checkState(stsc.readInt() == 1, "first_chunk must be 1");
index = -1;
}
public boolean moveNext() {
if (++index == length) {
return false;
}
offset = chunkOffsetsAreLongs ? chunkOffsets.readUnsignedLongToLong()
: chunkOffsets.readUnsignedInt();
if (index == nextSamplesPerChunkChangeIndex) {
numSamples = stsc.readUnsignedIntToInt();
stsc.skipBytes(4); // Skip sample_description_index
nextSamplesPerChunkChangeIndex = --remainingSamplesPerChunkChanges > 0
? (stsc.readUnsignedIntToInt() - 1) : C.INDEX_UNSET;
}
return true;
}
}
/**
* Holds data parsed from a tkhd atom.
*/
private static final class TkhdData {
private final int id;
private final long duration;
private final int rotationDegrees;
public TkhdData(int id, long duration, int rotationDegrees) {
this.id = id;
this.duration = duration;
this.rotationDegrees = rotationDegrees;
}
}
/**
* Holds data parsed from an stsd atom and its children.
*/
private static final class StsdData {
public static final int STSD_HEADER_SIZE = 8;
public final TrackEncryptionBox[] trackEncryptionBoxes;
@Nullable public Format format;
public int nalUnitLengthFieldLength;
@Track.Transformation public int requiredSampleTransformation;
public StsdData(int numberOfEntries) {
trackEncryptionBoxes = new TrackEncryptionBox[numberOfEntries];
requiredSampleTransformation = Track.TRANSFORMATION_NONE;
}
}
/**
* A box containing sample sizes (e.g. stsz, stz2).
*/
private interface SampleSizeBox {
/**
* Returns the number of samples.
*/
int getSampleCount();
/**
* Returns the size for the next sample.
*/
int readNextSampleSize();
/**
* Returns whether samples have a fixed size.
*/
boolean isFixedSampleSize();
}
/**
* An stsz sample size box.
*/
/* package */ static final class StszSampleSizeBox implements SampleSizeBox {
private final int fixedSampleSize;
private final int sampleCount;
private final ParsableByteArray data;
public StszSampleSizeBox(Atom.LeafAtom stszAtom) {
data = stszAtom.data;
data.setPosition(Atom.FULL_HEADER_SIZE);
fixedSampleSize = data.readUnsignedIntToInt();
sampleCount = data.readUnsignedIntToInt();
}
@Override
public int getSampleCount() {
return sampleCount;
}
@Override
public int readNextSampleSize() {
return fixedSampleSize == 0 ? data.readUnsignedIntToInt() : fixedSampleSize;
}
@Override
public boolean isFixedSampleSize() {
return fixedSampleSize != 0;
}
}
/**
* An stz2 sample size box.
*/
/* package */ static final class Stz2SampleSizeBox implements SampleSizeBox {
private final ParsableByteArray data;
private final int sampleCount;
private final int fieldSize; // Can be 4, 8, or 16.
// Used only if fieldSize == 4.
private int sampleIndex;
private int currentByte;
public Stz2SampleSizeBox(Atom.LeafAtom stz2Atom) {
data = stz2Atom.data;
data.setPosition(Atom.FULL_HEADER_SIZE);
fieldSize = data.readUnsignedIntToInt() & 0x000000FF;
sampleCount = data.readUnsignedIntToInt();
}
@Override
public int getSampleCount() {
return sampleCount;
}
@Override
public int readNextSampleSize() {
if (fieldSize == 8) {
return data.readUnsignedByte();
} else if (fieldSize == 16) {
return data.readUnsignedShort();
} else {
// fieldSize == 4.
if ((sampleIndex++ % 2) == 0) {
// Read the next byte into our cached byte when we are reading the upper bits.
currentByte = data.readUnsignedByte();
// Read the upper bits from the byte and shift them to the lower 4 bits.
return (currentByte & 0xF0) >> 4;
} else {
// Mask out the upper 4 bits of the last byte we read.
return currentByte & 0x0F;
}
}
}
@Override
public boolean isFixedSampleSize() {
return false;
}
}
}
| Remove AtomParsers from extractors nullness exclusion list
PiperOrigin-RevId: 322131697
| library/extractor/src/main/java/com/google/android/exoplayer2/extractor/mp4/AtomParsers.java | Remove AtomParsers from extractors nullness exclusion list |
|
Java | apache-2.0 | 11b66c3887d1bd64bec8bda8d49432edf33511b0 | 0 | mike-tr-adamson/incubator-tinkerpop,krlohnes/tinkerpop,BrynCooke/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,robertdale/tinkerpop,artem-aliev/tinkerpop,jorgebay/tinkerpop,apache/tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,apache/incubator-tinkerpop,apache/incubator-tinkerpop,pluradj/incubator-tinkerpop,krlohnes/tinkerpop,newkek/incubator-tinkerpop,robertdale/tinkerpop,newkek/incubator-tinkerpop,artem-aliev/tinkerpop,samiunn/incubator-tinkerpop,robertdale/tinkerpop,jorgebay/tinkerpop,artem-aliev/tinkerpop,apache/incubator-tinkerpop,samiunn/incubator-tinkerpop,apache/tinkerpop,artem-aliev/tinkerpop,mike-tr-adamson/incubator-tinkerpop,artem-aliev/tinkerpop,apache/tinkerpop,pluradj/incubator-tinkerpop,robertdale/tinkerpop,pluradj/incubator-tinkerpop,krlohnes/tinkerpop,jorgebay/tinkerpop,robertdale/tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,apache/tinkerpop,samiunn/incubator-tinkerpop,apache/tinkerpop,jorgebay/tinkerpop,BrynCooke/incubator-tinkerpop,newkek/incubator-tinkerpop | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop.gremlin.remote;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.AbstractGraphProvider;
import org.apache.tinkerpop.gremlin.LoadGraphWith;
import org.apache.tinkerpop.gremlin.driver.Client;
import org.apache.tinkerpop.gremlin.driver.Cluster;
import org.apache.tinkerpop.gremlin.driver.remote.DriverRemoteConnection;
import org.apache.tinkerpop.gremlin.process.remote.RemoteGraph;
import org.apache.tinkerpop.gremlin.server.GremlinServer;
import org.apache.tinkerpop.gremlin.server.ServerTestHelper;
import org.apache.tinkerpop.gremlin.server.Settings;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class RemoteGraphProvider extends AbstractGraphProvider {
private static final Set<Class> IMPLEMENTATION = new HashSet<Class>() {{
add(RemoteGraph.class);
}};
private static GremlinServer server;
private final Map<String,RemoteGraph> remoteCache = new HashMap<>();
private final Cluster cluster = Cluster.open();
private final Client client = cluster.connect();
static {
try {
startServer();
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public Graph openTestGraph(final Configuration config) {
final String serverGraphName = config.getString("connectionGraphName");
return remoteCache.computeIfAbsent(serverGraphName,
k -> RemoteGraph.open(new DriverRemoteConnection(cluster, config), TinkerGraph.class));
}
@Override
public Map<String, Object> getBaseConfiguration(final String graphName, Class<?> test, final String testMethodName,
final LoadGraphWith.GraphData loadGraphWith) {
final String serverGraphName = getServerGraphName(loadGraphWith);
final Supplier<Graph> graphGetter = () -> server.getServerGremlinExecutor().getGraphManager().getGraphs().get(serverGraphName);
return new HashMap<String, Object>() {{
put(Graph.GRAPH, RemoteGraph.class.getName());
put(RemoteGraph.GREMLIN_SERVERGRAPH_GRAPH_CLASS, TinkerGraph.class.getName());
put(RemoteGraph.GREMLIN_SERVERGRAPH_SERVER_CONNECTION_CLASS, DriverRemoteConnection.class.getName());
put("connectionGraphName", serverGraphName);
put("hidden.for.testing.only", graphGetter);
}};
}
@Override
public void clear(final Graph graph, final Configuration configuration) throws Exception {
// doesn't bother to clear grateful because i don't believe that ever gets mutated - read-only
client.submit("classic.clear();modern.clear();crew.clear();graph.clear();" +
"TinkerFactory.generateClassic(classic);" +
"TinkerFactory.generateModern(modern);" +
"TinkerFactory.generateTheCrew(crew);null").all().get();
}
@Override
public void loadGraphData(final Graph graph, final LoadGraphWith loadGraphWith, final Class testClass, final String testName) {
// server already loads with the all the graph instances for LoadGraphWith
}
@Override
public Set<Class> getImplementations() {
return IMPLEMENTATION;
}
public static void startServer() throws Exception {
final InputStream stream = RemoteGraphProvider.class.getResourceAsStream("gremlin-server-integration.yaml");
final Settings settings = Settings.read(stream);
ServerTestHelper.rewritePathsInGremlinServerSettings(settings);
server = new GremlinServer(settings);
server.start().join();
}
public static void stopServer() throws Exception {
server.stop().join();
server = null;
}
private static String getServerGraphName(final LoadGraphWith.GraphData loadGraphWith) {
final String serverGraphName;
if (null == loadGraphWith) return "graph";
switch (loadGraphWith) {
case CLASSIC:
serverGraphName = "classic";
break;
case MODERN:
serverGraphName = "modern";
break;
case GRATEFUL:
serverGraphName = "grateful";
break;
case CREW:
serverGraphName = "crew";
break;
default:
serverGraphName = "graph";
break;
}
return serverGraphName;
}
}
| gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/remote/RemoteGraphProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop.gremlin.remote;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.AbstractGraphProvider;
import org.apache.tinkerpop.gremlin.LoadGraphWith;
import org.apache.tinkerpop.gremlin.driver.Client;
import org.apache.tinkerpop.gremlin.driver.Cluster;
import org.apache.tinkerpop.gremlin.driver.remote.DriverRemoteConnection;
import org.apache.tinkerpop.gremlin.process.remote.RemoteGraph;
import org.apache.tinkerpop.gremlin.server.GremlinServer;
import org.apache.tinkerpop.gremlin.server.ServerTestHelper;
import org.apache.tinkerpop.gremlin.server.Settings;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class RemoteGraphProvider extends AbstractGraphProvider {
private static final Set<Class> IMPLEMENTATION = new HashSet<Class>() {{
add(RemoteGraph.class);
}};
private static GremlinServer server;
private final Map<String,RemoteGraph> remoteCache = new HashMap<>();
private final Cluster cluster = Cluster.open();
private final Client client = cluster.connect();
static {
try {
startServer();
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public Graph openTestGraph(final Configuration config) {
final String serverGraphName = config.getString("connectionGraphName");
return remoteCache.computeIfAbsent(serverGraphName,
k -> RemoteGraph.open(new DriverRemoteConnection(cluster, config), TinkerGraph.class));
}
@Override
public Map<String, Object> getBaseConfiguration(final String graphName, Class<?> test, final String testMethodName,
final LoadGraphWith.GraphData loadGraphWith) {
final String serverGraphName = getServerGraphName(loadGraphWith);
final Supplier<Graph> graphGetter = () -> server.getServerGremlinExecutor().getGraphManager().getGraphs().get(serverGraphName);
return new HashMap<String, Object>() {{
put(Graph.GRAPH, RemoteGraph.class.getName());
put(RemoteGraph.GREMLIN_SERVERGRAPH_GRAPH_CLASS, TinkerGraph.class.getName());
put(RemoteGraph.GREMLIN_SERVERGRAPH_SERVER_CONNECTION_CLASS, DriverRemoteConnection.class.getName());
put("connectionGraphName", serverGraphName);
put("hidden.for.testing.only", graphGetter);
}};
}
@Override
public void clear(final Graph graph, final Configuration configuration) throws Exception {
// doesn't bother to clear grateful because i don't believe that ever gets mutated - read-only
client.submit("classic.clear();modern.clear();crew.clear();graph.clear();" +
"TinkerFactory.generateClassic(classic);" +
"TinkerFactory.generateModern(modern);" +
"TinkerFactory.generateTheCrew(crew);null").all().get();
}
@Override
public void loadGraphData(final Graph graph, final LoadGraphWith loadGraphWith, final Class testClass, final String testName) {
// server already loads with the all the graph instances for LoadGraphWith
}
@Override
public Set<Class> getImplementations() {
return IMPLEMENTATION;
}
public static void startServer() throws Exception {
final InputStream stream = RemoteGraphProvider.class.getResourceAsStream("gremlin-server-integration.yaml");
final Settings settings = Settings.read(stream);
ServerTestHelper.rewritePathsInGremlinServerSettings(settings);
server = new GremlinServer(settings);
server.start().join();
}
public static void stopServer() throws Exception {
server.stop().join();
server = null;
}
private static String getServerGraphName(final LoadGraphWith.GraphData loadGraphWith) {
final String serverGraphName;
switch (loadGraphWith) {
case CLASSIC:
serverGraphName = "classic";
break;
case MODERN:
serverGraphName = "modern";
break;
case GRATEFUL:
serverGraphName = "grateful";
break;
case CREW:
serverGraphName = "crew";
break;
default:
serverGraphName = "graph";
break;
}
return serverGraphName;
}
}
| Bind the empty graph to tests that don't have LoadGraphWith annotation.
| gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/remote/RemoteGraphProvider.java | Bind the empty graph to tests that don't have LoadGraphWith annotation. |
|
Java | apache-2.0 | 71a5dfe15f9e7c96cbf663e384d23be45ea1965c | 0 | VisuFlow/visuflow-plugin | package de.unipaderborn.visuflow.ui.graph;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.JToolTip;
import org.graphstream.graph.Edge;
import org.graphstream.graph.Graph;
import org.graphstream.graph.Node;
import org.graphstream.graph.implementations.MultiGraph;
import org.graphstream.ui.geom.Point3;
import org.graphstream.ui.graphicGraph.GraphicElement;
import org.graphstream.ui.layout.Layout;
import org.graphstream.ui.layout.springbox.implementations.SpringBox;
import org.graphstream.ui.swingViewer.ViewPanel;
import org.graphstream.ui.view.Viewer;
import org.graphstream.ui.view.ViewerListener;
import org.graphstream.ui.view.ViewerPipe;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import de.unipaderborn.visuflow.model.DataModel;
import de.unipaderborn.visuflow.model.VFClass;
import de.unipaderborn.visuflow.model.VFMethod;
import de.unipaderborn.visuflow.util.ServiceUtil;
import de.visuflow.callgraph.ControlFlowGraph;
public class GraphManager implements Runnable, ViewerListener {
Graph graph;
String styleSheet;
private Viewer viewer;
private ViewPanel view;
List<VFClass> analysisData;
Container panel;
JApplet applet;
JButton zoomInButton, zoomOutButton, viewCenterButton, filterGraphButton, toggleLayout;
JToolBar settingsBar;
JTextField attribute;
JScrollPane scrollbar;
JComboBox<VFMethod> methodList;
double zoomInDelta, zoomOutDelta, maxZoomPercent, minZoomPercent;
boolean autoLayoutEnabled = false;
Layout graphLayout = new SpringBox();
private JToolTip tip;
public GraphManager(String graphName, String styleSheet)
{
System.setProperty("sun.awt.noerasebackground", "true");
System.setProperty("org.graphstream.ui.renderer", "org.graphstream.ui.j2dviewer.J2DGraphRenderer");
this.zoomInDelta = .2;
this.zoomOutDelta = .2;
this.maxZoomPercent = .5;
this.minZoomPercent = 2.0;
this.styleSheet = styleSheet;
createGraph(graphName);
createUI();
EventHandler dataModelHandler = new EventHandler() {
@Override
public void handleEvent(Event event) {
@SuppressWarnings("unchecked")
List<VFClass> vfClasses = (List<VFClass>) event.getProperty("model");
System.out.println("Model changed " + vfClasses.size() + " " + vfClasses);
}
};
Hashtable<String, String> properties = new Hashtable<String, String>();
properties.put(EventConstants.EVENT_TOPIC, DataModel.EA_TOPIC_DATA_MODEL_CHANGED);
ServiceUtil.registerService(EventHandler.class, dataModelHandler, properties);
}
public Container getApplet() {
return applet.getRootPane();
}
void createGraph(String graphName)
{
if(graph == null && graphName != null)
{
System.out.println("Graph object is null... Creating a new Graph");
graph = new MultiGraph(graphName);
}
graph.clear();
graph.addAttribute("ui.stylesheet", styleSheet);
graph.setStrict(true);
graph.setAutoCreate(true);
graph.addAttribute("ui.quality");
graph.addAttribute("ui.antialias");
viewer = new Viewer(graph, Viewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
viewer.setCloseFramePolicy(Viewer.CloseFramePolicy.CLOSE_VIEWER);
view = viewer.addDefaultView(false);
}
private void createUI() {
// TODO Auto-generated method stub
createZoomControls();
createViewListeners();
createAttributeControls();
createToggleLayoutButton();
createMethodComboBox();
createSettingsBar();
createPanel();
createAppletContainer();
}
private void createAppletContainer() {
// TODO Auto-generated method stub
applet = new JApplet();
scrollbar = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
view.setAutoscrolls(true);
scrollbar.setPreferredSize(new Dimension(20, 0));
scrollbar.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
// TODO Auto-generated method stub
System.out.println("vertical scrollbar " + e.getValue());
}
});
scrollbar.getHorizontalScrollBar().addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
// TODO Auto-generated method stub
Point3 viewCenter = view.getCamera().getViewCenter();
System.out.println("horizontal scrollbar " + e.getValue());
System.out.println("view center " + viewCenter);
if(e.getAdjustmentType() == AdjustmentEvent.UNIT_INCREMENT)
view.getCamera().setViewCenter(viewCenter.x + 1.0, viewCenter.y + 1.0, 0.0);
if(e.getAdjustmentType() == AdjustmentEvent.UNIT_DECREMENT)
view.getCamera().setViewCenter(viewCenter.x + 1.0, viewCenter.y + 1.0, 0.0);
}
});
applet.add(scrollbar);
}
private void createAttributeControls() {
// TODO Auto-generated method stub
attribute = new JTextField("ui.screenshot,C:/Users/Shashank B S/Desktop/image.png");
filterGraphButton = new JButton("SetAttribute");
filterGraphButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String[] newAttribute = attribute.getText().split(",");
graph.setAttribute(newAttribute[0], newAttribute[1]);
}
});
}
private void createMethodComboBox()
{
methodList = new JComboBox<VFMethod>();
// methodList.addItem("Select Method");
methodList.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
@SuppressWarnings("unchecked")
JComboBox<String> methodBox = (JComboBox<String>) e.getSource();
if(analysisData == null)
System.out.println("analysis data is null");
try {
VFMethod selectedMethod = (VFMethod) methodBox.getSelectedItem();
System.out.println(selectedMethod.getControlFlowGraph().listEdges.size());
System.out.println(selectedMethod.getControlFlowGraph().listNodes.size());
renderMethodCFG(selectedMethod.getControlFlowGraph());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
experimentalLayout();
}
});
}
private void createSettingsBar() {
// TODO Auto-generated method stub
settingsBar = new JToolBar("ControlsBar", JToolBar.HORIZONTAL);
settingsBar.add(zoomInButton);
settingsBar.add(zoomOutButton);
settingsBar.add(viewCenterButton);
settingsBar.add(methodList);
settingsBar.add(filterGraphButton);
settingsBar.add(attribute);
settingsBar.add(toggleLayout);
}
private void createPanel() {
// TODO Auto-generated method stub
panel = new JFrame().getContentPane();
panel.add(view);
panel.add(settingsBar, BorderLayout.PAGE_START);
}
private void createViewListeners() {
// TODO Auto-generated method stub
view.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
// TODO Auto-generated method stub
int rotationDirection = e.getWheelRotation();
if(rotationDirection > 0)
zoomIn();
else
zoomOut();
}
});
view.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent event) {
GraphicElement curElement = view.findNodeOrSpriteAt(event.getX(), event.getY());
if(curElement == null && tip != null) {
tip.setVisible(false);
setTip(null);
view.repaint();
}
if(curElement != null && tip == null) {
Node node=graph.getNode(curElement.getId());
String result = "<html><table>";
int maxToolTipLength=0;
int height=0;
for(String key:node.getEachAttributeKey()) {
if(key.startsWith("nodeData")){
height++;
Object value = node.getAttribute(key);
String tempVal=key.substring(key.lastIndexOf(".")+1)+" : "+value.toString();
if(tempVal.length()>maxToolTipLength){
maxToolTipLength=tempVal.length();
}
result+="<tr><td>"+key.substring(key.lastIndexOf(".")+1)+"</td>"+"<td>"+value.toString()+"</td></tr>";
}
}
result+="</table></html>";
tip = new JToolTip();
String tipText = result;
tip.setTipText(tipText);
tip.setBounds(event.getX() - tipText.length()*3 + 1, event.getY(), maxToolTipLength*6+3,height*30 );
setTip(tip);
tip.setVisible(true);
if(tipText.length() > 10) {
tip.setLocation(event.getX()-15, event.getY());
}
view.add(tip);
tip.repaint();
}
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
/*if(e.getButton() == 0)
{
Point dest = e.getPoint();
System.out.println("dragged with button");
System.out.println(dest);
Point3 currViewCenter = view.getCamera().getViewCenter();
for(int i=0; i<e.getClickCount(); i++)
{
view.getCamera().setViewCenter(currViewCenter.x+.2, currViewCenter.y+.2, 0);
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
}
}*/
}
});
}
private void zoomIn()
{
double viewPercent = view.getCamera().getViewPercent();
if(viewPercent > maxZoomPercent)
view.getCamera().setViewPercent(viewPercent - zoomInDelta);
}
private void zoomOut()
{
double viewPercent = view.getCamera().getViewPercent();
if(viewPercent < minZoomPercent)
view.getCamera().setViewPercent(viewPercent + zoomOutDelta);
}
private void createZoomControls() {
// TODO Auto-generated method stub
zoomInButton = new JButton("+");
zoomOutButton = new JButton("-");
viewCenterButton = new JButton("reset");
zoomInButton.setBackground(Color.gray);
zoomInButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
zoomIn();
}
});
zoomOutButton.setBackground(Color.gray);
zoomOutButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
zoomOut();
}
});
viewCenterButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
view.getCamera().resetView();
}
});
}
private void createToggleLayoutButton()
{
toggleLayout = new JButton();
toggleAutoLayout();
toggleLayout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
toggleAutoLayout();
}
});
}
private void toggleAutoLayout()
{
if(!autoLayoutEnabled)
{
if(viewer != null && graphLayout != null)
{
// viewer.enableAutoLayout(graphLayout);
experimentalLayout();
}
else if(viewer != null)
{
// viewer.enableAutoLayout();
experimentalLayout();
}
autoLayoutEnabled = true;
toggleLayout.setText("Disable Layouting");
}
else
{
viewer.disableAutoLayout();
autoLayoutEnabled = false;
toggleLayout.setText("Enable Layouting");
}
}
void generateGraphFromGraphStructure()
{
DataModel dataModel = ServiceUtil.getService(DataModel.class);
analysisData = dataModel.listClasses();
if(!analysisData.isEmpty()) {
VFClass first = analysisData.get(0);
for (VFMethod vfMethod : first.getMethods()) {
methodList.addItem(vfMethod);
}
}
}
private void renderMethodCFG(ControlFlowGraph interGraph) throws Exception
{
if(interGraph == null)
throw new Exception("GraphStructure is null");
Iterator<Node> itr = graph.iterator();
try {
for(Edge curr : itr.next())
{
if(graph.getId() != null)
{
graph.removeNode(curr.getNode0().getId());
graph.removeNode(curr.getNode1().getId());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
System.out.println(e.getMessage());
}
ListIterator<de.visuflow.callgraph.Edge> edgeIterator = interGraph.listEdges.listIterator();
while(edgeIterator.hasNext())
{
de.visuflow.callgraph.Edge currEdgeIterator = edgeIterator.next();
de.visuflow.callgraph.Node src = currEdgeIterator.getSource();
de.visuflow.callgraph.Node dest = currEdgeIterator.getDestination();
createGraphNode(src);
createGraphNode(dest);
createGraphEdge(src,dest);
}
}
private void createGraphEdge(de.visuflow.callgraph.Node src, de.visuflow.callgraph.Node dest) {
// TODO Auto-generated method stub
if(graph.getEdge("" + src.getId() + dest.getId()) == null)
{
Edge createdEdge = graph.addEdge(src.getId() + "" + dest.getId(), src.getId() + "", dest.getId() + "", true);
createdEdge.addAttribute("ui.label", "{a,b}");
createdEdge.addAttribute("edgeData.outSet", "{a,b}");
}
}
private void createGraphNode(de.visuflow.callgraph.Node node) {
// TODO Auto-generated method stub
if(graph.getNode(node.getId() + "") == null)
{
Node createdNode = graph.addNode(node.getId() + "");
createdNode.setAttribute("ui.label", node.getLabel().toString());
createdNode.setAttribute("nodeData.unit", node.getLabel().toString());
createdNode.setAttribute("nodeData.unitType", node.getLabel().getClass());
createdNode.setAttribute("nodeData.inSet", "coming soon");
createdNode.setAttribute("nodeData.outSet", "coming soon");
}
}
private void experimentalLayout()
{
// viewer.disableAutoLayout();
double spacing = 2.0;
double rowSpacing = 12.0;
double nodeCount = graph.getNodeCount() * spacing;
Iterator<Node> nodeIterator = graph.getNodeIterator();
while(nodeIterator.hasNext())
{
Node curr = nodeIterator.next();
Iterator<Edge> leavingEdgeIterator = curr.getEdgeIterator();
double outEdges = 0.0;
while(leavingEdgeIterator.hasNext())
{
Edge outEdge = leavingEdgeIterator.next();
Node target = outEdge.getTargetNode();
target.setAttribute("xyz", outEdges, nodeCount, 0.0);
outEdges += rowSpacing;
}
curr.setAttribute("xyz", 0.0, nodeCount, 0.0);
nodeCount -= spacing;
}
}
void toggleNode(String id){
System.out.println("Togglenodes called");
Node n = graph.getNode(id);
Object[] pos = n.getAttribute("xyz");
Iterator<Node> it = n.getBreadthFirstIterator(true);
if(n.hasAttribute("collapsed")){
n.removeAttribute("collapsed");
while(it.hasNext()){
Node m = it.next();
for(Edge e : m.getLeavingEdgeSet()) {
e.removeAttribute("ui.hide");
}
m.removeAttribute("layout.frozen");
m.setAttribute("x",((double)pos[0])+Math.random()*0.0001);
m.setAttribute("y",((double)pos[1])+Math.random()*0.0001);
m.removeAttribute("ui.hide");
}
n.removeAttribute("ui.class");
} else {
n.setAttribute("ui.class", "plus");
n.setAttribute("collapsed");
while(it.hasNext()){
Node m = it.next();
for(Edge e : m.getLeavingEdgeSet()) {
e.setAttribute("ui.hide");
}
if(n != m) {
m.setAttribute("layout.frozen");
// m.setAttribute("x", ((double) pos[0]) + Math.random() * 0.0001);
// m.setAttribute("y", ((double) pos[1]) + Math.random() * 0.0001);
m.setAttribute("xyz", ((double) pos[0]) + Math.random() * 0.0001, ((double) pos[1]) + Math.random() * 0.0001, 0.0);
m.setAttribute("ui.hide");
}
}
}
}
@Override
public void run() {
// TODO Auto-generated method stub
generateGraphFromGraphStructure();
ViewerPipe fromViewer = viewer.newViewerPipe();
fromViewer.addViewerListener(this);
fromViewer.addSink(graph);
/*Iterator<? extends Node> nodeIterator = graph.getEachNode().iterator();
while(nodeIterator.hasNext())
{
Node curr = nodeIterator.next();
System.out.println("Attribute count " + curr.getAttributeCount());
System.out.println("nodeData.unit " + curr.getAttribute("nodeData.unit").toString());
}*/
// FIXME the Thread.sleep slows down the loop, so that it does not eat up the CPU
// but this really should be implemented differently. isn't there an event listener
// or something we can use, so that we call pump() only when necessary
while(true) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
fromViewer.pump();
}
}
@Override
public void buttonPushed(String id) {
// TODO Auto-generated method stub
toggleNode(id);
experimentalLayout();
}
@Override
public void buttonReleased(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void viewClosed(String arg0) {
// TODO Auto-generated method stub
}
protected void setTip(JToolTip toolTip) {
this.tip = toolTip;
}
} | src/de/unipaderborn/visuflow/ui/graph/GraphManager.java | package de.unipaderborn.visuflow.ui.graph;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.JToolTip;
import org.graphstream.graph.Edge;
import org.graphstream.graph.Graph;
import org.graphstream.graph.Node;
import org.graphstream.graph.implementations.MultiGraph;
import org.graphstream.ui.geom.Point3;
import org.graphstream.ui.graphicGraph.GraphicElement;
import org.graphstream.ui.layout.Layout;
import org.graphstream.ui.layout.springbox.implementations.SpringBox;
import org.graphstream.ui.swingViewer.ViewPanel;
import org.graphstream.ui.view.Viewer;
import org.graphstream.ui.view.ViewerListener;
import org.graphstream.ui.view.ViewerPipe;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import de.unipaderborn.visuflow.model.DataModel;
import de.unipaderborn.visuflow.model.VFClass;
import de.unipaderborn.visuflow.model.VFMethod;
import de.unipaderborn.visuflow.util.ServiceUtil;
import de.visuflow.callgraph.ControlFlowGraph;
public class GraphManager implements Runnable, ViewerListener {
Graph graph;
String styleSheet;
private Viewer viewer;
private ViewPanel view;
List<VFClass> analysisData;
Container panel;
JApplet applet;
JButton zoomInButton, zoomOutButton, viewCenterButton, filterGraphButton, toggleLayout;
JToolBar settingsBar;
JTextField attribute;
JScrollPane scrollbar;
JComboBox<VFMethod> methodList;
double zoomInDelta, zoomOutDelta, maxZoomPercent, minZoomPercent;
boolean autoLayoutEnabled = false;
Layout graphLayout = new SpringBox();
private JToolTip tip;
public GraphManager(String graphName, String styleSheet)
{
System.setProperty("sun.awt.noerasebackground", "true");
System.setProperty("org.graphstream.ui.renderer", "org.graphstream.ui.j2dviewer.J2DGraphRenderer");
this.zoomInDelta = .2;
this.zoomOutDelta = .2;
this.maxZoomPercent = .5;
this.minZoomPercent = 2.0;
this.styleSheet = styleSheet;
createGraph(graphName);
createUI();
EventHandler dataModelHandler = new EventHandler() {
@Override
public void handleEvent(Event event) {
@SuppressWarnings("unchecked")
List<VFClass> vfClasses = (List<VFClass>) event.getProperty("model");
System.out.println("Model changed " + vfClasses.size() + " " + vfClasses);
}
};
Hashtable<String, String> properties = new Hashtable<String, String>();
properties.put(EventConstants.EVENT_TOPIC, DataModel.EA_TOPIC_DATA_MODEL_CHANGED);
ServiceUtil.registerService(EventHandler.class, dataModelHandler, properties);
}
public Container getApplet() {
return applet.getRootPane();
}
void createGraph(String graphName)
{
if(graph == null && graphName != null)
{
System.out.println("Graph object is null... Creating a new Graph");
graph = new MultiGraph(graphName);
}
graph.clear();
graph.addAttribute("ui.stylesheet", styleSheet);
graph.setStrict(true);
graph.setAutoCreate(true);
graph.addAttribute("ui.quality");
graph.addAttribute("ui.antialias");
viewer = new Viewer(graph, Viewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
viewer.setCloseFramePolicy(Viewer.CloseFramePolicy.CLOSE_VIEWER);
view = viewer.addDefaultView(false);
}
private void createUI() {
// TODO Auto-generated method stub
createZoomControls();
createViewListeners();
createAttributeControls();
createToggleLayoutButton();
createMethodComboBox();
createSettingsBar();
createPanel();
createAppletContainer();
}
private void createAppletContainer() {
// TODO Auto-generated method stub
applet = new JApplet();
scrollbar = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
view.setAutoscrolls(true);
scrollbar.setPreferredSize(new Dimension(20, 0));
scrollbar.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
// TODO Auto-generated method stub
System.out.println("vertical scrollbar " + e.getValue());
}
});
scrollbar.getHorizontalScrollBar().addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
// TODO Auto-generated method stub
Point3 viewCenter = view.getCamera().getViewCenter();
System.out.println("horizontal scrollbar " + e.getValue());
System.out.println("view center " + viewCenter);
if(e.getAdjustmentType() == AdjustmentEvent.UNIT_INCREMENT)
view.getCamera().setViewCenter(viewCenter.x + 1.0, viewCenter.y + 1.0, 0.0);
if(e.getAdjustmentType() == AdjustmentEvent.UNIT_DECREMENT)
view.getCamera().setViewCenter(viewCenter.x + 1.0, viewCenter.y + 1.0, 0.0);
}
});
applet.add(scrollbar);
}
private void createAttributeControls() {
// TODO Auto-generated method stub
attribute = new JTextField("ui.screenshot,C:/Users/Shashank B S/Desktop/image.png");
filterGraphButton = new JButton("SetAttribute");
filterGraphButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String[] newAttribute = attribute.getText().split(",");
graph.setAttribute(newAttribute[0], newAttribute[1]);
}
});
}
private void createMethodComboBox()
{
methodList = new JComboBox<VFMethod>();
// methodList.addItem("Select Method");
methodList.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
@SuppressWarnings("unchecked")
JComboBox<String> methodBox = (JComboBox<String>) e.getSource();
if(analysisData == null)
System.out.println("analysis data is null");
try {
VFMethod selectedMethod = (VFMethod) methodBox.getSelectedItem();
System.out.println(selectedMethod.getControlFlowGraph().listEdges.size());
System.out.println(selectedMethod.getControlFlowGraph().listNodes.size());
renderMethodCFG(selectedMethod.getControlFlowGraph());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
experimentalLayout();
}
});
}
private void createSettingsBar() {
// TODO Auto-generated method stub
settingsBar = new JToolBar("ControlsBar", JToolBar.HORIZONTAL);
settingsBar.add(zoomInButton);
settingsBar.add(zoomOutButton);
settingsBar.add(viewCenterButton);
settingsBar.add(methodList);
settingsBar.add(filterGraphButton);
settingsBar.add(attribute);
settingsBar.add(toggleLayout);
}
private void createPanel() {
// TODO Auto-generated method stub
panel = new JFrame().getContentPane();
panel.add(view);
panel.add(settingsBar, BorderLayout.PAGE_START);
}
private void createViewListeners() {
// TODO Auto-generated method stub
view.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
// TODO Auto-generated method stub
int rotationDirection = e.getWheelRotation();
if(rotationDirection > 0)
zoomIn();
else
zoomOut();
}
});
view.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent event) {
GraphicElement curElement = view.findNodeOrSpriteAt(event.getX(), event.getY());
if(curElement == null && tip != null) {
tip.setVisible(false);
setTip(null);
view.repaint();
}
if(curElement != null && tip == null) {
Node node=graph.getNode(curElement.getId());
String result = "<html>";
int maxToolTipLength=0;
int height=0;
for(String key:node.getEachAttributeKey()) {
if(key.startsWith("nodeData")){
height++;
Object value = node.getAttribute(key);
String tempVal=key.substring(key.lastIndexOf(".")+1)+" : "+value.toString();
if(tempVal.length()>maxToolTipLength){
maxToolTipLength=tempVal.length();
}
result+=tempVal+"<br>";
}
}
result+="</html>";
tip = new JToolTip();
String tipText = result;
tip.setTipText(tipText);
tip.setBounds(event.getX() - tipText.length()*3 + 1, event.getY(), maxToolTipLength*6+3,height*20 );
setTip(tip);
tip.setVisible(true);
if(tipText.length() > 10) {
tip.setLocation(event.getX()-15, event.getY());
}
view.add(tip);
tip.repaint();
}
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
/*if(e.getButton() == 0)
{
Point dest = e.getPoint();
System.out.println("dragged with button");
System.out.println(dest);
Point3 currViewCenter = view.getCamera().getViewCenter();
for(int i=0; i<e.getClickCount(); i++)
{
view.getCamera().setViewCenter(currViewCenter.x+.2, currViewCenter.y+.2, 0);
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
}
}*/
}
});
}
private void zoomIn()
{
double viewPercent = view.getCamera().getViewPercent();
if(viewPercent > maxZoomPercent)
view.getCamera().setViewPercent(viewPercent - zoomInDelta);
}
private void zoomOut()
{
double viewPercent = view.getCamera().getViewPercent();
if(viewPercent < minZoomPercent)
view.getCamera().setViewPercent(viewPercent + zoomOutDelta);
}
private void createZoomControls() {
// TODO Auto-generated method stub
zoomInButton = new JButton("+");
zoomOutButton = new JButton("-");
viewCenterButton = new JButton("reset");
zoomInButton.setBackground(Color.gray);
zoomInButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
zoomIn();
}
});
zoomOutButton.setBackground(Color.gray);
zoomOutButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
zoomOut();
}
});
viewCenterButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
view.getCamera().resetView();
}
});
}
private void createToggleLayoutButton()
{
toggleLayout = new JButton();
toggleAutoLayout();
toggleLayout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
toggleAutoLayout();
}
});
}
private void toggleAutoLayout()
{
if(!autoLayoutEnabled)
{
if(viewer != null && graphLayout != null)
{
// viewer.enableAutoLayout(graphLayout);
experimentalLayout();
}
else if(viewer != null)
{
// viewer.enableAutoLayout();
experimentalLayout();
}
autoLayoutEnabled = true;
toggleLayout.setText("Disable Layouting");
}
else
{
viewer.disableAutoLayout();
autoLayoutEnabled = false;
toggleLayout.setText("Enable Layouting");
}
}
void generateGraphFromGraphStructure()
{
DataModel dataModel = ServiceUtil.getService(DataModel.class);
analysisData = dataModel.listClasses();
if(!analysisData.isEmpty()) {
VFClass first = analysisData.get(0);
for (VFMethod vfMethod : first.getMethods()) {
methodList.addItem(vfMethod);
}
}
}
private void renderMethodCFG(ControlFlowGraph interGraph) throws Exception
{
if(interGraph == null)
throw new Exception("GraphStructure is null");
Iterator<Node> itr = graph.iterator();
try {
for(Edge curr : itr.next())
{
if(graph.getId() != null)
{
graph.removeNode(curr.getNode0().getId());
graph.removeNode(curr.getNode1().getId());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
System.out.println(e.getMessage());
}
ListIterator<de.visuflow.callgraph.Edge> edgeIterator = interGraph.listEdges.listIterator();
while(edgeIterator.hasNext())
{
de.visuflow.callgraph.Edge currEdgeIterator = edgeIterator.next();
de.visuflow.callgraph.Node src = currEdgeIterator.getSource();
de.visuflow.callgraph.Node dest = currEdgeIterator.getDestination();
createGraphNode(src);
createGraphNode(dest);
createGraphEdge(src,dest);
}
}
private void createGraphEdge(de.visuflow.callgraph.Node src, de.visuflow.callgraph.Node dest) {
// TODO Auto-generated method stub
if(graph.getEdge("" + src.getId() + dest.getId()) == null)
{
Edge createdEdge = graph.addEdge(src.getId() + "" + dest.getId(), src.getId() + "", dest.getId() + "", true);
createdEdge.addAttribute("ui.label", "{a,b}");
createdEdge.addAttribute("edgeData.outSet", "{a,b}");
}
}
private void createGraphNode(de.visuflow.callgraph.Node node) {
// TODO Auto-generated method stub
if(graph.getNode(node.getId() + "") == null)
{
Node createdNode = graph.addNode(node.getId() + "");
createdNode.setAttribute("ui.label", node.getLabel().toString());
createdNode.setAttribute("nodeData.unit", node.getLabel().toString());
createdNode.setAttribute("nodeData.unitType", node.getLabel().getClass());
createdNode.setAttribute("nodeData.inSet", "coming soon");
createdNode.setAttribute("nodeData.outSet", "coming soon");
}
}
private void experimentalLayout()
{
// viewer.disableAutoLayout();
double spacing = 2.0;
double rowSpacing = 12.0;
double nodeCount = graph.getNodeCount() * spacing;
Iterator<Node> nodeIterator = graph.getNodeIterator();
while(nodeIterator.hasNext())
{
Node curr = nodeIterator.next();
Iterator<Edge> leavingEdgeIterator = curr.getEdgeIterator();
double outEdges = 0.0;
while(leavingEdgeIterator.hasNext())
{
Edge outEdge = leavingEdgeIterator.next();
Node target = outEdge.getTargetNode();
target.setAttribute("xyz", outEdges, nodeCount, 0.0);
outEdges += rowSpacing;
}
curr.setAttribute("xyz", 0.0, nodeCount, 0.0);
nodeCount -= spacing;
}
}
void toggleNode(String id){
System.out.println("Togglenodes called");
Node n = graph.getNode(id);
Object[] pos = n.getAttribute("xyz");
Iterator<Node> it = n.getBreadthFirstIterator(true);
if(n.hasAttribute("collapsed")){
n.removeAttribute("collapsed");
while(it.hasNext()){
Node m = it.next();
for(Edge e : m.getLeavingEdgeSet()) {
e.removeAttribute("ui.hide");
}
m.removeAttribute("layout.frozen");
m.setAttribute("x",((double)pos[0])+Math.random()*0.0001);
m.setAttribute("y",((double)pos[1])+Math.random()*0.0001);
m.removeAttribute("ui.hide");
}
n.removeAttribute("ui.class");
} else {
n.setAttribute("ui.class", "plus");
n.setAttribute("collapsed");
while(it.hasNext()){
Node m = it.next();
for(Edge e : m.getLeavingEdgeSet()) {
e.setAttribute("ui.hide");
}
if(n != m) {
m.setAttribute("layout.frozen");
// m.setAttribute("x", ((double) pos[0]) + Math.random() * 0.0001);
// m.setAttribute("y", ((double) pos[1]) + Math.random() * 0.0001);
m.setAttribute("xyz", ((double) pos[0]) + Math.random() * 0.0001, ((double) pos[1]) + Math.random() * 0.0001, 0.0);
m.setAttribute("ui.hide");
}
}
}
}
@Override
public void run() {
// TODO Auto-generated method stub
generateGraphFromGraphStructure();
ViewerPipe fromViewer = viewer.newViewerPipe();
fromViewer.addViewerListener(this);
fromViewer.addSink(graph);
/*Iterator<? extends Node> nodeIterator = graph.getEachNode().iterator();
while(nodeIterator.hasNext())
{
Node curr = nodeIterator.next();
System.out.println("Attribute count " + curr.getAttributeCount());
System.out.println("nodeData.unit " + curr.getAttribute("nodeData.unit").toString());
}*/
// FIXME the Thread.sleep slows down the loop, so that it does not eat up the CPU
// but this really should be implemented differently. isn't there an event listener
// or something we can use, so that we call pump() only when necessary
while(true) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
fromViewer.pump();
}
}
@Override
public void buttonPushed(String id) {
// TODO Auto-generated method stub
toggleNode(id);
experimentalLayout();
}
@Override
public void buttonReleased(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void viewClosed(String arg0) {
// TODO Auto-generated method stub
}
protected void setTip(JToolTip toolTip) {
this.tip = toolTip;
}
} | Added table layout to tooltip
| src/de/unipaderborn/visuflow/ui/graph/GraphManager.java | Added table layout to tooltip |
|
Java | apache-2.0 | 5f2e7562333c7d7d42bcb5c06303a4b5d23eee0f | 0 | BrunoEberhard/minimal-j,BrunoEberhard/minimal-j,BrunoEberhard/minimal-j | package org.minimalj.model;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.minimalj.model.properties.PropertyInterface;
public class KeysTest {
@BeforeClass
public static void initializeAllClasses() {
new TestClass1();
new TestClass2();
new TestClass3();
new TestClass4();
}
@Test
public void accessString() {
TestClass1 object1 = new TestClass1();
object1.s1 = "Test";
PropertyInterface property = Keys.getProperty(TestClass1.$.s1);
Assert.assertEquals("Get should return the value of the public field", object1.s1, property.getValue(object1));
}
@Test
public void accessSubString() {
TestClass2 testObject2 = new TestClass2();
testObject2.testClass1.s1 = "TestS1";
PropertyInterface property = Keys.getProperty(TestClass2.$.testClass1.s1);
Assert.assertEquals("Get should return the value of referenced Objects", testObject2.testClass1.s1, property.getValue(testObject2));
}
@Test
public void accessViaGetter() {
TestClass2 testObject2 = new TestClass2();
testObject2.setS3("access5");
PropertyInterface property = Keys.getProperty(TestClass2.$.getS3());
Assert.assertEquals("If private, get should use the getter method", testObject2.getS3(), property.getValue(testObject2));
property.setValue(testObject2, "access5a");
Assert.assertEquals("If private, get should use the setter method to change value", testObject2.getS3(), property.getValue(testObject2));
}
@Test
public void accessViaIs() {
TestClass2 testObject2 = new TestClass2();
testObject2.setB1(true);
PropertyInterface property = Keys.getProperty(TestClass2.$.getB1());
Assert.assertEquals("For private boolean, get should use the isXy method", testObject2.getB1(), property.getValue(testObject2));
property.setValue(testObject2, Boolean.FALSE);
Assert.assertEquals("For private boolean, set should use the setXy method", testObject2.getB1(), property.getValue(testObject2));
}
@Test
public void accessChildViaIs() {
TestClass2 testObject2 = new TestClass2();
testObject2.testClass1.b2 = true;
testObject2.testClass1b.b2 = false;
PropertyInterface property = Keys.getProperty(TestClass2.$.testClass1.getB2());
Assert.assertEquals("For private boolean, get should use the isXy method, even for related objects", testObject2.testClass1.getB2(), property.getValue(testObject2));
PropertyInterface propertyB = Keys.getProperty(TestClass2.$.getTestClass1b().getB2());
Assert.assertEquals("For private boolean, get should use the isXy method, even for related objects", testObject2.getTestClass1b().getB2(), propertyB.getValue(testObject2));
testObject2.testClass1b.b2 = true;
Assert.assertEquals("For private boolean, get should use the isXy method, even for related objects", testObject2.getTestClass1b().getB2(), propertyB.getValue(testObject2));
testObject2.testClass1.b2 = false;
Assert.assertEquals("For private boolean, get should use the isXy method, even for related objects", testObject2.testClass1.getB2(), property.getValue(testObject2));
}
@Test
public void updateList() {
TestClass3 testClass3 = new TestClass3();
List<TestClass1> list = testClass3.list;
list.add(new TestClass1());
Assert.assertEquals(1, testClass3.list.size());
PropertyInterface property = Keys.getProperty(TestClass3.$.list);
property.setValue(testClass3, list);
Assert.assertEquals("After set a final list field with its existing values the content must be the same", 1, testClass3.list.size());
List<TestClass1> list2 = new ArrayList<>();
list2.add(new TestClass1());
list2.add(new TestClass1());
property.setValue(testClass3, list2);
Assert.assertEquals("Update of final list field with new values failed", list2.size(), testClass3.list.size());
}
@Test
public void methodFieldOfInlineInTwoClasses() {
TestClass2 testClass2 = new TestClass2();
testClass2.tc1.setB2(true);
TestClass4 testClass4 = new TestClass4();
testClass4.testClass1.setB2(false);
String message = "Method property should return correct value even if it is contained in two inner classes";
Assert.assertEquals(message, Boolean.TRUE, Keys.getProperty(TestClass2.$.tc1.getB2()).getValue(testClass2));
Assert.assertEquals(message, Boolean.FALSE, Keys.getProperty(TestClass4.$.testClass1.getB2()).getValue(testClass4));
}
@Test
public void fieldsOfGetterReturnType() {
Assert.assertNotNull(TestClass2.$.getTestClass1b().s1);
String message = "Chained properties should have correct path even if they contain a method property";
Assert.assertEquals(message, "testClass1b", Keys.getProperty(TestClass2.$.getTestClass1b()).getPath());
Assert.assertEquals(message, "testClass1b.s1", Keys.getProperty(TestClass2.$.getTestClass1b().s1).getPath());
Assert.assertEquals(message, "testClass1b.testClass3.list", Keys.getProperty(TestClass2.$.getTestClass1b().getTestClass3().list).getPath());
}
//
public static class TestClass1 {
public static final TestClass1 $ = Keys.of(TestClass1.class);
public String s1;
private Boolean b2;
public Boolean getB2() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "b2", Boolean.class);
return b2;
}
public void setB2(Boolean b2) {
this.b2 = b2;
}
public TestClass3 getTestClass3() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "testClass3", TestClass3.class);
return null;
}
}
public static class TestClass2 {
public static final TestClass2 $ = Keys.of(TestClass2.class);
public String s2;
private String s3;
private Boolean b1;
public final TestClass1 testClass1 = new TestClass1();
private final TestClass1 testClass1b = new TestClass1();
public final TestClass1 tc1 = new TestClass1();
public String getS3() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "s3", String.class);
return s3;
}
public void setS3(String s3) {
this.s3 = s3;
}
public Boolean getB1() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "b1", Boolean.class);
return b1;
}
public void setB1(Boolean b1) {
this.b1 = b1;
}
public TestClass1 getTestClass1b() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "testClass1b", TestClass1.class);
return testClass1b;
}
}
public static class TestClass3 {
public static final TestClass3 $ = Keys.of(TestClass3.class);
public final List<TestClass1> list = new ArrayList<>();
}
public static class TestClass4 {
public static final TestClass4 $ = Keys.of(TestClass4.class);
public final TestClass1 testClass1 = new TestClass1();
}
}
| src/test/java/org/minimalj/model/KeysTest.java | package org.minimalj.model;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.minimalj.model.properties.PropertyInterface;
public class KeysTest {
@BeforeClass
public static void initializeAllClasses() {
new TestClass1();
new TestClass2();
new TestClass3();
new TestClass4();
}
@Test
public void accessString() {
TestClass1 object1 = new TestClass1();
object1.s1 = "Test";
PropertyInterface property = Keys.getProperty(TestClass1.$.s1);
Assert.assertEquals("Get should return the value of the public field", object1.s1, property.getValue(object1));
}
@Test
public void accessSubString() {
TestClass2 testObject2 = new TestClass2();
testObject2.testClass1.s1 = "TestS1";
PropertyInterface property = Keys.getProperty(TestClass2.$.testClass1.s1);
Assert.assertEquals("Get should return the value of referenced Objects", testObject2.testClass1.s1, property.getValue(testObject2));
}
@Test
public void accessViaGetter() {
TestClass2 testObject2 = new TestClass2();
testObject2.setS3("access5");
PropertyInterface property = Keys.getProperty(TestClass2.$.getS3());
Assert.assertEquals("If private, get should use the getter method", testObject2.getS3(), property.getValue(testObject2));
property.setValue(testObject2, "access5a");
Assert.assertEquals("If private, get should use the setter method to change value", testObject2.getS3(), property.getValue(testObject2));
}
@Test
public void accessViaIs() {
TestClass2 testObject2 = new TestClass2();
testObject2.setB1(true);
PropertyInterface property = Keys.getProperty(TestClass2.$.getB1());
Assert.assertEquals("For private boolean, get should use the isXy method", testObject2.getB1(), property.getValue(testObject2));
property.setValue(testObject2, Boolean.FALSE);
Assert.assertEquals("For private boolean, set should use the setXy method", testObject2.getB1(), property.getValue(testObject2));
}
@Test
public void accessChildViaIs() {
TestClass2 testObject2 = new TestClass2();
testObject2.testClass1.b2 = true;
testObject2.testClass1b.b2 = false;
PropertyInterface property = Keys.getProperty(TestClass2.$.testClass1.getB2());
Assert.assertEquals("For private boolean, get should use the isXy method, even for related objects", testObject2.testClass1.getB2(), property.getValue(testObject2));
PropertyInterface propertyB = Keys.getProperty(TestClass2.$.getTestClass1b().getB2());
Assert.assertEquals("For private boolean, get should use the isXy method, even for related objects", testObject2.getTestClass1b().getB2(), propertyB.getValue(testObject2));
testObject2.testClass1b.b2 = true;
Assert.assertEquals("For private boolean, get should use the isXy method, even for related objects", testObject2.getTestClass1b().getB2(), propertyB.getValue(testObject2));
testObject2.testClass1.b2 = false;
Assert.assertEquals("For private boolean, get should use the isXy method, even for related objects", testObject2.testClass1.getB2(), property.getValue(testObject2));
}
@Test
public void updateList() {
TestClass3 testClass3 = new TestClass3();
List<TestClass1> list = testClass3.list;
list.add(new TestClass1());
Assert.assertEquals(1, testClass3.list.size());
PropertyInterface property = Keys.getProperty(TestClass3.$.list);
property.setValue(testClass3, list);
Assert.assertEquals("After set a final list field with its existing values the content must be the same", 1, testClass3.list.size());
List<TestClass1> list2 = new ArrayList<>();
list2.add(new TestClass1());
list2.add(new TestClass1());
property.setValue(testClass3, list2);
Assert.assertEquals("Update of final list field with new values failed", list2.size(), testClass3.list.size());
}
@Test
public void methodFieldOfInlineInTwoClasses() {
TestClass2 testClass2 = new TestClass2();
TestClass4 testClass4 = new TestClass4();
Keys.getProperty(TestClass2.$.tc1.getB2()).getValue(testClass2);
Keys.getProperty(TestClass4.$.testClass1.getB2()).getValue(testClass4);
}
@Test
public void fieldsOfGetterReturnType() {
Assert.assertNotNull(TestClass2.$.getTestClass1b().s1);
Assert.assertEquals("testClass1b", Keys.getProperty(TestClass2.$.getTestClass1b()).getPath());
Assert.assertEquals("testClass1b.s1", Keys.getProperty(TestClass2.$.getTestClass1b().s1).getPath());
Assert.assertEquals("testClass1b.testClass3.list", Keys.getProperty(TestClass2.$.getTestClass1b().getTestClass3().list).getPath());
}
//
public static class TestClass1 {
public static final TestClass1 $ = Keys.of(TestClass1.class);
public String s1;
private Boolean b2;
public Boolean getB2() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "b2", Boolean.class);
return b2;
}
public void setB2(Boolean b2) {
this.b2 = b2;
}
public TestClass3 getTestClass3() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "testClass3", TestClass3.class);
return null;
}
}
public static class TestClass2 {
public static final TestClass2 $ = Keys.of(TestClass2.class);
public String s2;
private String s3;
private Boolean b1;
public final TestClass1 testClass1 = new TestClass1();
private final TestClass1 testClass1b = new TestClass1();
public final TestClass1 tc1 = new TestClass1();
public String getS3() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "s3", String.class);
return s3;
}
public void setS3(String s3) {
this.s3 = s3;
}
public Boolean getB1() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "b1", Boolean.class);
return b1;
}
public void setB1(Boolean b1) {
this.b1 = b1;
}
public TestClass1 getTestClass1b() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "testClass1b", TestClass1.class);
return testClass1b;
}
}
public static class TestClass3 {
public static final TestClass3 $ = Keys.of(TestClass3.class);
public final List<TestClass1> list = new ArrayList<>();
}
public static class TestClass4 {
public static final TestClass4 $ = Keys.of(TestClass4.class);
public final TestClass1 testClass1 = new TestClass1();
}
}
| KeysTest: added messages to assertions | src/test/java/org/minimalj/model/KeysTest.java | KeysTest: added messages to assertions |
|
Java | apache-2.0 | bddc34ba5f20c268a4d331f1cc1701d979eebb90 | 0 | utdrobotchess/chess-game | package chess.engine;
/**
* Static class to construct a chessboard from squares that are connected properly
* to each other.
* @author Ryan J. Marcotte
*/
public class ChessBoardBuilder {
private static Square[] boardSquares;
//for each location on the chessboard, denotes its neighboring locations (prior to remapping)
private final static int[][] mappingReferences = new int[100][8];
//denotes the indexes to which Squares ordered 0-99 should be mapped; inverse
//of occupantToLocationMapping
private final static int[] locationToOccupantMapping = new int[100];
//denotes the Square that occupies each index; inverse of locationToOccupantMapping
private final static int[] occupantToLocationMapping = {
64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 0, 1, 2, 3, 4, 5, 6, 7, 75,
76, 8, 9, 10, 11, 12, 13, 14, 15, 77,
78, 16, 17, 18, 19, 20, 21, 22, 23, 79,
80, 24, 25, 26, 27, 28, 29, 30, 31, 81,
82, 32, 33, 34, 35, 36, 37, 38, 39, 83,
84, 40, 41, 42, 43, 44, 45, 46, 47, 85,
86, 48, 49, 50, 51, 52, 53, 54, 55, 87,
88, 56, 57, 58, 59, 60, 61, 62, 63, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99
};
protected static void build(ChessBoard board) {
boardSquares = board.getAllSquares();
buildSquares();
assignMappingReferences();
applyMappingReferencesToBoard();
}
private static void buildSquares() {
for(int i = 0; i < 100; i++) {
if(i < 64)
boardSquares[i] = InteriorSquare.generateInteriorSquareAt(i);
else
boardSquares[i] = PerimeterSquare.generatePerimeterSquareAt(i);
}
}
private static void assignMappingReferences() {
mapLocationsToOccupants();
initializeMappingReferences();
//each type of mapping reference has a unique rule that maps a location
//to its directional neighbor; we apply these rules, skipping rows and
//columns that do not have a particular directional neighbor
assignNorthMappingReferences();
assignNorthEastMappingReferences();
assignEastMappingReferences();
assignSouthEastMappingReferences();
assignSouthMappingReferences();
assignSouthWestMappingReferences();
assignWestMappingReferences();
assignNorthWestMappingReferences();
}
private static void mapLocationsToOccupants() {
//from the hard-coded locationToOccupantMapping array, we define the
//inverse locationToOccupantMapping array
for(int i = 0; i < 100; i++)
locationToOccupantMapping[occupantToLocationMapping[i]] = i;
}
private static void initializeMappingReferences() {
for(int i = 0; i < 100; i++)
for(int j = 0; j < 8; j++)
mappingReferences[i][j] = -1;
}
private static void assignNorthMappingReferences() {
//skip the first row
for(int i = 10; i < 100; i++)
mappingReferences[i][0] = i - 10;
}
private static void assignNorthEastMappingReferences() {
//skip the first row and last column
for(int i = 10; i < 100; i++)
if(i % 10 != 9)
mappingReferences[i][1] = i - 9;
}
private static void assignEastMappingReferences() {
//skip the last column
for(int i = 0; i < 100; i++)
if(i % 10 != 9)
mappingReferences[i][2] = i + 1;
}
private static void assignSouthEastMappingReferences() {
//skip the last row and last column
for(int i = 0; i < 90; i++)
if(i % 10 != 9)
mappingReferences[i][3] = i + 11;
}
private static void assignSouthMappingReferences() {
//skip the last row
for(int i = 0; i < 90; i++)
mappingReferences[i][4] = i + 10;
}
private static void assignSouthWestMappingReferences() {
//skip the last row and first column
for(int i = 0; i < 90; i++)
if(i % 10 != 0)
mappingReferences[i][5] = i + 9;
}
private static void assignWestMappingReferences() {
//skip the first column
for(int i = 0; i < 100; i++)
if(i % 10 != 0)
mappingReferences[i][6] = i - 1;
}
private static void assignNorthWestMappingReferences() {
//skip the first row and first column
for(int i = 10; i < 100; i++)
if(i % 10 != 0)
mappingReferences[i][7] = i - 11;
}
private static void applyMappingReferencesToBoard() {
for(int i = 0; i < 100; i++) {
Square sq = boardSquares[i];
for(int j = 0; j < 8; j++) {
int newNeighborIndex = mappingReferences[locationToOccupantMapping[i]][j];
if(newNeighborIndex == -1) {
sq.assignNeighborInDirection(NullSquare.generateNullSquare(), j);
} else {
Square newNeighbor = boardSquares[occupantToLocationMapping[newNeighborIndex]];
sq.assignNeighborInDirection(newNeighbor, j);
}
}
}
}
}
| Centralized-Java/src/chess/engine/ChessBoardBuilder.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chess.engine;
/**
*
* @author Ryan J. Marcotte
*/
public class ChessBoardBuilder {
private static Square[] boardSquares;
private static int[][] mappingReferences = new int[100][8];
private static int[] locationToOccupantMapping = new int[100];
private final static int[] occupantToLocationMapping = {
64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 0, 1, 2, 3, 4, 5, 6, 7, 75,
76, 8, 9, 10, 11, 12, 13, 14, 15, 77,
78, 16, 17, 18, 19, 20, 21, 22, 23, 79,
80, 24, 25, 26, 27, 28, 29, 30, 31, 81,
82, 32, 33, 34, 35, 36, 37, 38, 39, 83,
84, 40, 41, 42, 43, 44, 45, 46, 47, 85,
86, 48, 49, 50, 51, 52, 53, 54, 55, 87,
88, 56, 57, 58, 59, 60, 61, 62, 63, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99
};
public static void main(String[] args) {
ChessBoard board = ChessBoard.generateChessBoard();
}
protected static void build(ChessBoard board) {
boardSquares = board.getAllSquares();
buildSquares();
assignMappingReferences();
remap();
}
private static void buildSquares() {
for(int i = 0; i < 100; i++) {
if(i < 64) {
boardSquares[i] = InteriorSquare.generateInteriorSquareAt(i);
} else {
boardSquares[i] = PerimeterSquare.generatePerimeterSquareAt(i);
}
}
}
private static void assignMappingReferences() {
mapLocationsToOccupants();
initializeMappingReferences();
assignNorthMappingReferences();
assignNorthEastMappingReferences();
assignEastMappingReferences();
assignSouthEastMappingReferences();
assignSouthMappingReferences();
assignSouthWestMappingReferences();
assignWestMappingReferences();
assignNorthWestMappingReferences();
}
private static void mapLocationsToOccupants() {
for(int i = 0; i < 100; i++) {
locationToOccupantMapping[occupantToLocationMapping[i]] = i;
}
}
private static void initializeMappingReferences() {
for(int i = 0; i < 100; i++) {
for(int j = 0; j < 8; j++) {
mappingReferences[i][j] = -1;
}
}
}
private static void assignNorthMappingReferences() {
for(int i = 10; i < 100; i++) {
mappingReferences[i][0] = i - 10;
}
}
private static void assignNorthEastMappingReferences() {
for(int i = 10; i < 100; i++) {
if(i % 10 != 9)
mappingReferences[i][1] = i - 9;
}
}
private static void assignEastMappingReferences() {
for(int i = 0; i < 100; i++) {
if(i % 10 != 9)
mappingReferences[i][2] = i + 1;
}
}
private static void assignSouthEastMappingReferences() {
for(int i = 0; i < 90; i++) {
if(i % 10 != 9)
mappingReferences[i][3] = i + 11;
}
}
private static void assignSouthMappingReferences() {
for(int i = 0; i < 90; i++) {
mappingReferences[i][4] = i + 10;
}
}
private static void assignSouthWestMappingReferences() {
for(int i = 0; i < 90; i++) {
if(i % 10 != 0)
mappingReferences[i][5] = i + 9;
}
}
private static void assignWestMappingReferences() {
for(int i = 0; i < 100; i++) {
if(i % 10 != 0)
mappingReferences[i][6] = i - 1;
}
}
private static void assignNorthWestMappingReferences() {
for(int i = 10; i < 100; i++) {
if(i % 10 != 0)
mappingReferences[i][7] = i - 11;
}
}
private static void remap() {
for(int i = 0; i < 100; i++) {
Square sq = boardSquares[i];
for(int j = 0; j < 8; j++) {
int newNeighborIndex = mappingReferences[locationToOccupantMapping[i]][j];
if(newNeighborIndex == -1) {
sq.assignNeighborInDirection(NullSquare.generateNullSquare(), j);
} else {
Square newNeighbor = boardSquares[occupantToLocationMapping[newNeighborIndex]];
sq.assignNeighborInDirection(newNeighbor, j);
}
}
}
}
}
| Updated comments, generally improved clarity | Centralized-Java/src/chess/engine/ChessBoardBuilder.java | Updated comments, generally improved clarity |
|
Java | apache-2.0 | c4fdfb57d336b1a0f1b27354c758c61c0a586942 | 0 | gradle/gradle,blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,lsmaira/gradle,lsmaira/gradle,robinverduijn/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,gstevey/gradle,lsmaira/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,lsmaira/gradle,gradle/gradle,lsmaira/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,gstevey/gradle,robinverduijn/gradle,gstevey/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,gstevey/gradle,gstevey/gradle,gradle/gradle,blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,gstevey/gradle,lsmaira/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,gstevey/gradle,blindpirate/gradle,gradle/gradle,lsmaira/gradle,blindpirate/gradle,robinverduijn/gradle | /*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.classloader;
import org.gradle.internal.reflect.JavaMethod;
import org.gradle.internal.reflect.JavaReflectionUtil;
import java.io.IOException;
import java.net.URL;
import java.util.*;
/**
* A ClassLoader which hides all non-system classes, packages and resources. Allows certain non-system packages and classes to be declared as visible. By default, only the Java system classes,
* packages and resources are visible.
*/
public class FilteringClassLoader extends ClassLoader implements ClassLoaderHierarchy {
private static final ClassLoader EXT_CLASS_LOADER;
private static final Set<String> SYSTEM_PACKAGES = new HashSet<String>();
private final Set<String> packageNames = new HashSet<String>();
private final Set<String> packagePrefixes = new HashSet<String>();
private final Set<String> resourcePrefixes = new HashSet<String>();
private final Set<String> resourceNames = new HashSet<String>();
private final Set<String> classNames = new HashSet<String>();
private final Set<String> disallowedClassNames = new HashSet<String>();
private final Set<String> disallowedPackagePrefixes = new HashSet<String>();
static {
EXT_CLASS_LOADER = ClassLoader.getSystemClassLoader().getParent();
JavaMethod<ClassLoader, Package[]> method = JavaReflectionUtil.method(ClassLoader.class, Package[].class, "getPackages");
Package[] systemPackages = method.invoke(EXT_CLASS_LOADER);
for (Package p : systemPackages) {
SYSTEM_PACKAGES.add(p.getName());
}
}
public FilteringClassLoader(ClassLoader parent) {
super(parent);
}
public FilteringClassLoader(ClassLoader parent, Spec spec) {
super(parent);
packageNames.addAll(spec.packageNames);
packagePrefixes.addAll(spec.packagePrefixes);
resourceNames.addAll(spec.resourceNames);
resourcePrefixes.addAll(spec.resourcePrefixes);
classNames.addAll(spec.classNames);
disallowedClassNames.addAll(spec.disallowedClassNames);
disallowedPackagePrefixes.addAll(spec.disallowedPackagePrefixes);
}
public void visit(ClassLoaderVisitor visitor) {
visitor.visitSpec(new Spec(classNames, packageNames, packagePrefixes, resourcePrefixes, resourceNames, disallowedClassNames, disallowedPackagePrefixes));
visitor.visitParent(getParent());
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
try {
return EXT_CLASS_LOADER.loadClass(name);
} catch (ClassNotFoundException ignore) {
// ignore
}
if (!classAllowed(name)) {
throw new ClassNotFoundException(name + " not found.");
}
Class<?> cl = super.loadClass(name, false);
if (resolve) {
resolveClass(cl);
}
return cl;
}
@Override
protected Package getPackage(String name) {
Package p = super.getPackage(name);
if (p == null || !allowed(p)) {
return null;
}
return p;
}
@Override
protected Package[] getPackages() {
List<Package> packages = new ArrayList<Package>();
for (Package p : super.getPackages()) {
if (allowed(p)) {
packages.add(p);
}
}
return packages.toArray(new Package[packages.size()]);
}
@Override
public URL getResource(String name) {
if (allowed(name)) {
return super.getResource(name);
}
return EXT_CLASS_LOADER.getResource(name);
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
if (allowed(name)) {
return super.getResources(name);
}
return EXT_CLASS_LOADER.getResources(name);
}
private boolean allowed(String resourceName) {
if (resourceNames.contains(resourceName)) {
return true;
}
for (String resourcePrefix : resourcePrefixes) {
if (resourceName.startsWith(resourcePrefix)) {
return true;
}
}
return false;
}
private boolean allowed(Package pkg) {
for (String packagePrefix : disallowedPackagePrefixes) {
if (pkg.getName().startsWith(packagePrefix)) {
return false;
}
}
if (SYSTEM_PACKAGES.contains(pkg.getName())) {
return true;
}
if (packageNames.contains(pkg.getName())) {
return true;
}
for (String packagePrefix : packagePrefixes) {
if (pkg.getName().startsWith(packagePrefix)) {
return true;
}
}
return false;
}
private boolean classAllowed(String className) {
if (disallowedClassNames.contains(className)) {
return false;
}
for (String packagePrefix : disallowedPackagePrefixes) {
if (className.startsWith(packagePrefix)) {
return false;
}
}
if (classNames.contains(className)) {
return true;
}
for (String packagePrefix : packagePrefixes) {
if (className.startsWith(packagePrefix)) {
return true;
}
}
return false;
}
/**
* Marks a package and all its sub-packages as visible. Also makes resources in those packages visible.
*
* @param packageName the package name
*/
public void allowPackage(String packageName) {
packageNames.add(packageName);
packagePrefixes.add(packageName + ".");
resourcePrefixes.add(packageName.replace('.', '/') + '/');
}
/**
* Marks a single class as visible.
*
* @param clazz the class
*/
public void allowClass(Class<?> clazz) {
classNames.add(clazz.getName());
}
/**
* Marks a single class as not visible.
*
* @param className the class name
*/
public void disallowClass(String className) {
disallowedClassNames.add(className);
}
/**
* Marks a package and all its sub-packages as not visible. Does not affect resources in those packages.
*
* @param packagePrefix the package prefix
*/
public void disallowPackage(String packagePrefix) {
disallowedPackagePrefixes.add(packagePrefix + ".");
}
/**
* Marks all resources with the given prefix as visible.
*
* @param resourcePrefix the resource prefix
*/
public void allowResources(String resourcePrefix) {
resourcePrefixes.add(resourcePrefix + "/");
}
/**
* Marks a single resource as visible.
*
* @param resourceName the resource name
*/
public void allowResource(String resourceName) {
resourceNames.add(resourceName);
}
public static class Spec extends ClassLoaderSpec {
final Set<String> packageNames;
final Set<String> packagePrefixes;
final Set<String> resourcePrefixes;
final Set<String> resourceNames;
final Set<String> classNames;
final Set<String> disallowedClassNames;
final Set<String> disallowedPackagePrefixes;
public Spec(Collection<String> classNames, Collection<String> packageNames, Collection<String> packagePrefixes, Collection<String> resourcePrefixes, Collection<String> resourceNames, Collection<String> disallowedClassNames, Collection<String> disallowedPackagePrefixes) {
this.classNames = new HashSet<String>(classNames);
this.packageNames = new HashSet<String>(packageNames);
this.packagePrefixes = new HashSet<String>(packagePrefixes);
this.resourcePrefixes = new HashSet<String>(resourcePrefixes);
this.resourceNames = new HashSet<String>(resourceNames);
this.disallowedClassNames = new HashSet<String>(disallowedClassNames);
this.disallowedPackagePrefixes = new HashSet<String>(disallowedPackagePrefixes);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != getClass()) {
return false;
}
Spec other = (Spec) obj;
return other.packageNames.equals(packageNames)
&& other.packagePrefixes.equals(packagePrefixes)
&& other.resourceNames.equals(resourceNames)
&& other.resourcePrefixes.equals(resourcePrefixes)
&& other.classNames.equals(classNames)
&& other.disallowedClassNames.equals(disallowedClassNames)
&& other.disallowedPackagePrefixes.equals(disallowedPackagePrefixes);
}
@Override
public int hashCode() {
return packageNames.hashCode()
^ packagePrefixes.hashCode()
^ resourceNames.hashCode()
^ resourcePrefixes.hashCode()
^ classNames.hashCode()
^ disallowedClassNames.hashCode()
^ disallowedPackagePrefixes.hashCode();
}
}
}
| subprojects/base-services/src/main/java/org/gradle/internal/classloader/FilteringClassLoader.java | /*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.classloader;
import org.gradle.internal.reflect.JavaMethod;
import org.gradle.internal.reflect.JavaReflectionUtil;
import java.io.IOException;
import java.net.URL;
import java.util.*;
/**
* A ClassLoader which hides all non-system classes, packages and resources. Allows certain non-system packages and classes to be declared as visible. By default, only the Java system classes,
* packages and resources are visible.
*/
public class FilteringClassLoader extends ClassLoader implements ClassLoaderHierarchy {
private static final ClassLoader EXT_CLASS_LOADER;
private static final Set<String> SYSTEM_PACKAGES = new HashSet<String>();
private final Set<String> packageNames = new HashSet<String>();
private final Set<String> packagePrefixes = new HashSet<String>();
private final Set<String> resourcePrefixes = new HashSet<String>();
private final Set<String> resourceNames = new HashSet<String>();
private final Set<String> classNames = new HashSet<String>();
private final Set<String> disallowedClassNames = new HashSet<String>();
private final Set<String> disallowedPackagePrefixes = new HashSet<String>();
static {
EXT_CLASS_LOADER = ClassLoader.getSystemClassLoader().getParent();
JavaMethod<ClassLoader, Package[]> method = JavaReflectionUtil.method(ClassLoader.class, Package[].class, "getPackages");
Package[] systemPackages = method.invoke(EXT_CLASS_LOADER);
for (Package p : systemPackages) {
SYSTEM_PACKAGES.add(p.getName());
}
}
public FilteringClassLoader(ClassLoader parent) {
super(parent);
}
public FilteringClassLoader(ClassLoader parent, Spec spec) {
super(parent);
packageNames.addAll(spec.packageNames);
packagePrefixes.addAll(spec.packagePrefixes);
resourceNames.addAll(spec.resourceNames);
resourcePrefixes.addAll(spec.resourcePrefixes);
classNames.addAll(spec.classNames);
disallowedClassNames.addAll(spec.disallowedClassNames);
disallowedPackagePrefixes.addAll(spec.disallowedPackagePrefixes);
}
public void visit(ClassLoaderVisitor visitor) {
visitor.visitSpec(new Spec(classNames, packageNames, packagePrefixes, resourcePrefixes, resourceNames, disallowedClassNames, disallowedPackagePrefixes));
visitor.visitParent(getParent());
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
try {
return EXT_CLASS_LOADER.loadClass(name);
} catch (ClassNotFoundException ignore) {
// ignore
}
if (!classAllowed(name)) {
throw new ClassNotFoundException(String.format("%s not found.", name));
}
Class<?> cl = super.loadClass(name, false);
if (resolve) {
resolveClass(cl);
}
return cl;
}
@Override
protected Package getPackage(String name) {
Package p = super.getPackage(name);
if (p == null || !allowed(p)) {
return null;
}
return p;
}
@Override
protected Package[] getPackages() {
List<Package> packages = new ArrayList<Package>();
for (Package p : super.getPackages()) {
if (allowed(p)) {
packages.add(p);
}
}
return packages.toArray(new Package[packages.size()]);
}
@Override
public URL getResource(String name) {
if (allowed(name)) {
return super.getResource(name);
}
return EXT_CLASS_LOADER.getResource(name);
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
if (allowed(name)) {
return super.getResources(name);
}
return EXT_CLASS_LOADER.getResources(name);
}
private boolean allowed(String resourceName) {
if (resourceNames.contains(resourceName)) {
return true;
}
for (String resourcePrefix : resourcePrefixes) {
if (resourceName.startsWith(resourcePrefix)) {
return true;
}
}
return false;
}
private boolean allowed(Package pkg) {
for (String packagePrefix : disallowedPackagePrefixes) {
if (pkg.getName().startsWith(packagePrefix)) {
return false;
}
}
if (SYSTEM_PACKAGES.contains(pkg.getName())) {
return true;
}
if (packageNames.contains(pkg.getName())) {
return true;
}
for (String packagePrefix : packagePrefixes) {
if (pkg.getName().startsWith(packagePrefix)) {
return true;
}
}
return false;
}
private boolean classAllowed(String className) {
if (disallowedClassNames.contains(className)) {
return false;
}
for (String packagePrefix : disallowedPackagePrefixes) {
if (className.startsWith(packagePrefix)) {
return false;
}
}
if (classNames.contains(className)) {
return true;
}
for (String packagePrefix : packagePrefixes) {
if (className.startsWith(packagePrefix)) {
return true;
}
}
return false;
}
/**
* Marks a package and all its sub-packages as visible. Also makes resources in those packages visible.
*
* @param packageName the package name
*/
public void allowPackage(String packageName) {
packageNames.add(packageName);
packagePrefixes.add(packageName + ".");
resourcePrefixes.add(packageName.replace('.', '/') + '/');
}
/**
* Marks a single class as visible.
*
* @param clazz the class
*/
public void allowClass(Class<?> clazz) {
classNames.add(clazz.getName());
}
/**
* Marks a single class as not visible.
*
* @param className the class name
*/
public void disallowClass(String className) {
disallowedClassNames.add(className);
}
/**
* Marks a package and all its sub-packages as not visible. Does not affect resources in those packages.
*
* @param packagePrefix the package prefix
*/
public void disallowPackage(String packagePrefix) {
disallowedPackagePrefixes.add(packagePrefix + ".");
}
/**
* Marks all resources with the given prefix as visible.
*
* @param resourcePrefix the resource prefix
*/
public void allowResources(String resourcePrefix) {
resourcePrefixes.add(resourcePrefix + "/");
}
/**
* Marks a single resource as visible.
*
* @param resourceName the resource name
*/
public void allowResource(String resourceName) {
resourceNames.add(resourceName);
}
public static class Spec extends ClassLoaderSpec {
final Set<String> packageNames;
final Set<String> packagePrefixes;
final Set<String> resourcePrefixes;
final Set<String> resourceNames;
final Set<String> classNames;
final Set<String> disallowedClassNames;
final Set<String> disallowedPackagePrefixes;
public Spec(Collection<String> classNames, Collection<String> packageNames, Collection<String> packagePrefixes, Collection<String> resourcePrefixes, Collection<String> resourceNames, Collection<String> disallowedClassNames, Collection<String> disallowedPackagePrefixes) {
this.classNames = new HashSet<String>(classNames);
this.packageNames = new HashSet<String>(packageNames);
this.packagePrefixes = new HashSet<String>(packagePrefixes);
this.resourcePrefixes = new HashSet<String>(resourcePrefixes);
this.resourceNames = new HashSet<String>(resourceNames);
this.disallowedClassNames = new HashSet<String>(disallowedClassNames);
this.disallowedPackagePrefixes = new HashSet<String>(disallowedPackagePrefixes);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != getClass()) {
return false;
}
Spec other = (Spec) obj;
return other.packageNames.equals(packageNames)
&& other.packagePrefixes.equals(packagePrefixes)
&& other.resourceNames.equals(resourceNames)
&& other.resourcePrefixes.equals(resourcePrefixes)
&& other.classNames.equals(classNames)
&& other.disallowedClassNames.equals(disallowedClassNames)
&& other.disallowedPackagePrefixes.equals(disallowedPackagePrefixes);
}
@Override
public int hashCode() {
return packageNames.hashCode()
^ packagePrefixes.hashCode()
^ resourceNames.hashCode()
^ resourcePrefixes.hashCode()
^ classNames.hashCode()
^ disallowedClassNames.hashCode()
^ disallowedPackagePrefixes.hashCode();
}
}
}
| Replaced String.format() with concatenation.
| subprojects/base-services/src/main/java/org/gradle/internal/classloader/FilteringClassLoader.java | Replaced String.format() with concatenation. |
|
Java | apache-2.0 | 6a79cd9044a9f2d8451b29b70ed2fd3728ef0193 | 0 | davidegiannella/jackrabbit-oak,davidegiannella/jackrabbit-oak,davidegiannella/jackrabbit-oak,davidegiannella/jackrabbit-oak,davidegiannella/jackrabbit-oak | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.document;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.CheckForNull;
import com.google.common.collect.Lists;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.DefaultEditor;
import org.apache.jackrabbit.oak.spi.commit.Editor;
import org.apache.jackrabbit.oak.spi.commit.EditorHook;
import org.apache.jackrabbit.oak.spi.commit.EditorProvider;
import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.jackrabbit.oak.spi.commit.CommitInfo.EMPTY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class ClusterConflictTest {
@Rule
public final DocumentMKBuilderProvider builderProvider = new DocumentMKBuilderProvider();
private static final Logger LOG = LoggerFactory.getLogger(ClusterConflictTest.class);
private DocumentNodeStore ns1;
private DocumentNodeStore ns2;
@Before
public void setUp() {
MemoryDocumentStore store = new MemoryDocumentStore();
ns1 = newDocumentNodeStore(store, 1);
ns2 = newDocumentNodeStore(store, 2);
}
private DocumentNodeStore newDocumentNodeStore(DocumentStore store, int clusterId) {
// use high async delay and run background ops manually
// asyncDelay set to zero prevents commits from suspending
return builderProvider.newBuilder()
.setAsyncDelay(60000)
.setDocumentStore(store)
.setLeaseCheck(false) // disabled for debugging purposes
.setClusterId(clusterId)
.getNodeStore();
}
@Test
public void suspendUntilVisible() throws Exception {
suspendUntilVisible(false);
}
@Test
public void suspendUntilVisibleWithBranch() throws Exception {
suspendUntilVisible(true);
}
private void suspendUntilVisible(boolean withBranch) throws Exception {
NodeBuilder b1 = ns1.getRoot().builder();
b1.child("counter").setProperty("value", 0);
merge(ns1, b1);
ns1.runBackgroundOperations();
ns2.runBackgroundOperations();
b1 = ns1.getRoot().builder();
b1.child("foo");
ns1.merge(b1, new TestHook(), EMPTY);
final List<Exception> exceptions = Lists.newArrayList();
final NodeBuilder b2 = ns2.getRoot().builder();
b2.child("bar");
if (withBranch) {
purge(b2);
}
b2.child("baz");
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
LOG.info("initiating merge");
ns2.merge(b2, new TestHook(), EMPTY);
LOG.info("merge succeeded");
} catch (CommitFailedException e) {
exceptions.add(e);
}
}
});
t.start();
// wait until t is suspended
for (int i = 0; i < 100; i++) {
if (ns2.commitQueue.numSuspendedThreads() > 0) {
break;
}
Thread.sleep(10);
}
assertEquals(1, ns2.commitQueue.numSuspendedThreads());
LOG.info("commit suspended");
ns1.runBackgroundOperations();
LOG.info("ran background ops on ns1");
ns2.runBackgroundOperations();
LOG.info("ran background ops on ns2");
assertEquals(0, ns2.commitQueue.numSuspendedThreads());
t.join(3000);
assertFalse("Commit did not succeed within 3 seconds", t.isAlive());
for (Exception e : exceptions) {
throw e;
}
}
// OAK-3859
@Ignore("OAK-3859")
@Test
public void mixedConflictAndCollision() throws Exception {
NodeBuilder b1 = ns1.getRoot().builder();
b1.child("test");
merge(ns1, b1);
ns1.runBackgroundOperations();
ns2.runBackgroundOperations();
AtomicLong counter = new AtomicLong();
final List<Exception> exceptions = Collections.synchronizedList(
new ArrayList<Exception>());
// the writers perform conflicting changes
List<Thread> writers = Lists.newArrayList();
writers.add(new Thread(new Writer(exceptions, ns1, counter)));
writers.add(new Thread(new Writer(exceptions, ns1, counter)));
for (Thread t : writers) {
t.start();
}
for (int i = 0; i < 10; i++) {
NodeBuilder b21 = ns2.getRoot().builder();
// this change does not conflict with changes on ns1 but
// will be considered a collision
b21.child("test").setProperty("q", 1);
merge(ns2, b21);
}
for (Thread t : writers) {
t.join(10000);
}
for (Exception e : exceptions) {
throw e;
}
}
private static class Writer implements Runnable {
private final List<Exception> exceptions;
private final NodeStore ns;
private final AtomicLong counter;
public Writer(List<Exception> exceptions,
NodeStore ns,
AtomicLong counter) {
this.exceptions = exceptions;
this.ns = ns;
this.counter = counter;
}
@Override
public void run() {
try {
for (int i = 0; i < 200; i++) {
NodeBuilder b = ns.getRoot().builder();
b.child("test").setProperty("p", counter.incrementAndGet());
merge(ns, b);
}
} catch (CommitFailedException e) {
e.printStackTrace();
exceptions.add(e);
}
}
}
private static class TestHook extends EditorHook {
TestHook() {
super(new EditorProvider() {
@CheckForNull
@Override
public Editor getRootEditor(NodeState before,
NodeState after,
NodeBuilder builder,
CommitInfo info)
throws CommitFailedException {
return new TestEditor(builder.child("counter"));
}
});
}
}
private static class TestEditor extends DefaultEditor {
private NodeBuilder counter;
TestEditor(NodeBuilder counter) {
this.counter = counter;
}
@Override
public Editor childNodeAdded(String name, NodeState after)
throws CommitFailedException {
counter.setProperty("value", counter.getProperty("value").getValue(Type.LONG) + 1);
return super.childNodeAdded(name, after);
}
}
private static NodeState merge(NodeStore store, NodeBuilder root)
throws CommitFailedException {
return store.merge(root, EmptyHook.INSTANCE, EMPTY);
}
private static void purge(NodeBuilder builder) {
((DocumentRootBuilder) builder).purge();
}
}
| oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/ClusterConflictTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.document;
import java.util.List;
import javax.annotation.CheckForNull;
import com.google.common.collect.Lists;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.DefaultEditor;
import org.apache.jackrabbit.oak.spi.commit.Editor;
import org.apache.jackrabbit.oak.spi.commit.EditorHook;
import org.apache.jackrabbit.oak.spi.commit.EditorProvider;
import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.jackrabbit.oak.spi.commit.CommitInfo.EMPTY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class ClusterConflictTest {
@Rule
public final DocumentMKBuilderProvider builderProvider = new DocumentMKBuilderProvider();
private static final Logger LOG = LoggerFactory.getLogger(ClusterConflictTest.class);
private DocumentNodeStore ns1;
private DocumentNodeStore ns2;
@Before
public void setUp() {
MemoryDocumentStore store = new MemoryDocumentStore();
ns1 = newDocumentNodeStore(store, 1);
ns2 = newDocumentNodeStore(store, 2);
}
private DocumentNodeStore newDocumentNodeStore(DocumentStore store, int clusterId) {
// use high async delay and run background ops manually
// asyncDelay set to zero prevents commits from suspending
return builderProvider.newBuilder()
.setAsyncDelay(60000)
.setDocumentStore(store)
.setLeaseCheck(false) // disabled for debugging purposes
.setClusterId(clusterId)
.getNodeStore();
}
@Test
public void suspendUntilVisible() throws Exception {
suspendUntilVisible(false);
}
@Test
public void suspendUntilVisibleWithBranch() throws Exception {
suspendUntilVisible(true);
}
private void suspendUntilVisible(boolean withBranch) throws Exception {
NodeBuilder b1 = ns1.getRoot().builder();
b1.child("counter").setProperty("value", 0);
merge(ns1, b1);
ns1.runBackgroundOperations();
ns2.runBackgroundOperations();
b1 = ns1.getRoot().builder();
b1.child("foo");
ns1.merge(b1, new TestHook(), EMPTY);
final List<Exception> exceptions = Lists.newArrayList();
final NodeBuilder b2 = ns2.getRoot().builder();
b2.child("bar");
if (withBranch) {
purge(b2);
}
b2.child("baz");
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
LOG.info("initiating merge");
ns2.merge(b2, new TestHook(), EMPTY);
LOG.info("merge succeeded");
} catch (CommitFailedException e) {
exceptions.add(e);
}
}
});
t.start();
// wait until t is suspended
for (int i = 0; i < 100; i++) {
if (ns2.commitQueue.numSuspendedThreads() > 0) {
break;
}
Thread.sleep(10);
}
assertEquals(1, ns2.commitQueue.numSuspendedThreads());
LOG.info("commit suspended");
ns1.runBackgroundOperations();
LOG.info("ran background ops on ns1");
ns2.runBackgroundOperations();
LOG.info("ran background ops on ns2");
assertEquals(0, ns2.commitQueue.numSuspendedThreads());
t.join(3000);
assertFalse("Commit did not succeed within 3 seconds", t.isAlive());
for (Exception e : exceptions) {
throw e;
}
}
private static class TestHook extends EditorHook {
TestHook() {
super(new EditorProvider() {
@CheckForNull
@Override
public Editor getRootEditor(NodeState before,
NodeState after,
NodeBuilder builder,
CommitInfo info)
throws CommitFailedException {
return new TestEditor(builder.child("counter"));
}
});
}
}
private static class TestEditor extends DefaultEditor {
private NodeBuilder counter;
TestEditor(NodeBuilder counter) {
this.counter = counter;
}
@Override
public Editor childNodeAdded(String name, NodeState after)
throws CommitFailedException {
counter.setProperty("value", counter.getProperty("value").getValue(Type.LONG) + 1);
return super.childNodeAdded(name, after);
}
}
private static NodeState merge(NodeStore store, NodeBuilder root)
throws CommitFailedException {
return store.merge(root, EmptyHook.INSTANCE, EMPTY);
}
private static void purge(NodeBuilder builder) {
((DocumentRootBuilder) builder).purge();
}
}
| OAK-3859: Suspended commit depends on non-conflicting change
Add (ignored) test
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1724260 13f79535-47bb-0310-9956-ffa450edef68
| oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/ClusterConflictTest.java | OAK-3859: Suspended commit depends on non-conflicting change |
|
Java | apache-2.0 | cbe715743312e70e6b072a2732399ab59186991c | 0 | playn/playn,tinkerstudent/playn,rachelharvey/playn,ruslansennov/playn2,rachelharvey/playn,longtaoge/playn,ruslansennov/playn2,playn/playn,tinkerstudent/playn,playn/playn,longtaoge/playn,thecocce/playn-1,thecocce/playn-1 | /**
* Copyright 2010 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package playn.core;
import playn.core.util.Callback;
/**
* An image.
*/
public interface Image {
/** Used with {@link #transform}. */
public interface BitmapTransformer {
}
/**
* This image's width in pixels.
*/
float width();
/**
* This image's height in pixels.
*/
float height();
/**
* Whether or not this image is ready to be used.
*/
boolean isReady();
/**
* Adds a callback to be notified when this image has loaded. If the image is
* already loaded, the callback will be notified immediately; otherwise on the main playn
* thread at a later time. The callback is discarded once the image is loaded.
*/
void addCallback(Callback<? super Image> callback);
/**
* A subregion of an image. See {@link Image#subImage}.
*/
public interface Region extends Image {
/**
* The x offset (in pixels) of this subimage into its parent image.
*/
float x();
/**
* The y offset (in pixels) of this subimage into its parent image.
*/
float y();
/**
* Updates this region's bounds in its parent image. If you need a rapidly changing region of
* an image, this can be more efficient than repeatedly creating new subimages as it creates no
* garbage to be collected.
*/
void setBounds(float x, float y, float width, float height);
/**
* The image of which this subimage is part.
*/
Image parent();
}
/**
* Returns an image that draws the specified sub-region of this image.
* @param x the x offset (in pixels) of the subimage.
* @param y the y offset (in pixels) of the subimage.
* @param width the width (in pixels) of the subimage.
* @param height the height (in pixels) of the subimage.
*/
Region subImage(float x, float y, float width, float height);
/**
* Creates a {@link Pattern} that can be used to use this image as a fill in a canvas.
*/
Pattern toPattern();
/**
* Extracts pixel data from a rectangular area of this image. This method may perform poorly, in
* particular on HTML and Flash platforms - avoid using this if possible.
*
* The returned pixel format is {@code (alpha << 24 | red << 16 | green << 8 | blue)}, where
* alpha, red, green and blue are the corresponding channel values, ranging from 0 to 255
* inclusive.
*
* Currently not implemented for iOS.
*
* @param startX x-coordinate of the upper left corner of the area.
* @param startY y-coordinate of the upper left corner of the area.
* @param width width of the area.
* @param height height of the area.
* @param rgbArray will be filled with the pixel data from the area
* @param offset fill start offset in rgbArray.
* @param scanSize number of pixels in a row in rgbArray.
*/
void getRgb(int startX, int startY, int width, int height, int[] rgbArray,
int offset, int scanSize);
/**
* Generates a new image from this image's bitmap, using a bitmap transformer created for the
* platform in use. See {@code JavaBitmapTransformer} and {@code IOSBitmapTransformer}. This does
* not work on sub-images.
*/
Image transform(BitmapTransformer xform);
/**
* Creates a texture for this image (if one does not already exist) and returns its OpenGL
* texture id. Returns 0 if the underlying image data is not yet ready or if this platform does
* not use OpenGL. If either {@code repeatX} or {@code repeatY} are true, the underlying image
* data will be scaled up into a power of two texture. The image will maintain one or both of an
* unscaled and scaled texture until a call to {@link #clearTexture} is made or until this image
* is garbage collected (at which time the textures are cleared).
*
* @param repeatX controls S texture wrapping parameter (repeat or clamp to edge).
* @param repeatY controls T texture wrapping parameter (repeat or clamp to edge).
*/
int ensureTexture(boolean repeatX, boolean repeatY);
/**
* Clears the GPU texture(s) associated with this image, on platforms implemented via OpenGL.
* Does nothing on non-OpenGL platforms. In general it is not necessary to call this method.
* Images added to {@link ImageLayer} instances automatically clear their texture when the image
* layer is removed from the scene graph. Textures are also cleared when the image is garbage
* collected. However, if you manually call {@link #ensureTexture}, or if you draw images to a
* {@link Surface}, you may wish to clear textures manually to avoid running out of GPU memory
* before garbage collection has a chance to run and clear the textures for you.
*/
void clearTexture();
}
| core/src/playn/core/Image.java | /**
* Copyright 2010 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package playn.core;
import playn.core.util.Callback;
/**
* An image.
*/
public interface Image {
/** Used with {@link #transform}. */
public interface BitmapTransformer {
}
/**
* This image's width in pixels.
*/
float width();
/**
* This image's height in pixels.
*/
float height();
/**
* Whether or not this image is ready to be used.
*/
boolean isReady();
/**
* Adds a callback to be notified when this image has loaded. If the image is
* already loaded, the callback will be notified immediately. The callback is
* discarded once the image is loaded.
*/
void addCallback(Callback<? super Image> callback);
/**
* A subregion of an image. See {@link Image#subImage}.
*/
public interface Region extends Image {
/**
* The x offset (in pixels) of this subimage into its parent image.
*/
float x();
/**
* The y offset (in pixels) of this subimage into its parent image.
*/
float y();
/**
* Updates this region's bounds in its parent image. If you need a rapidly changing region of
* an image, this can be more efficient than repeatedly creating new subimages as it creates no
* garbage to be collected.
*/
void setBounds(float x, float y, float width, float height);
/**
* The image of which this subimage is part.
*/
Image parent();
}
/**
* Returns an image that draws the specified sub-region of this image.
* @param x the x offset (in pixels) of the subimage.
* @param y the y offset (in pixels) of the subimage.
* @param width the width (in pixels) of the subimage.
* @param height the height (in pixels) of the subimage.
*/
Region subImage(float x, float y, float width, float height);
/**
* Creates a {@link Pattern} that can be used to use this image as a fill in a canvas.
*/
Pattern toPattern();
/**
* Extracts pixel data from a rectangular area of this image. This method may perform poorly, in
* particular on HTML and Flash platforms - avoid using this if possible.
*
* The returned pixel format is {@code (alpha << 24 | red << 16 | green << 8 | blue)}, where
* alpha, red, green and blue are the corresponding channel values, ranging from 0 to 255
* inclusive.
*
* Currently not implemented for iOS.
*
* @param startX x-coordinate of the upper left corner of the area.
* @param startY y-coordinate of the upper left corner of the area.
* @param width width of the area.
* @param height height of the area.
* @param rgbArray will be filled with the pixel data from the area
* @param offset fill start offset in rgbArray.
* @param scanSize number of pixels in a row in rgbArray.
*/
void getRgb(int startX, int startY, int width, int height, int[] rgbArray,
int offset, int scanSize);
/**
* Generates a new image from this image's bitmap, using a bitmap transformer created for the
* platform in use. See {@code JavaBitmapTransformer} and {@code IOSBitmapTransformer}. This does
* not work on sub-images.
*/
Image transform(BitmapTransformer xform);
/**
* Creates a texture for this image (if one does not already exist) and returns its OpenGL
* texture id. Returns 0 if the underlying image data is not yet ready or if this platform does
* not use OpenGL. If either {@code repeatX} or {@code repeatY} are true, the underlying image
* data will be scaled up into a power of two texture. The image will maintain one or both of an
* unscaled and scaled texture until a call to {@link #clearTexture} is made or until this image
* is garbage collected (at which time the textures are cleared).
*
* @param repeatX controls S texture wrapping parameter (repeat or clamp to edge).
* @param repeatY controls T texture wrapping parameter (repeat or clamp to edge).
*/
int ensureTexture(boolean repeatX, boolean repeatY);
/**
* Clears the GPU texture(s) associated with this image, on platforms implemented via OpenGL.
* Does nothing on non-OpenGL platforms. In general it is not necessary to call this method.
* Images added to {@link ImageLayer} instances automatically clear their texture when the image
* layer is removed from the scene graph. Textures are also cleared when the image is garbage
* collected. However, if you manually call {@link #ensureTexture}, or if you draw images to a
* {@link Surface}, you may wish to clear textures manually to avoid running out of GPU memory
* before garbage collection has a chance to run and clear the textures for you.
*/
void clearTexture();
}
| Include threading guarantee in docs
I wasn't sure if this was just standard practice and spent some time tracking it down on ios, so
figured I'd include it in the docs.
| core/src/playn/core/Image.java | Include threading guarantee in docs |
|
Java | apache-2.0 | bef0d7f09b61c3869e79aa143e62826b7710fed4 | 0 | dimagi/commcare,dimagi/commcare-core,dimagi/commcare-core,dimagi/commcare,dimagi/commcare,dimagi/commcare-core | package org.commcare.xml;
import org.commcare.data.xml.TransactionParser;
import org.commcare.modern.util.Pair;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.services.storage.IStorageUtilityIndexed;
import org.javarosa.core.services.storage.StorageFullException;
import org.javarosa.core.services.storage.StorageManager;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.xml.TreeElementParser;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.Vector;
/**
* The Fixture XML Parser is responsible for parsing incoming fixture data and
* storing it as a file with a pointer in a db.
*
* @author ctsims
*/
public class FixtureXmlParser extends TransactionParser<FormInstance> {
IStorageUtilityIndexed<FormInstance> storage;
private final boolean overwrite;
public FixtureXmlParser(KXmlParser parser) {
this(parser, true, null);
}
public FixtureXmlParser(KXmlParser parser, boolean overwrite,
IStorageUtilityIndexed<FormInstance> storage) {
super(parser);
this.overwrite = overwrite;
this.storage = storage;
}
@Override
public FormInstance parse() throws InvalidStructureException, IOException,
XmlPullParserException, UnfullfilledRequirementsException {
this.checkNode("fixture");
String fixtureId = parser.getAttributeValue(null, "id");
if (fixtureId == null) {
throw new InvalidStructureException("fixture is lacking id attribute", parser);
}
String userId = parser.getAttributeValue(null, "user_id");
TreeElement root;
if (!nextTagInBlock("fixture")) {
// fixture with no body; don't commit to storage
return null;
}
//TODO: We need to overwrite any matching records here.
root = new TreeElementParser(parser, 0, fixtureId).parse();
Pair<FormInstance, Boolean> instanceAndCommitStatus =
setupInstance(storage(), root, fixtureId, userId, overwrite);
if (instanceAndCommitStatus.second) {
commit(instanceAndCommitStatus.first);
}
return instanceAndCommitStatus.first;
}
private static Pair<FormInstance, Boolean> setupInstance(IStorageUtilityIndexed<FormInstance> storage,
TreeElement root, String fixtureId,
String userId, boolean overwrite) {
FormInstance instance = new FormInstance(root, fixtureId);
//This is a terrible hack and clayton should feeel terrible about it
if (userId != null) {
instance.schema = userId;
}
//If we're using storage, deal properly
if (storage != null) {
int recordId = -1;
Vector<Integer> matchingFixtures = storage.getIDsForValue(FormInstance.META_ID, fixtureId);
if (matchingFixtures.size() > 0) {
//find all fixtures with the same user
Vector<Integer> matchingUsers = storage.getIDsForValue(FormInstance.META_XMLNS, ExtUtil.emptyIfNull(userId));
for (Integer i : matchingFixtures) {
if (matchingUsers.indexOf(i) != -1) {
recordId = i;
}
}
}
if (recordId != -1) {
if (!overwrite) {
//parse it out, but don't write anything to memory if one already exists
return Pair.create(instance, false);
}
instance.setID(recordId);
}
}
return Pair.create(instance, true);
}
@Override
protected void commit(FormInstance parsed) throws IOException {
try {
storage().write(parsed);
} catch (StorageFullException e) {
e.printStackTrace();
throw new IOException("Storage full while writing case!");
}
}
public IStorageUtilityIndexed<FormInstance> storage() {
if (storage == null) {
storage = (IStorageUtilityIndexed)StorageManager.getStorage(FormInstance.STORAGE_KEY);
}
return storage;
}
}
| src/main/java/org/commcare/xml/FixtureXmlParser.java | package org.commcare.xml;
import org.commcare.data.xml.TransactionParser;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.services.storage.IStorageUtilityIndexed;
import org.javarosa.core.services.storage.StorageFullException;
import org.javarosa.core.services.storage.StorageManager;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.xml.TreeElementParser;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.Vector;
/**
* The Fixture XML Parser is responsible for parsing incoming fixture data and
* storing it as a file with a pointer in a db.
*
* @author ctsims
*/
public class FixtureXmlParser extends TransactionParser<FormInstance> {
IStorageUtilityIndexed<FormInstance> storage;
private final boolean overwrite;
public FixtureXmlParser(KXmlParser parser) {
this(parser, true, null);
}
public FixtureXmlParser(KXmlParser parser, boolean overwrite,
IStorageUtilityIndexed<FormInstance> storage) {
super(parser);
this.overwrite = overwrite;
this.storage = storage;
}
@Override
public FormInstance parse() throws InvalidStructureException, IOException,
XmlPullParserException, UnfullfilledRequirementsException {
this.checkNode("fixture");
String fixtureId = parser.getAttributeValue(null, "id");
if (fixtureId == null) {
throw new InvalidStructureException("fixture is lacking id attribute", parser);
}
String userId = parser.getAttributeValue(null, "user_id");
TreeElement root;
if (!nextTagInBlock("fixture")) {
// fixture with no body; don't commit to storage
return null;
}
//TODO: We need to overwrite any matching records here.
root = new TreeElementParser(parser, 0, fixtureId).parse();
FormInstance instance = new FormInstance(root, fixtureId);
//This is a terrible hack and clayton should feeel terrible about it
if (userId != null) {
instance.schema = userId;
}
//If we're using storage, deal properly
if (storage() != null) {
int recordId = -1;
Vector<Integer> matchingFixtures = storage().getIDsForValue(FormInstance.META_ID, fixtureId);
if (matchingFixtures.size() > 0) {
//find all fixtures with the same user
Vector<Integer> matchingUsers = storage().getIDsForValue(FormInstance.META_XMLNS, ExtUtil.emptyIfNull(userId));
for (Integer i : matchingFixtures) {
if (matchingUsers.indexOf(i) != -1) {
recordId = i;
}
}
}
if (recordId != -1) {
if (!overwrite) {
//parse it out, but don't write anything to memory if one already exists
return instance;
}
instance.setID(recordId);
}
}
commit(instance);
return instance;
}
@Override
protected void commit(FormInstance parsed) throws IOException {
try {
storage().write(parsed);
} catch (StorageFullException e) {
e.printStackTrace();
throw new IOException("Storage full while writing case!");
}
}
public IStorageUtilityIndexed<FormInstance> storage() {
if (storage == null) {
storage = (IStorageUtilityIndexed)StorageManager.getStorage(FormInstance.STORAGE_KEY);
}
return storage;
}
}
| move parser's instance setup code into helper
| src/main/java/org/commcare/xml/FixtureXmlParser.java | move parser's instance setup code into helper |
|
Java | bsd-2-clause | 10a1babd90f9fbb19a9f2fa62ffc6cf47151ee22 | 0 | KronosDesign/runelite,abelbriggs1/runelite,abelbriggs1/runelite,KronosDesign/runelite,l2-/runelite,Sethtroll/runelite,l2-/runelite,runelite/runelite,runelite/runelite,abelbriggs1/runelite,Sethtroll/runelite,runelite/runelite | /*
* Copyright (c) 2017. l2-
* Copyright (c) 2017, Adam <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.chatcommands;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Provides;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.ChatMessageType;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.ItemComposition;
import net.runelite.api.MessageNode;
import net.runelite.api.events.SetMessage;
import net.runelite.api.vars.AccountType;
import net.runelite.client.chat.ChatColorType;
import net.runelite.client.chat.ChatMessageBuilder;
import net.runelite.client.chat.ChatMessageManager;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.game.ItemManager;
import net.runelite.client.input.KeyManager;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.util.StackFormatter;
import net.runelite.http.api.hiscore.HiscoreClient;
import net.runelite.http.api.hiscore.HiscoreEndpoint;
import net.runelite.http.api.hiscore.HiscoreResult;
import net.runelite.http.api.hiscore.HiscoreSkill;
import net.runelite.http.api.hiscore.SingleHiscoreSkillResult;
import net.runelite.http.api.hiscore.Skill;
import net.runelite.http.api.item.Item;
import net.runelite.http.api.item.ItemPrice;
import net.runelite.http.api.item.SearchResult;
@PluginDescriptor(
name = "Chat Commands"
)
@Slf4j
public class ChatCommandsPlugin extends Plugin
{
private static final float HIGH_ALCHEMY_CONSTANT = 0.6f;
private final HiscoreClient hiscoreClient = new HiscoreClient();
@Inject
private Client client;
@Inject
private ChatCommandsConfig config;
@Inject
private ItemManager itemManager;
@Inject
private ChatMessageManager chatMessageManager;
@Inject
private ScheduledExecutorService executor;
@Inject
private KeyManager keyManager;
@Inject
private ChatKeyboardListener chatKeyboardListener;
@Override
public void startUp()
{
keyManager.registerKeyListener(chatKeyboardListener);
}
@Override
public void shutDown()
{
keyManager.unregisterKeyListener(chatKeyboardListener);
}
@Provides
ChatCommandsConfig provideConfig(ConfigManager configManager)
{
return configManager.getConfig(ChatCommandsConfig.class);
}
/**
* Checks if the chat message is a command.
*
* @param setMessage The chat message.
*/
@Subscribe
public void onSetMessage(SetMessage setMessage)
{
if (client.getGameState() != GameState.LOGGED_IN)
{
return;
}
switch (setMessage.getType())
{
case PUBLIC:
case CLANCHAT:
case PRIVATE_MESSAGE_RECEIVED:
case PRIVATE_MESSAGE_SENT:
break;
default:
return;
}
String message = setMessage.getValue();
MessageNode messageNode = setMessage.getMessageNode();
// clear RuneLite formatted message as the message node is
// being reused
messageNode.setRuneLiteFormatMessage(null);
if (config.lvl() && message.toLowerCase().equals("!total"))
{
log.debug("Running total level lookup");
executor.submit(() -> playerSkillLookup(setMessage.getType(), setMessage, "total"));
}
else if (config.price() && message.toLowerCase().startsWith("!price") && message.length() > 7)
{
String search = message.substring(7);
log.debug("Running price lookup for {}", search);
executor.submit(() -> itemPriceLookup(setMessage.getMessageNode(), search));
}
else if (config.lvl() && message.toLowerCase().startsWith("!lvl") && message.length() > 5)
{
String search = message.substring(5);
log.debug("Running level lookup for {}", search);
executor.submit(() -> playerSkillLookup(setMessage.getType(), setMessage, search));
}
else if (config.clue() && message.toLowerCase().equals("!clues"))
{
log.debug("Running lookup for overall clues");
executor.submit(() -> playerClueLookup(setMessage.getType(), setMessage, "total"));
}
else if (config.clue() && message.toLowerCase().startsWith("!clues") && message.length() > 7)
{
String search = message.substring(7);
log.debug("Running clue lookup for {}", search);
executor.submit(() -> playerClueLookup(setMessage.getType(), setMessage, search));
}
}
/**
* Looks up the item price and changes the original message to the
* response.
*
* @param messageNode The chat message containing the command.
* @param search The item given with the command.
*/
private void itemPriceLookup(MessageNode messageNode, String search)
{
SearchResult result;
try
{
result = itemManager.searchForItem(search);
}
catch (ExecutionException ex)
{
log.warn("Unable to search for item {}", search, ex);
return;
}
if (result != null && !result.getItems().isEmpty())
{
Item item = retrieveFromList(result.getItems(), search);
if (item == null)
{
log.debug("Unable to find item {} in result {}", search, result);
return;
}
int itemId = item.getId();
ItemPrice itemPrice = itemManager.getItemPrice(itemId);
final ChatMessageBuilder builder = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Price of ")
.append(ChatColorType.HIGHLIGHT)
.append(item.getName())
.append(ChatColorType.NORMAL)
.append(": GE average ")
.append(ChatColorType.HIGHLIGHT)
.append(StackFormatter.formatNumber(itemPrice.getPrice()));
ItemComposition itemComposition = itemManager.getItemComposition(itemId);
if (itemComposition != null)
{
int alchPrice = Math.round(itemComposition.getPrice() * HIGH_ALCHEMY_CONSTANT);
builder
.append(ChatColorType.NORMAL)
.append(" HA value ")
.append(ChatColorType.HIGHLIGHT)
.append(StackFormatter.formatNumber(alchPrice));
}
String response = builder.build();
log.debug("Setting response {}", response);
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
}
/**
* Looks up the player skill and changes the original message to the
* response.
*
* @param setMessage The chat message containing the command.
* @param search The item given with the command.
*/
private void playerSkillLookup(ChatMessageType type, SetMessage setMessage, String search)
{
search = SkillAbbreviations.getFullName(search);
final String player;
final HiscoreEndpoint ironmanStatus;
if (type.equals(ChatMessageType.PRIVATE_MESSAGE_SENT))
{
player = client.getLocalPlayer().getName();
ironmanStatus = getHiscoreEndpointType();
}
else
{
player = sanitize(setMessage.getName());
if (player.equals(client.getLocalPlayer().getName()))
{
// Get ironman status from for the local player
ironmanStatus = getHiscoreEndpointType();
}
else
{
// Get ironman status from their icon in chat
ironmanStatus = getHiscoreEndpointByName(setMessage.getName());
}
}
final HiscoreSkill skill;
try
{
skill = HiscoreSkill.valueOf(search.toUpperCase());
}
catch (IllegalArgumentException i)
{
return;
}
try
{
SingleHiscoreSkillResult result = hiscoreClient.lookup(player, skill, ironmanStatus);
Skill hiscoreSkill = result.getSkill();
String response = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Level ")
.append(ChatColorType.HIGHLIGHT)
.append(skill.getName()).append(": ").append(String.valueOf(hiscoreSkill.getLevel()))
.append(ChatColorType.NORMAL)
.append(" Experience: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", hiscoreSkill.getExperience()))
.append(ChatColorType.NORMAL)
.append(" Rank: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", hiscoreSkill.getRank()))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = setMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
catch (IOException ex)
{
log.warn("unable to look up skill {} for {}", skill, search, ex);
}
}
/**
* Looks up the quantities of clues completed
* for the requested clue-level (no arg if requesting total)
* easy, medium, hard, elite, master
*/
private void playerClueLookup(ChatMessageType type, SetMessage setMessage, String search)
{
String player;
if (type.equals(ChatMessageType.PRIVATE_MESSAGE_SENT))
{
player = client.getLocalPlayer().getName();
}
else
{
player = sanitize(setMessage.getName());
}
try
{
Skill hiscoreSkill;
HiscoreResult result = hiscoreClient.lookup(player);
String level = search.toLowerCase();
switch (level)
{
case "easy":
hiscoreSkill = result.getClueScrollEasy();
break;
case "medium":
hiscoreSkill = result.getClueScrollMedium();
break;
case "hard":
hiscoreSkill = result.getClueScrollHard();
break;
case "elite":
hiscoreSkill = result.getClueScrollElite();
break;
case "master":
hiscoreSkill = result.getClueScrollMaster();
break;
case "total":
hiscoreSkill = result.getClueScrollAll();
break;
default:
return;
}
int quantity = hiscoreSkill.getLevel();
int rank = hiscoreSkill.getRank();
if (quantity == -1)
{
return;
}
ChatMessageBuilder chatMessageBuilder = new ChatMessageBuilder()
.append("Clue scroll (" + level + ")").append(": ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(quantity));
if (rank != -1)
{
chatMessageBuilder.append(ChatColorType.NORMAL)
.append(" Rank: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", rank));
}
String response = chatMessageBuilder.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = setMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
catch (IOException ex)
{
log.warn("error looking up clues", ex);
}
}
/**
* Compares the names of the items in the list with the original input.
* Returns the item if its name is equal to the original input or null
* if it can't find the item.
*
* @param items List of items.
* @param originalInput String with the original input.
* @return Item which has a name equal to the original input.
*/
private Item retrieveFromList(List<Item> items, String originalInput)
{
for (Item item : items)
{
if (item.getName().toLowerCase().equals(originalInput.toLowerCase()))
{
return item;
}
}
return null;
}
/**
* Cleans the ironman status icon from playername string if present and
* corrects spaces.
*
* @param lookup Playername to lookup.
* @return Cleaned playername.
*/
private static String sanitize(String lookup)
{
String cleaned = lookup.contains("<img") ? lookup.substring(lookup.lastIndexOf('>') + 1) : lookup;
return cleaned.replace('\u00A0', ' ');
}
/**
* Looks up the ironman status of the local player. Does NOT work on other players.
* @return hiscore endpoint
*/
private HiscoreEndpoint getHiscoreEndpointType()
{
return toEndPoint(client.getAccountType());
}
/**
* Returns the ironman status based on the symbol in the name of the player.
* @param name player name
* @return hiscore endpoint
*/
private static HiscoreEndpoint getHiscoreEndpointByName(final String name)
{
if (name.contains("<img=2>"))
{
return toEndPoint(AccountType.IRONMAN);
}
else if (name.contains("<img=3>"))
{
return toEndPoint(AccountType.ULTIMATE_IRONMAN);
}
else if (name.contains("<img=10>"))
{
return toEndPoint(AccountType.HARDCORE_IRONMAN);
}
else
{
return toEndPoint(AccountType.NORMAL);
}
}
/**
* Converts account type to hiscore endpoint
* @param accountType account type
* @return hiscore endpoint
*/
private static HiscoreEndpoint toEndPoint(final AccountType accountType)
{
switch (accountType)
{
case IRONMAN:
return HiscoreEndpoint.IRONMAN;
case ULTIMATE_IRONMAN:
return HiscoreEndpoint.ULTIMATE_IRONMAN;
case HARDCORE_IRONMAN:
return HiscoreEndpoint.HARDCORE_IRONMAN;
default:
return HiscoreEndpoint.NORMAL;
}
}
}
| runelite-client/src/main/java/net/runelite/client/plugins/chatcommands/ChatCommandsPlugin.java | /*
* Copyright (c) 2017. l2-
* Copyright (c) 2017, Adam <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.chatcommands;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Provides;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.AccountType;
import net.runelite.api.ChatMessageType;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.ItemComposition;
import net.runelite.api.MessageNode;
import net.runelite.api.Varbits;
import net.runelite.api.events.SetMessage;
import net.runelite.client.chat.ChatColorType;
import net.runelite.client.chat.ChatMessageBuilder;
import net.runelite.client.chat.ChatMessageManager;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.game.ItemManager;
import net.runelite.client.input.KeyManager;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.util.StackFormatter;
import net.runelite.http.api.hiscore.HiscoreClient;
import net.runelite.http.api.hiscore.HiscoreResult;
import net.runelite.http.api.hiscore.HiscoreEndpoint;
import net.runelite.http.api.hiscore.HiscoreSkill;
import net.runelite.http.api.hiscore.SingleHiscoreSkillResult;
import net.runelite.http.api.hiscore.Skill;
import net.runelite.http.api.item.Item;
import net.runelite.http.api.item.ItemPrice;
import net.runelite.http.api.item.SearchResult;
@PluginDescriptor(
name = "Chat Commands"
)
@Slf4j
public class ChatCommandsPlugin extends Plugin
{
private static final float HIGH_ALCHEMY_CONSTANT = 0.6f;
private final HiscoreClient hiscoreClient = new HiscoreClient();
@Inject
private Client client;
@Inject
private ChatCommandsConfig config;
@Inject
private ItemManager itemManager;
@Inject
private ChatMessageManager chatMessageManager;
@Inject
private ScheduledExecutorService executor;
@Inject
private KeyManager keyManager;
@Inject
private ChatKeyboardListener chatKeyboardListener;
@Override
public void startUp()
{
keyManager.registerKeyListener(chatKeyboardListener);
}
@Override
public void shutDown()
{
keyManager.unregisterKeyListener(chatKeyboardListener);
}
@Provides
ChatCommandsConfig provideConfig(ConfigManager configManager)
{
return configManager.getConfig(ChatCommandsConfig.class);
}
/**
* Checks if the chat message is a command.
*
* @param setMessage The chat message.
*/
@Subscribe
public void onSetMessage(SetMessage setMessage)
{
if (client.getGameState() != GameState.LOGGED_IN)
{
return;
}
switch (setMessage.getType())
{
case PUBLIC:
case CLANCHAT:
case PRIVATE_MESSAGE_RECEIVED:
case PRIVATE_MESSAGE_SENT:
break;
default:
return;
}
String message = setMessage.getValue();
MessageNode messageNode = setMessage.getMessageNode();
// clear RuneLite formatted message as the message node is
// being reused
messageNode.setRuneLiteFormatMessage(null);
if (config.lvl() && message.toLowerCase().equals("!total"))
{
log.debug("Running total level lookup");
executor.submit(() -> playerSkillLookup(setMessage.getType(), setMessage, "total"));
}
else if (config.price() && message.toLowerCase().startsWith("!price") && message.length() > 7)
{
String search = message.substring(7);
log.debug("Running price lookup for {}", search);
executor.submit(() -> itemPriceLookup(setMessage.getMessageNode(), search));
}
else if (config.lvl() && message.toLowerCase().startsWith("!lvl") && message.length() > 5)
{
String search = message.substring(5);
log.debug("Running level lookup for {}", search);
executor.submit(() -> playerSkillLookup(setMessage.getType(), setMessage, search));
}
else if (config.clue() && message.toLowerCase().equals("!clues"))
{
log.debug("Running lookup for overall clues");
executor.submit(() -> playerClueLookup(setMessage.getType(), setMessage, "total"));
}
else if (config.clue() && message.toLowerCase().startsWith("!clues") && message.length() > 7)
{
String search = message.substring(7);
log.debug("Running clue lookup for {}", search);
executor.submit(() -> playerClueLookup(setMessage.getType(), setMessage, search));
}
}
/**
* Looks up the item price and changes the original message to the
* response.
*
* @param messageNode The chat message containing the command.
* @param search The item given with the command.
*/
private void itemPriceLookup(MessageNode messageNode, String search)
{
SearchResult result;
try
{
result = itemManager.searchForItem(search);
}
catch (ExecutionException ex)
{
log.warn("Unable to search for item {}", search, ex);
return;
}
if (result != null && !result.getItems().isEmpty())
{
Item item = retrieveFromList(result.getItems(), search);
if (item == null)
{
log.debug("Unable to find item {} in result {}", search, result);
return;
}
int itemId = item.getId();
ItemPrice itemPrice = itemManager.getItemPrice(itemId);
final ChatMessageBuilder builder = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Price of ")
.append(ChatColorType.HIGHLIGHT)
.append(item.getName())
.append(ChatColorType.NORMAL)
.append(": GE average ")
.append(ChatColorType.HIGHLIGHT)
.append(StackFormatter.formatNumber(itemPrice.getPrice()));
ItemComposition itemComposition = itemManager.getItemComposition(itemId);
if (itemComposition != null)
{
int alchPrice = Math.round(itemComposition.getPrice() * HIGH_ALCHEMY_CONSTANT);
builder
.append(ChatColorType.NORMAL)
.append(" HA value ")
.append(ChatColorType.HIGHLIGHT)
.append(StackFormatter.formatNumber(alchPrice));
}
String response = builder.build();
log.debug("Setting response {}", response);
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
}
/**
* Looks up the player skill and changes the original message to the
* response.
*
* @param setMessage The chat message containing the command.
* @param search The item given with the command.
*/
private void playerSkillLookup(ChatMessageType type, SetMessage setMessage, String search)
{
search = SkillAbbreviations.getFullName(search);
final String player;
final HiscoreEndpoint ironmanStatus;
if (type.equals(ChatMessageType.PRIVATE_MESSAGE_SENT))
{
player = client.getLocalPlayer().getName();
ironmanStatus = getIronmanStatusByVarbit();
}
else
{
player = sanitize(setMessage.getName());
if (player.equals(client.getLocalPlayer().getName()))
{
// Get ironman btw status from varbit
ironmanStatus = getIronmanStatusByVarbit();
}
else
{
// Get ironman btw status from their icon in chat
ironmanStatus = getIronmanStatusByName(setMessage.getName());
}
}
final HiscoreSkill skill;
try
{
skill = HiscoreSkill.valueOf(search.toUpperCase());
}
catch (IllegalArgumentException i)
{
return;
}
try
{
SingleHiscoreSkillResult result = hiscoreClient.lookup(player, skill, ironmanStatus);
Skill hiscoreSkill = result.getSkill();
String response = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Level ")
.append(ChatColorType.HIGHLIGHT)
.append(skill.getName()).append(": ").append(String.valueOf(hiscoreSkill.getLevel()))
.append(ChatColorType.NORMAL)
.append(" Experience: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", hiscoreSkill.getExperience()))
.append(ChatColorType.NORMAL)
.append(" Rank: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", hiscoreSkill.getRank()))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = setMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
catch (IOException ex)
{
log.warn("unable to look up skill {} for {}", skill, search, ex);
}
}
/**
* Looks up the quantities of clues completed
* for the requested clue-level (no arg if requesting total)
* easy, medium, hard, elite, master
*/
private void playerClueLookup(ChatMessageType type, SetMessage setMessage, String search)
{
String player;
if (type.equals(ChatMessageType.PRIVATE_MESSAGE_SENT))
{
player = client.getLocalPlayer().getName();
}
else
{
player = sanitize(setMessage.getName());
}
try
{
Skill hiscoreSkill;
HiscoreResult result = hiscoreClient.lookup(player);
String level = search.toLowerCase();
switch (level)
{
case "easy":
hiscoreSkill = result.getClueScrollEasy();
break;
case "medium":
hiscoreSkill = result.getClueScrollMedium();
break;
case "hard":
hiscoreSkill = result.getClueScrollHard();
break;
case "elite":
hiscoreSkill = result.getClueScrollElite();
break;
case "master":
hiscoreSkill = result.getClueScrollMaster();
break;
case "total":
hiscoreSkill = result.getClueScrollAll();
break;
default:
return;
}
int quantity = hiscoreSkill.getLevel();
int rank = hiscoreSkill.getRank();
if (quantity == -1)
{
return;
}
ChatMessageBuilder chatMessageBuilder = new ChatMessageBuilder()
.append("Clue scroll (" + level + ")").append(": ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(quantity));
if (rank != -1)
{
chatMessageBuilder.append(ChatColorType.NORMAL)
.append(" Rank: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", rank));
}
String response = chatMessageBuilder.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = setMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
catch (IOException ex)
{
log.warn("error looking up clues", ex);
}
}
/**
* Compares the names of the items in the list with the original input.
* Returns the item if its name is equal to the original input or null
* if it can't find the item.
*
* @param items List of items.
* @param originalInput String with the original input.
* @return Item which has a name equal to the original input.
*/
private Item retrieveFromList(List<Item> items, String originalInput)
{
for (Item item : items)
{
if (item.getName().toLowerCase().equals(originalInput.toLowerCase()))
{
return item;
}
}
return null;
}
/**
* Cleans the ironman status icon from playername string if present and
* corrects spaces.
*
* @param lookup Playername to lookup.
* @return Cleaned playername.
*/
private static String sanitize(String lookup)
{
String cleaned = lookup.contains("<img") ? lookup.substring(lookup.lastIndexOf('>') + 1) : lookup;
return cleaned.replace('\u00A0', ' ');
}
/**
* Looks up the ironman status of the local player. Does NOT work on other players.
* @return hiscore endpoint
*/
private HiscoreEndpoint getIronmanStatusByVarbit()
{
return toEndPoint(AccountType.fromVarbit(client.getVarbitValue(client.getVarps(), Varbits.IRONMAN_STATUS.getId())));
}
/**
* Returns the ironman status based on the symbol in the name of the player.
* @param name player name
* @return hiscore endpoint
*/
private static HiscoreEndpoint getIronmanStatusByName(final String name)
{
return toEndPoint(AccountType.fromName(name));
}
/**
* Converts account type to hiscore endpoint
* @param accountType account type
* @return hiscore endpoint
*/
private static HiscoreEndpoint toEndPoint(final AccountType accountType)
{
switch (accountType)
{
case IRONMAN:
return HiscoreEndpoint.IRONMAN;
case ULTIMATE_IRONMAN:
return HiscoreEndpoint.ULTIMATE_IRONMAN;
case HARDCORE_IRONMAN:
return HiscoreEndpoint.HARDCORE_IRONMAN;
default:
return HiscoreEndpoint.NORMAL;
}
}
}
| chat commands: fix to use exiting accounttype api
| runelite-client/src/main/java/net/runelite/client/plugins/chatcommands/ChatCommandsPlugin.java | chat commands: fix to use exiting accounttype api |
|
Java | bsd-3-clause | eea08b9abe793fb61ddd8ae8d21d4cde1efd915b | 0 | NCIP/nci-term-browser,NCIP/nci-term-browser,NCIP/nci-term-browser,NCIP/nci-term-browser | package gov.nih.nci.evs.browser.utils;
/*
* Copyright: (c) 2004-2009 Mayo Foundation for Medical Education and
* Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the
* triple-shield Mayo logo are trademarks and service marks of MFMER.
*
* Except as contained in the copyright notice above, or as used to identify
* MFMER as the author of this software, the trade names, trademarks, service
* marks, or product names of the copyright holder shall not be used in
* advertising, promotion or otherwise in connection with this software without
* prior written authorization of the copyright holder.
*
* Licensed under the Eclipse Public License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
*/
/**
* @author EVS Team
* @version 1.0
*
* Note: This class is created based on Mayo's BuildTreForCode.java sample code
*
* Modification history
* Initial modification [email protected]
*
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import java.io.Serializable;
import org.LexGrid.LexBIG.DataModel.Collections.AssociatedConceptList;
import org.LexGrid.LexBIG.DataModel.Collections.AssociationList;
import org.LexGrid.LexBIG.DataModel.Collections.LocalNameList;
import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept;
import org.LexGrid.LexBIG.DataModel.Core.Association;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.DataModel.Core.ConceptReference;
import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference;
import org.LexGrid.LexBIG.Exceptions.LBException;
import org.LexGrid.LexBIG.Exceptions.LBResourceUnavailableException;
import org.LexGrid.LexBIG.Extensions.Generic.LexBIGServiceConvenienceMethods;
import org.LexGrid.LexBIG.Extensions.Generic.LexBIGServiceConvenienceMethods.HierarchyPathResolveOption;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeGraph;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet;
import org.LexGrid.LexBIG.LexBIGService.LexBIGService;
import org.LexGrid.LexBIG.Utility.Constructors;
import org.LexGrid.codingSchemes.CodingScheme;
import org.LexGrid.commonTypes.EntityDescription;
import org.LexGrid.naming.SupportedHierarchy;
import org.LexGrid.naming.Mappings;
import org.LexGrid.LexBIG.DataModel.Collections.ConceptReferenceList;
import org.LexGrid.concepts.Concept;
import org.LexGrid.LexBIG.DataModel.Core.NameAndValue;
import org.LexGrid.LexBIG.DataModel.Collections.NameAndValueList;
import org.LexGrid.LexBIG.Extensions.Generic.LexBIGServiceConvenienceMethods;
//import static gov.nih.nci.evs.browser.common.Constants.*;
/**
* Attempts to provide a tree, based on a focus code, that includes the
* following information:
* <pre>
* - All paths from the hierarchy root to one or more focus codes.
* - Immediate children of every node in path to root
* - Indicator to show whether any unexpanded node can be further expanded
* </pre>
*
* This example accepts two parameters...
* The first parameter is required, and must contain at least one code
* in a comma-delimited list. A tree is produced for each code. Time to
* produce the tree for each code is printed in milliseconds. In order
* to factor out costs of startup and shutdown, resolving multiple
* codes may offer a better overall estimate performance.
*
* The second parameter is optional, and can indicate a hierarchy ID to
* navigate when resolving child nodes. If not provided, "is_a" is
* assumed.
*/
public class TreeUtils {
static LocalNameList noopList_ = Constructors.createLocalNameList("_noop_");
public TreeUtils() {
}
public HashMap getTreePathData(String scheme, String version,
String hierarchyID, String code) throws LBException {
return getTreePathData(scheme, version, hierarchyID, code, -1);
}
public HashMap getTreePathData(String scheme, String version,
String hierarchyID, String code, int maxLevel) throws LBException {
LexBIGService lbsvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbsvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbsvc);
if (hierarchyID == null)
hierarchyID = "is_a";
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
SupportedHierarchy hierarchyDefn = getSupportedHierarchy(lbsvc, scheme,
csvt, hierarchyID);
return getTreePathData(lbsvc, lbscm, scheme, csvt, hierarchyDefn, code,
maxLevel);
}
public HashMap getTreePathData(LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, SupportedHierarchy hierarchyDefn,
String focusCode) throws LBException {
return getTreePathData(lbsvc, lbscm, scheme, csvt, hierarchyDefn,
focusCode, -1);
}
public HashMap getTreePathData(LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, SupportedHierarchy hierarchyDefn,
String focusCode, int maxLevel) throws LBException {
HashMap hmap = new HashMap();
TreeItem ti = new TreeItem("<Root>", "Root node");
long ms = System.currentTimeMillis();
int pathsResolved = 0;
try {
// Resolve 'is_a' hierarchy info. This example will
// need to make some calls outside of what is covered
// by existing convenience methods, but we use the
// registered hierarchy to prevent need to hard code
// relationship and direction info used on lookup ...
String hierarchyID = hierarchyDefn.getLocalId();
String[] associationsToNavigate = hierarchyDefn.getAssociationNames();
boolean associationsNavigatedFwd = hierarchyDefn
.getIsForwardNavigable();
// Identify the set of all codes on path from root
// to the focus code ...
Map<String, EntityDescription> codesToDescriptions = new HashMap<String, EntityDescription>();
AssociationList pathsFromRoot = getPathsFromRoot(lbsvc, lbscm,
scheme, csvt, hierarchyID, focusCode, codesToDescriptions,
maxLevel);
// Typically there will be one path, but handle multiple just in
// case. Each path from root provides a 'backbone', from focus
// code to root, for additional nodes to hang off of in our
// printout. For every backbone node, one level of children is
// printed, along with an indication of whether those nodes can
// be expanded.
for (Iterator<Association> paths = pathsFromRoot
.iterateAssociation(); paths.hasNext();) {
addPathFromRoot(ti, lbsvc, lbscm, scheme, csvt, paths.next(),
associationsToNavigate, associationsNavigatedFwd,
codesToDescriptions);
pathsResolved++;
}
} finally {
System.out.println("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms) + " to resolve "
+ pathsResolved + " paths from root.");
}
hmap.put(focusCode, ti);
return hmap;
}
public void run(String scheme, String version, String hierarchyId,
String focusCode) throws LBException {
HashMap hmap = getTreePathData(scheme, version, hierarchyId, focusCode);
Set keyset = hmap.keySet();
Object[] objs = keyset.toArray();
String code = (String) objs[0];
TreeItem ti = (TreeItem) hmap.get(code);
printTree(ti, focusCode, 0);
}
public static void printTree(HashMap hmap) {
if (hmap == null) {
System.out.println("ERROR printTree -- hmap is null.");
return;
}
Object[] objs = hmap.keySet().toArray();
String code = (String) objs[0];
TreeItem ti = (TreeItem) hmap.get(code);
printTree(ti, code, 0);
}
protected void addPathFromRoot(TreeItem ti, LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, Association path,
String[] associationsToNavigate, boolean associationsNavigatedFwd,
Map<String, EntityDescription> codesToDescriptions)
throws LBException {
// First, add the branch point from the path ...
ConceptReference branchRoot = path.getAssociationReference();
//=======================================================================v.50
String branchCode = branchRoot.getConceptCode();
String branchCodeDescription = codesToDescriptions
.containsKey(branchCode) ? codesToDescriptions.get(branchCode)
.getContent() : getCodeDescription(lbsvc, scheme, csvt,
branchCode);
TreeItem branchPoint = new TreeItem(branchCode, branchCodeDescription);
String branchNavText = getDirectionalLabel(lbscm, scheme, csvt, path,
associationsNavigatedFwd);
// Now process elements in the branch ...
AssociatedConceptList concepts = path.getAssociatedConcepts();
for (int i = 0; i < concepts.getAssociatedConceptCount(); i++) {
// Determine the next concept in the branch and
// add a corresponding item to the tree.
AssociatedConcept concept = concepts.getAssociatedConcept(i);
String code = concept.getConceptCode();
TreeItem branchItem = new TreeItem(code,
getCodeDescription(concept));
branchPoint.addChild(branchNavText, branchItem);
// Recurse to process the remainder of the backbone ...
AssociationList nextLevel = concept.getSourceOf();
if (nextLevel != null) {
if (nextLevel.getAssociationCount() != 0) {
// Add immediate children of the focus code with an
// indication of sub-nodes (+). Codes already
// processed as part of the path are ignored since
// they are handled through recursion.
addChildren(branchItem, lbsvc, lbscm, scheme, csvt, code,
codesToDescriptions.keySet(),
associationsToNavigate, associationsNavigatedFwd);
// More levels left to process ...
for (int j = 0; j < nextLevel.getAssociationCount(); j++)
addPathFromRoot(branchPoint, lbsvc, lbscm, scheme,
csvt, nextLevel.getAssociation(j),
associationsToNavigate,
associationsNavigatedFwd, codesToDescriptions);
} else {
// End of the line ...
// Always add immediate children of the focus code,
// in this case with no exclusions since we are moving
// beyond the path to root and allowed to duplicate
// nodes that may have occurred in the path to root.
addChildren(branchItem, lbsvc, lbscm, scheme, csvt, code,
Collections.EMPTY_SET, associationsToNavigate,
associationsNavigatedFwd);
}
} else {
// Add immediate children of the focus code with an
// indication of sub-nodes (+). Codes already
// processed as part of the path are ignored since
// they are handled through recursion.
addChildren(branchItem, lbsvc, lbscm, scheme, csvt, code,
codesToDescriptions.keySet(), associationsToNavigate,
associationsNavigatedFwd);
}
}
// Add immediate children of the node being processed,
// and indication of sub-nodes.
addChildren(branchPoint, lbsvc, lbscm, scheme, csvt, branchCode,
codesToDescriptions.keySet(), associationsToNavigate,
associationsNavigatedFwd);
// Add the populated tree item to those tracked from root.
ti.addChild(branchNavText, branchPoint);
}
/**
* Populate child nodes for a single branch of the tree, and indicates
* whether further expansion (to grandchildren) is possible.
*/
protected void addChildren(TreeItem ti, LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, String branchRootCode,
Set<String> codesToExclude, String[] associationsToNavigate,
boolean associationsNavigatedFwd) throws LBException {
// Resolve the next branch, representing children of the given
// code, navigated according to the provided relationship and
// direction. Resolve the children as a code graph, looking 2
// levels deep but leaving the final level unresolved.
CodedNodeGraph cng = lbsvc.getNodeGraph(scheme, csvt, null);
ConceptReference focus = Constructors.createConceptReference(
branchRootCode, scheme);
cng = cng.restrictToAssociations(Constructors
.createNameAndValueList(associationsToNavigate), null);
ResolvedConceptReferenceList branch = cng.resolveAsList(focus,
associationsNavigatedFwd,
//!associationsNavigatedFwd, -1, 2, noopList_, null, null, null, -1, true);
!associationsNavigatedFwd, -1, 2, noopList_, null, null, null,
-1, false);
// The resolved branch will be represented by the first node in
// the resolved list. The node will be subdivided by source or
// target associations (depending on direction). The associated
// nodes define the children.
for (Iterator<ResolvedConceptReference> nodes = branch
.iterateResolvedConceptReference(); nodes.hasNext();) {
ResolvedConceptReference node = nodes.next();
AssociationList childAssociationList = associationsNavigatedFwd ? node
.getSourceOf()
: node.getTargetOf();
//KLO 091509
if (childAssociationList == null) return;
// Process each association defining children ...
for (Iterator<Association> pathsToChildren = childAssociationList
.iterateAssociation(); pathsToChildren.hasNext();) {
Association child = pathsToChildren.next();
String childNavText = getDirectionalLabel(lbscm, scheme, csvt,
child, associationsNavigatedFwd);
// Each association may have multiple children ...
AssociatedConceptList branchItemList = child
.getAssociatedConcepts();
for (Iterator<AssociatedConcept> branchNodes = branchItemList
.iterateAssociatedConcept(); branchNodes.hasNext();) {
AssociatedConcept branchItemNode = branchNodes.next();
String branchItemCode = branchItemNode.getConceptCode();
// Add here if not in the list of excluded codes.
// This is also where we look to see if another level
// was indicated to be available. If so, mark the
// entry with a '+' to indicate it can be expanded.
//if (!branchItemNode.getReferencedEntry().getIsAnonymous()) {
if (!branchItemCode.startsWith("@")) {
if (!codesToExclude.contains(branchItemCode)) {
TreeItem childItem = new TreeItem(branchItemCode,
getCodeDescription(branchItemNode));
AssociationList grandchildBranch = associationsNavigatedFwd ? branchItemNode
.getSourceOf()
: branchItemNode.getTargetOf();
if (grandchildBranch != null)
childItem.expandable = true;
ti.addChild(childNavText, childItem);
}
}
}
}
}
}
/**
* Prints the given tree item, recursing through all branches.
* @param ti
*/
//protected void printTree(TreeItem ti, String focusCode, int depth) {
public static void printTree(TreeItem ti, String focusCode, int depth) {
StringBuffer indent = new StringBuffer();
for (int i = 0; i < depth * 2; i++)
indent.append("| ");
StringBuffer codeAndText = new StringBuffer(indent).append(
focusCode.equals(ti.code) ? ">>>>" : "").append(ti.code)
.append(':').append(
ti.text.length() > 64 ? ti.text.substring(0, 62)
+ "..." : ti.text).append(
ti.expandable ? " [+]" : "");
System.out.println(codeAndText.toString());
indent.append("| ");
for (String association : ti.assocToChildMap.keySet()) {
System.out.println(indent.toString() + association);
List<TreeItem> children = ti.assocToChildMap.get(association);
Collections.sort(children);
for (TreeItem childItem : children)
printTree(childItem, focusCode, depth + 1);
}
}
///////////////////////////////////////////////////////
// Helper Methods
///////////////////////////////////////////////////////
/**
* Returns the entity description for the given code.
*/
protected static String getCodeDescription(LexBIGService lbsvc, String scheme,
CodingSchemeVersionOrTag csvt, String code) throws LBException {
CodedNodeSet cns = lbsvc.getCodingSchemeConcepts(scheme, csvt);
cns = cns.restrictToCodes(Constructors.createConceptReferenceList(code,
scheme));
ResolvedConceptReferenceList rcrl = null;
try {
rcrl = cns.resolveToList(null, noopList_, null, 1);
} catch (Exception ex) {
System.out.println("WARNING: TreeUtils getCodeDescription cns.resolveToList throws exceptions");
return "null";
}
if (rcrl != null && rcrl.getResolvedConceptReferenceCount() > 0) {
EntityDescription desc = rcrl.getResolvedConceptReference(0)
.getEntityDescription();
if (desc != null)
return desc.getContent();
}
return "<Not assigned>";
}
/**
* Returns the entity description for the given resolved concept reference.
*/
protected static String getCodeDescription(ResolvedConceptReference ref)
throws LBException {
EntityDescription desc = ref.getEntityDescription();
if (desc != null)
return desc.getContent();
return "<Not assigned>";
}
public static boolean isBlank(String str) {
if ((str == null) || str.matches("^\\s*$")) {
return true;
} else {
return false;
}
}
/**
* Returns the label to display for the given association and directional
* indicator.
*/
protected static String getDirectionalLabel(LexBIGServiceConvenienceMethods lbscm,
String scheme, CodingSchemeVersionOrTag csvt, Association assoc,
boolean navigatedFwd) throws LBException {
String assocLabel = navigatedFwd ? lbscm.getAssociationForwardName(
assoc.getAssociationName(), scheme, csvt) : lbscm
.getAssociationReverseName(assoc.getAssociationName(), scheme,
csvt);
//if (StringUtils.isBlank(assocLabel))
if (isBlank(assocLabel))
assocLabel = (navigatedFwd ? "" : "[Inverse]")
+ assoc.getAssociationName();
return assocLabel;
}
/**
* Resolves one or more paths from the hierarchy root to the given code
* through a list of connected associations defined by the hierarchy.
*/
protected AssociationList getPathsFromRoot(LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, String hierarchyID,
String focusCode, Map<String, EntityDescription> codesToDescriptions)
throws LBException {
return getPathsFromRoot(lbsvc, lbscm, scheme, csvt, hierarchyID,
focusCode, codesToDescriptions, -1);
}
protected AssociationList getPathsFromRoot(LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, String hierarchyID,
String focusCode,
Map<String, EntityDescription> codesToDescriptions, int maxLevel)
throws LBException {
// Get paths from the focus code to the root from the
// convenience method. All paths are resolved. If only
// one path is required, it would be possible to use
// HierarchyPathResolveOption.ONE to reduce processing
// and improve overall performance.
AssociationList pathToRoot = lbscm.getHierarchyPathToRoot(scheme, csvt,
null, focusCode, false, HierarchyPathResolveOption.ALL, null);
// But for purposes of this example we need to display info
// in order coming from root direction. Process the paths to root
// recursively to reverse the order for processing ...
AssociationList pathFromRoot = new AssociationList();
for (int i = pathToRoot.getAssociationCount() - 1; i >= 0; i--)
reverseAssoc(lbsvc, lbscm, scheme, csvt, pathToRoot
.getAssociation(i), pathFromRoot, codesToDescriptions,
maxLevel, 0);
return pathFromRoot;
}
/**
* Returns a description of the hierarchy defined by the given coding
* scheme and matching the specified ID.
*/
protected static SupportedHierarchy getSupportedHierarchy(
LexBIGService lbsvc, String scheme, CodingSchemeVersionOrTag csvt,
String hierarchyID) throws LBException {
CodingScheme cs = lbsvc.resolveCodingScheme(scheme, csvt);
if (cs == null) {
throw new LBResourceUnavailableException(
"Coding scheme not found: " + scheme);
}
for (SupportedHierarchy h : cs.getMappings().getSupportedHierarchy())
if (h.getLocalId().equals(hierarchyID))
return h;
throw new LBResourceUnavailableException("Hierarchy not defined: "
+ hierarchyID);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public boolean hasSubconcepts(String scheme, String version, String code) {
HashMap hmap = getSubconcepts(scheme, version, code);
if (hmap == null) return false;
TreeItem item = (TreeItem) hmap.get(code);
return item.expandable;
}
public static HashMap getSubconcepts(String scheme, String version, String code) {
if (scheme.compareTo("NCI Thesaurus") == 0) {
return getAssociatedConcepts(scheme, version, code, "subClassOf", false);
}
else if (scheme.indexOf("MedDRA") != -1) {
return getAssociatedConcepts(scheme, version, code, "CHD", true);
}
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
if (cs == null) return null;
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
if (hierarchies == null || hierarchies.length == 0) return null;
SupportedHierarchy hierarchyDefn = hierarchies[0];
String hier_id = hierarchyDefn.getLocalId();
String[] associationsToNavigate = hierarchyDefn.getAssociationNames();
//String assocName = hier_id;//associationsToNavigate[0];
String assocName = associationsToNavigate[0];
if (assocName.compareTo("part_of") == 0) assocName = "is_a";
boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable();
if (assocName.compareTo("PAR") == 0) associationsNavigatedFwd = false;
//return getAssociatedConcepts(scheme, version, code, assocName, associationsNavigatedFwd);
return getAssociatedConcepts(lbSvc, lbscm, scheme, version, code, assocName, associationsNavigatedFwd);
} catch (Exception ex) {
return null;
}
}
public static HashMap getSuperconcepts(String scheme, String version, String code) {
if (scheme.compareTo("NCI Thesaurus") == 0) {
return getAssociatedConcepts(scheme, version, code, "subClassOf", true);
}
else if (scheme.indexOf("MedDRA") != -1) {
return getAssociatedConcepts(scheme, version, code, "CHD", false);
}
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
if (cs == null) return null;
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
if (hierarchies == null || hierarchies.length == 0) return null;
SupportedHierarchy hierarchyDefn = hierarchies[0];
String[] associationsToNavigate = hierarchyDefn.getAssociationNames();
//String assocName = hier_id;//associationsToNavigate[0];
String assocName = associationsToNavigate[0];
if (assocName.compareTo("part_of") == 0) assocName = "is_a";
boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable();
if (assocName.compareTo("PAR") == 0) associationsNavigatedFwd = false;
return getAssociatedConcepts(scheme, version, code, assocName, !associationsNavigatedFwd);
} catch (Exception ex) {
return null;
}
}
/*
public static HashMap getSuperconcepts(String scheme, String version, String code) {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
if (cs == null) return null;
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
if (hierarchies == null || hierarchies.length == 0) return null;
SupportedHierarchy hierarchyDefn = hierarchies[0];
String hier_id = hierarchyDefn.getLocalId();
String[] associationsToNavigate = hierarchyDefn.getAssociationNames();
String assocName = associationsToNavigate[0];
boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable();
return getAssociatedConcepts(scheme, version, code, assocName, !associationsNavigatedFwd);
} catch (Exception ex) {
return null;
}
}
*/
public static String[] getAssociationsToNavigate(String scheme, String version) {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
if (cs == null) return null;
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
if (hierarchies == null || hierarchies.length == 0) {
System.out.println("TreeUtils mappings.getSupportedHierarchy() either returns null, or an empty array");
return null;
}
SupportedHierarchy hierarchyDefn = hierarchies[0];
String hier_id = hierarchyDefn.getLocalId();
String[] associationsToNavigate = hierarchyDefn.getAssociationNames();
return associationsToNavigate;
} catch (Exception ex) {
System.out.println("WARNING: TreeUtils getAssociationsToNavigate throws exceptions");
return null;
}
}
protected static Association processForAnonomousNodes(Association assoc) {
if (assoc == null) return null;
// clone Association except associatedConcepts
Association temp = new Association();
temp.setAssociatedData(assoc.getAssociatedData());
temp.setAssociationName(assoc.getAssociationName());
temp.setAssociationReference(assoc.getAssociationReference());
temp.setDirectionalName(assoc.getDirectionalName());
temp.setAssociatedConcepts(new AssociatedConceptList());
for (int i = 0; i < assoc.getAssociatedConcepts()
.getAssociatedConceptCount(); i++) {
// Conditionals to deal with anonymous nodes and UMLS top nodes
// "V-X"
// The first three allow UMLS traversal to top node.
// The last two are specific to owl anonymous nodes which can act
// like false
// top nodes.
/*
if (assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry() != null) {
System.out.println(assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry().getEntityDescription().getContent() + " === IsAnonymous? " + assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry().getIsAnonymous());
} else {
System.out.println("assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry() == null");
}
*/
/*
if (assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry() != null
&& assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry().getIsAnonymous() != false) {
// do nothing (NCI Thesaurus)
}
*/
if (assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry() != null
&& assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry().getIsAnonymous() != null
&& assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry().getIsAnonymous() != false
&& !assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getConceptCode().equals("@")
&& !assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getConceptCode().equals("@@")) {
// do nothing
} else {
temp.getAssociatedConcepts().addAssociatedConcept(
assoc.getAssociatedConcepts().getAssociatedConcept(i));
}
}
return temp;
}
/*
public static HashMap getAssociatedConcepts(String scheme, String version, String code, String assocName, boolean direction) {
HashMap hmap = new HashMap();
TreeItem ti = null;
long ms = System.currentTimeMillis();
Set<String> codesToExclude = Collections.EMPTY_SET;
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
String name = getCodeDescription(lbSvc, scheme, csvt, code);
ti = new TreeItem(code, name);
ti.expandable = false;
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
ConceptReference focus = Constructors.createConceptReference(code,
scheme);
cng = cng.restrictToAssociations(Constructors
.createNameAndValueList(assocName), null);
boolean associationsNavigatedFwd = direction;
// To remove anonymous classes (KLO, 091009), the resolveCodedEntryDepth parameter cannot be set to -1.
ResolvedConceptReferenceList branch = null;
try {
branch = cng.resolveAsList(focus,
associationsNavigatedFwd,
//!associationsNavigatedFwd, -1, 2, noopList_, null, null, null, -1, true);
!associationsNavigatedFwd, 1, 2, noopList_, null, null, null, -1, false);
} catch (Exception e) {
System.out.println("TreeUtils getAssociatedConcepts throws exceptions.");
return null;
}
for (Iterator<ResolvedConceptReference> nodes = branch
.iterateResolvedConceptReference(); nodes.hasNext();) {
ResolvedConceptReference node = nodes.next();
AssociationList childAssociationList = null;
//AssociationList childAssociationList = associationsNavigatedFwd ? node.getSourceOf(): node.getTargetOf();
if (associationsNavigatedFwd) {
childAssociationList = node.getSourceOf();
} else {
childAssociationList = node.getTargetOf();
}
if (childAssociationList != null) {
// Process each association defining children ...
for (Iterator<Association> pathsToChildren = childAssociationList
.iterateAssociation(); pathsToChildren.hasNext();) {
Association child = pathsToChildren.next();
//KLO 091009 remove anonomous nodes
child = processForAnonomousNodes(child);
String childNavText = getDirectionalLabel(lbscm, scheme,
csvt, child, associationsNavigatedFwd);
// Each association may have multiple children ...
AssociatedConceptList branchItemList = child
.getAssociatedConcepts();
List child_list = new ArrayList();
for (Iterator<AssociatedConcept> branchNodes = branchItemList
.iterateAssociatedConcept(); branchNodes.hasNext();) {
AssociatedConcept branchItemNode = branchNodes.next();
child_list.add(branchItemNode);
}
SortUtils.quickSort(child_list);
for (int i = 0; i < child_list.size(); i++) {
AssociatedConcept branchItemNode = (AssociatedConcept) child_list
.get(i);
String branchItemCode = branchItemNode.getConceptCode();
// Add here if not in the list of excluded codes.
// This is also where we look to see if another level
// was indicated to be available. If so, mark the
// entry with a '+' to indicate it can be expanded.
if (!codesToExclude.contains(branchItemCode)) {
TreeItem childItem = new TreeItem(branchItemCode,
getCodeDescription(branchItemNode));
ti.expandable = true;
AssociationList grandchildBranch = associationsNavigatedFwd ? branchItemNode
.getSourceOf()
: branchItemNode.getTargetOf();
if (grandchildBranch != null)
childItem.expandable = true;
ti.addChild(childNavText, childItem);
}
}
}
} else {
System.out.println("WARNING: childAssociationList == null.");
}
}
hmap.put(code, ti);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Run time (milliseconds) getSubconcepts: "
+ (System.currentTimeMillis() - ms) + " to resolve ");
return hmap;
}
*/
public static HashMap getAssociatedConcepts(String scheme, String version, String code, String assocName, boolean direction) {
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
return getAssociatedConcepts(lbSvc, lbscm, scheme, version, code, assocName, direction);
} catch (Exception ex) {
return null;
}
}
public static HashMap getAssociatedConcepts(LexBIGService lbSvc, LexBIGServiceConvenienceMethods lbscm,
String scheme, String version, String code, String assocName, boolean direction) {
HashMap hmap = new HashMap();
TreeItem ti = null;
long ms = System.currentTimeMillis();
Set<String> codesToExclude = Collections.EMPTY_SET;
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
/*
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
*/
String name = getCodeDescription(lbSvc, scheme, csvt, code);
ti = new TreeItem(code, name);
ti.expandable = false;
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
ConceptReference focus = Constructors.createConceptReference(code,
scheme);
cng = cng.restrictToAssociations(Constructors
.createNameAndValueList(assocName), null);
boolean associationsNavigatedFwd = direction;
// To remove anonymous classes (KLO, 091009), the resolveCodedEntryDepth parameter cannot be set to -1.
/*
ResolvedConceptReferenceList branch = cng.resolveAsList(focus,
associationsNavigatedFwd,
//!associationsNavigatedFwd, -1, 2, noopList_, null, null, null, -1, true);
!associationsNavigatedFwd, -1, 2, noopList_, null, null, null, -1, false);
*/
ResolvedConceptReferenceList branch = null;
try {
branch = cng.resolveAsList(focus,
associationsNavigatedFwd,
!associationsNavigatedFwd, 1, 2, noopList_, null, null, null, -1, false);
} catch (Exception e) {
System.out.println("TreeUtils getAssociatedConcepts throws exceptions.");
return null;
}
for (Iterator<ResolvedConceptReference> nodes = branch
.iterateResolvedConceptReference(); nodes.hasNext();) {
ResolvedConceptReference node = nodes.next();
AssociationList childAssociationList = null;
//AssociationList childAssociationList = associationsNavigatedFwd ? node.getSourceOf(): node.getTargetOf();
if (associationsNavigatedFwd) {
childAssociationList = node.getSourceOf();
} else {
childAssociationList = node.getTargetOf();
}
if (childAssociationList != null) {
// Process each association defining children ...
for (Iterator<Association> pathsToChildren = childAssociationList
.iterateAssociation(); pathsToChildren.hasNext();) {
Association child = pathsToChildren.next();
//KLO 091009 remove anonomous nodes
child = processForAnonomousNodes(child);
String childNavText = getDirectionalLabel(lbscm, scheme,
csvt, child, associationsNavigatedFwd);
// Each association may have multiple children ...
AssociatedConceptList branchItemList = child
.getAssociatedConcepts();
/*
for (Iterator<AssociatedConcept> branchNodes = branchItemList.iterateAssociatedConcept(); branchNodes
.hasNext();) {
AssociatedConcept branchItemNode = branchNodes.next();
*/
List child_list = new ArrayList();
for (Iterator<AssociatedConcept> branchNodes = branchItemList
.iterateAssociatedConcept(); branchNodes.hasNext();) {
AssociatedConcept branchItemNode = branchNodes.next();
child_list.add(branchItemNode);
}
SortUtils.quickSort(child_list);
for (int i = 0; i < child_list.size(); i++) {
AssociatedConcept branchItemNode = (AssociatedConcept) child_list
.get(i);
String branchItemCode = branchItemNode.getConceptCode();
if (!branchItemCode.startsWith("@")) {
// Add here if not in the list of excluded codes.
// This is also where we look to see if another level
// was indicated to be available. If so, mark the
// entry with a '+' to indicate it can be expanded.
if (!codesToExclude.contains(branchItemCode)) {
TreeItem childItem = new TreeItem(branchItemCode,
getCodeDescription(branchItemNode));
ti.expandable = true;
AssociationList grandchildBranch = associationsNavigatedFwd ? branchItemNode
.getSourceOf()
: branchItemNode.getTargetOf();
if (grandchildBranch != null)
childItem.expandable = true;
ti.addChild(childNavText, childItem);
}
}
}
}
} else {
System.out.println("WARNING: childAssociationList == null.");
}
}
hmap.put(code, ti);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Run time (milliseconds) getSubconcepts: "
+ (System.currentTimeMillis() - ms) + " to resolve ");
return hmap;
}
public HashMap getAssociationSources(String scheme, String version,
String code, String assocName) {
return getAssociatedConcepts(scheme, version, code, assocName, false);
}
public HashMap getAssociationTargets(String scheme, String version,
String code, String assocName) {
return getAssociatedConcepts(scheme, version, code, assocName, true);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Configurable tree size (MAXIMUM_TREE_LEVEL)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static ConceptReferenceList createConceptReferenceList(
String[] codes, String codingSchemeName) {
if (codes == null) {
return null;
}
ConceptReferenceList list = new ConceptReferenceList();
for (int i = 0; i < codes.length; i++) {
ConceptReference cr = new ConceptReference();
cr.setCodingSchemeName(codingSchemeName);
cr.setConceptCode(codes[i]);
list.addConceptReference(cr);
}
return list;
}
public static Concept getConceptByCode(String codingSchemeName,
String vers, String ltag, String code) {
try {
LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
if (lbSvc == null) {
System.out.println("lbSvc == null???");
return null;
}
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(vers);
ConceptReferenceList crefs = createConceptReferenceList(
new String[] { code }, codingSchemeName);
CodedNodeSet cns = null;
try {
cns = lbSvc.getCodingSchemeConcepts(codingSchemeName,
versionOrTag);
} catch (Exception e1) {
e1.printStackTrace();
}
cns = cns.restrictToCodes(crefs);
ResolvedConceptReferenceList matches = cns.resolveToList(null,
null, null, 1);
if (matches == null) {
System.out.println("Concep not found.");
return null;
}
// Analyze the result ...
if (matches.getResolvedConceptReferenceCount() > 0) {
ResolvedConceptReference ref = (ResolvedConceptReference) matches
.enumerateResolvedConceptReference().nextElement();
Concept entry = ref.getReferencedEntry();
return entry;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public static NameAndValueList createNameAndValueList(String[] names,
String[] values) {
NameAndValueList nvList = new NameAndValueList();
for (int i = 0; i < names.length; i++) {
NameAndValue nv = new NameAndValue();
nv.setName(names[i]);
if (values != null) {
nv.setContent(values[i]);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
protected AssociationList reverseAssoc(LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, Association assoc,
AssociationList addTo,
Map<String, EntityDescription> codeToEntityDescriptionMap,
int maxLevel, int currLevel) throws LBException {
if (maxLevel != -1 && currLevel >= maxLevel)
return addTo;
ConceptReference acRef = assoc.getAssociationReference();
AssociatedConcept acFromRef = new AssociatedConcept();
//===============================================================================v5.0
acFromRef.setConceptCode(acRef.getConceptCode());
AssociationList acSources = new AssociationList();
acFromRef.setIsNavigable(Boolean.TRUE);
acFromRef.setSourceOf(acSources);
// Use cached description if available (should be cached
// for all but original root) ...
if (codeToEntityDescriptionMap.containsKey(acRef.getConceptCode()))
acFromRef.setEntityDescription(codeToEntityDescriptionMap.get(acRef
.getConceptCode()));
// Otherwise retrieve on demand ...
else
acFromRef.setEntityDescription(Constructors
.createEntityDescription(getCodeDescription(lbsvc, scheme,
csvt, acRef.getConceptCode())));
AssociatedConceptList acl = assoc.getAssociatedConcepts();
for (AssociatedConcept ac : acl.getAssociatedConcept()) {
// Create reverse association (same non-directional name)
Association rAssoc = new Association();
rAssoc.setAssociationName(assoc.getAssociationName());
// On reverse, old associated concept is new reference point.
ConceptReference ref = new ConceptReference();
//===============================================================================v5.0
//ref.setCodingSchemeName(ac.getCodingSchemeName());
ref.setConceptCode(ac.getConceptCode());
rAssoc.setAssociationReference(ref);
// And old reference is new associated concept.
AssociatedConceptList rAcl = new AssociatedConceptList();
rAcl.addAssociatedConcept(acFromRef);
rAssoc.setAssociatedConcepts(rAcl);
// Set reverse directional name, if available.
String dirName = assoc.getDirectionalName();
if (dirName != null)
try {
rAssoc.setDirectionalName(lbscm.isForwardName(scheme, csvt,
dirName) ? lbscm.getAssociationReverseName(assoc
.getAssociationName(), scheme, csvt) : lbscm
.getAssociationReverseName(assoc
.getAssociationName(), scheme, csvt));
} catch (LBException e) {
}
// Save code desc for future reference when setting up
// concept references in recursive calls ...
codeToEntityDescriptionMap.put(ac.getConceptCode(), ac
.getEntityDescription());
AssociationList sourceOf = ac.getSourceOf();
if (sourceOf != null)
for (Association sourceAssoc : sourceOf.getAssociation()) {
AssociationList pos = reverseAssoc(lbsvc, lbscm, scheme,
csvt, sourceAssoc, addTo,
codeToEntityDescriptionMap, maxLevel, currLevel + 1);
pos.addAssociation(rAssoc);
}
else
addTo.addAssociation(rAssoc);
}
return acSources;
}
public Vector getHierarchyAssociationId(String scheme, String version) {
Vector association_vec = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
// Will handle secured ontologies later.
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(version);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag);
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
for (int k = 0; k < hierarchies.length; k++) {
java.lang.String[] ids = hierarchies[k].getAssociationNames();
for (int i = 0; i < ids.length; i++) {
if (!association_vec.contains(ids[i])) {
association_vec.add(ids[i]);
//System.out.println(ids[i]);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return association_vec;
}
public String getHierarchyAssociationId(String scheme, String version,
int index) {
try {
Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme,
version);
if (hierarchicalAssoName_vec != null
&& hierarchicalAssoName_vec.size() > 0) {
String hierarchicalAssoName = (String) hierarchicalAssoName_vec
.elementAt(0);
return hierarchicalAssoName;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public List getTopNodes(TreeItem ti) {
List list = new ArrayList();
getTopNodes(ti, list, 0, 1);
return list;
}
public void getTopNodes(TreeItem ti, List list, int currLevel, int maxLevel) {
if (list == null)
list = new ArrayList();
if (currLevel > maxLevel)
return;
if (ti.assocToChildMap.keySet().size() > 0) {
if (ti.text.compareTo("Root node") != 0) {
ResolvedConceptReference rcr = new ResolvedConceptReference();
rcr.setConceptCode(ti.code);
EntityDescription entityDescription = new EntityDescription();
entityDescription.setContent(ti.text);
rcr.setEntityDescription(entityDescription);
//System.out.println("Root: " + ti.text);
list.add(rcr);
}
}
for (String association : ti.assocToChildMap.keySet()) {
List<TreeItem> children = ti.assocToChildMap.get(association);
Collections.sort(children);
for (TreeItem childItem : children) {
getTopNodes(childItem, list, currLevel + 1, maxLevel);
}
}
}
public void dumpTree(HashMap hmap, String focusCode, int level) {
try {
Set keyset = hmap.keySet();
Object[] objs = keyset.toArray();
String code = (String) objs[0];
TreeItem ti = (TreeItem) hmap.get(code);
for (String association : ti.assocToChildMap.keySet()) {
System.out.println("\nassociation: " + association);
List<TreeItem> children = ti.assocToChildMap.get(association);
for (TreeItem childItem : children) {
System.out.println(childItem.text + "(" + childItem.code + ")");
int knt = 0;
if (childItem.expandable)
{
knt = 1;
System.out.println("\tnode.expandable");
printTree(childItem, focusCode, level);
List list = getTopNodes(childItem);
for (int i=0; i<list.size(); i++) {
Object obj = list.get(i);
String nd_code = "";
String nd_name = "";
if (obj instanceof ResolvedConceptReference)
{
ResolvedConceptReference node = (ResolvedConceptReference) list.get(i);
nd_code = node.getConceptCode();
nd_name = node.getEntityDescription().getContent();
}
else if (obj instanceof Concept) {
Concept node = (Concept) list.get(i);
nd_code = node.getEntityCode();
nd_name = node.getEntityDescription().getContent();
}
System.out.println("TOP NODE: " + nd_name + " (" + nd_code + ")" );
}
} else {
System.out.println("\tnode.NOT expandable");
}
}
}
} catch (Exception e) {
}
}
//====================================================================================================================
public static String[] getHierarchyIDs(String codingScheme, CodingSchemeVersionOrTag versionOrTag) throws LBException {
String[] hier = null;
Set<String> ids = new HashSet<String>();
SupportedHierarchy[] sh = null;
try {
sh = getSupportedHierarchies(codingScheme, versionOrTag);
if (sh != null)
{
for (int i = 0; i < sh.length; i++)
{
ids.add(sh[i].getLocalId());
}
// Cache and return the new value ...
hier = ids.toArray(new String[ids.size()]);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return hier;
}
protected static SupportedHierarchy[] getSupportedHierarchies(String codingScheme, CodingSchemeVersionOrTag versionOrTag) throws LBException {
CodingScheme cs = null;
try {
cs = getCodingScheme(codingScheme, versionOrTag);
} catch (Exception ex) {
}
if(cs == null){
throw new LBResourceUnavailableException("Coding scheme not found -- " + codingScheme);
}
Mappings mappings = cs.getMappings();
return mappings.getSupportedHierarchy();
}
protected static CodingScheme getCodingScheme(String codingScheme, CodingSchemeVersionOrTag versionOrTag) throws LBException {
CodingScheme cs = null;
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
cs = lbSvc.resolveCodingScheme(codingScheme, versionOrTag);
} catch (Exception ex) {
ex.printStackTrace();
}
return cs;
}
public static String getHierarchyID(String codingScheme, String version) {
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (version != null) versionOrTag.setVersion(version);
try {
String[] ids = getHierarchyIDs(codingScheme, versionOrTag);
if (ids.length > 0) return ids[0];
} catch (Exception e) {
}
return null;
}
public static ResolvedConceptReferenceList getHierarchyRoots(java.lang.String codingScheme, String version) {
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (version != null) versionOrTag.setVersion(version);
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
String hierarchyID = getHierarchyID(codingScheme, version);
return lbscm.getHierarchyRoots(codingScheme, versionOrTag, hierarchyID);
} catch (Exception e) {
return null;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
public void traverseUp(LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm,
java.lang.String codingScheme,
CodingSchemeVersionOrTag versionOrTag,
java.lang.String hierarchyID,
java.lang.String conceptCode,
TreeItem root,
TreeItem ti,
Set<String> codesToExclude,
String[] associationsToNavigate,
boolean associationsNavigatedFwd,
Set<String> visited_links,
HashMap<String, TreeItem> visited_nodes, int maxLevel, int currLevel) {
if (maxLevel != -1 && currLevel >= maxLevel) {
root.addChild("CHD", ti);
root.expandable = true;
return;
}
boolean resolveConcepts = false;
NameAndValueList associationQualifiers = null;
try {
AssociationList list = null;
list = lbscm.getHierarchyLevelPrev(codingScheme, versionOrTag, hierarchyID, conceptCode, resolveConcepts,
associationQualifiers);
int parent_knt = 0;
if (list != null && list.getAssociationCount() > 0) {
Association[] associations = list.getAssociation();
for (int k=0; k<associations.length; k++) {
Association association = associations[k];
AssociatedConceptList acl = association.getAssociatedConcepts();
for (int i = 0; i < acl.getAssociatedConceptCount(); i++) {
//child_knt = child_knt + acl.getAssociatedConceptCount();
// Determine the next concept in the branch and
// add a corresponding item to the tree.
AssociatedConcept concept = acl.getAssociatedConcept(i);
String parentCode = concept.getConceptCode();
String link = conceptCode + "|" + parentCode;
if (!visited_links.contains(link)) {
visited_links.add(link);
//System.out.println( getCodeDescription(concept) + "(" + parentCode + ")");
TreeItem branchItem = null;
if (visited_nodes.containsKey(parentCode)) {
branchItem = (TreeItem) visited_nodes.get(parentCode);
} else {
branchItem = new TreeItem(parentCode, getCodeDescription(concept));
branchItem.expandable = false;
visited_nodes.put(parentCode, branchItem);
}
try {
codesToExclude.add(conceptCode);
addChildren(branchItem, lbsvc,
lbscm, codingScheme,
versionOrTag,
parentCode,
codesToExclude,
associationsToNavigate,
associationsNavigatedFwd);
} catch (Exception ex) {
}
branchItem.addChild("CHD", ti);
parent_knt++;
//ti.addChild("PAR", branchItem);
branchItem.expandable = true;
traverseUp(lbsvc, lbscm, codingScheme, versionOrTag, hierarchyID, parentCode, root, branchItem, codesToExclude,
associationsToNavigate, associationsNavigatedFwd, visited_links, visited_nodes, maxLevel, currLevel+1);
}
}
}
}
if (parent_knt == 0) {
root.addChild("CHD", ti);
root.expandable = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public HashMap getTreePathData2(String scheme, String version, String code, int maxLevel) {
HashMap hmap = new HashMap();
TreeItem root = new TreeItem("<Root>", "Root node");
root.expandable = false;
long ms = System.currentTimeMillis();
Set<String> codesToExclude = new HashSet<String>();
HashMap<String, TreeItem> visited_nodes = new HashMap<String, TreeItem>();
Set<String> visited_links = new HashSet<String>();
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (version != null) versionOrTag.setVersion(version);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
if (cs == null) return null;
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
if (hierarchies == null || hierarchies.length == 0) return null;
SupportedHierarchy hierarchyDefn = hierarchies[0];
String hierarchyID = hierarchyDefn.getLocalId();
String[] associationsToNavigate = hierarchyDefn.getAssociationNames();
boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable();
String name = getCodeDescription(lbSvc, scheme, csvt, code);
TreeItem ti = new TreeItem(code, name);
//ti.expandable = false;
ti.expandable = hasSubconcepts(scheme, version, code);
System.out.println(name + "(" + code + ")");
traverseUp(lbSvc, lbscm, scheme, csvt, hierarchyID, code, root, ti, codesToExclude, associationsToNavigate, associationsNavigatedFwd, visited_links, visited_nodes, maxLevel, 0);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms) + " to resolve "
//+ pathsResolved + " paths from root.");
+ " paths from root.");
}
hmap.put(code, root);
return hmap;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
String url = "http://lexevsapi-dev.nci.nih.gov/lexevsapi42";
url = "http://lexevsapi-qa.nci.nih.gov/lexevsapi50";
HashMap hmap = null;
String scheme = "NCI Thesaurus";
String version = null;
String code = "C26709";
TreeUtils test = new TreeUtils();
//hmap = test.getSubconcepts(scheme, version, code);
//test.printTree(hmap);
code = "C2910";
code = "C9335";
String hierarchyID = test.getHierarchyID(scheme, null);
System.out.println("(*) " + scheme + " Hierarchy ID: " + hierarchyID);
hmap = test.getSubconcepts(scheme, version, code);
test.printTree(hmap);
System.out.println("=============================================================");
scheme = "Gene Ontology";
code = "GO:0008150";
hierarchyID = test.getHierarchyID(scheme, null);
System.out.println("Hierarchy ID: " + hierarchyID);
hmap = test.getSubconcepts(scheme, version, code);
test.printTree(hmap);
System.out.println("=============================================================");
scheme = "HL7 Reference Information Model ";
code = "AcknowledgementType";
hierarchyID = test.getHierarchyID(scheme, null);
System.out.println("Hierarchy ID: " + hierarchyID);
hmap = test.getSubconcepts(scheme, version, code);
test.printTree(hmap);
}
}
| software/ncitbrowser/src/java/gov/nih/nci/evs/browser/utils/TreeUtils.java | package gov.nih.nci.evs.browser.utils;
/*
* Copyright: (c) 2004-2009 Mayo Foundation for Medical Education and
* Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the
* triple-shield Mayo logo are trademarks and service marks of MFMER.
*
* Except as contained in the copyright notice above, or as used to identify
* MFMER as the author of this software, the trade names, trademarks, service
* marks, or product names of the copyright holder shall not be used in
* advertising, promotion or otherwise in connection with this software without
* prior written authorization of the copyright holder.
*
* Licensed under the Eclipse Public License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
*/
/**
* @author EVS Team
* @version 1.0
*
* Note: This class is created based on Mayo's BuildTreForCode.java sample code
*
* Modification history
* Initial modification [email protected]
*
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import java.io.Serializable;
import org.LexGrid.LexBIG.DataModel.Collections.AssociatedConceptList;
import org.LexGrid.LexBIG.DataModel.Collections.AssociationList;
import org.LexGrid.LexBIG.DataModel.Collections.LocalNameList;
import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept;
import org.LexGrid.LexBIG.DataModel.Core.Association;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.DataModel.Core.ConceptReference;
import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference;
import org.LexGrid.LexBIG.Exceptions.LBException;
import org.LexGrid.LexBIG.Exceptions.LBResourceUnavailableException;
import org.LexGrid.LexBIG.Extensions.Generic.LexBIGServiceConvenienceMethods;
import org.LexGrid.LexBIG.Extensions.Generic.LexBIGServiceConvenienceMethods.HierarchyPathResolveOption;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeGraph;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet;
import org.LexGrid.LexBIG.LexBIGService.LexBIGService;
import org.LexGrid.LexBIG.Utility.Constructors;
import org.LexGrid.codingSchemes.CodingScheme;
import org.LexGrid.commonTypes.EntityDescription;
import org.LexGrid.naming.SupportedHierarchy;
import org.LexGrid.naming.Mappings;
import org.LexGrid.LexBIG.DataModel.Collections.ConceptReferenceList;
import org.LexGrid.concepts.Concept;
import org.LexGrid.LexBIG.DataModel.Core.NameAndValue;
import org.LexGrid.LexBIG.DataModel.Collections.NameAndValueList;
import org.LexGrid.LexBIG.Extensions.Generic.LexBIGServiceConvenienceMethods;
//import static gov.nih.nci.evs.browser.common.Constants.*;
/**
* Attempts to provide a tree, based on a focus code, that includes the
* following information:
* <pre>
* - All paths from the hierarchy root to one or more focus codes.
* - Immediate children of every node in path to root
* - Indicator to show whether any unexpanded node can be further expanded
* </pre>
*
* This example accepts two parameters...
* The first parameter is required, and must contain at least one code
* in a comma-delimited list. A tree is produced for each code. Time to
* produce the tree for each code is printed in milliseconds. In order
* to factor out costs of startup and shutdown, resolving multiple
* codes may offer a better overall estimate performance.
*
* The second parameter is optional, and can indicate a hierarchy ID to
* navigate when resolving child nodes. If not provided, "is_a" is
* assumed.
*/
public class TreeUtils {
static LocalNameList noopList_ = Constructors.createLocalNameList("_noop_");
public TreeUtils() {
}
public HashMap getTreePathData(String scheme, String version,
String hierarchyID, String code) throws LBException {
return getTreePathData(scheme, version, hierarchyID, code, -1);
}
public HashMap getTreePathData(String scheme, String version,
String hierarchyID, String code, int maxLevel) throws LBException {
LexBIGService lbsvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbsvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbsvc);
if (hierarchyID == null)
hierarchyID = "is_a";
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
SupportedHierarchy hierarchyDefn = getSupportedHierarchy(lbsvc, scheme,
csvt, hierarchyID);
return getTreePathData(lbsvc, lbscm, scheme, csvt, hierarchyDefn, code,
maxLevel);
}
public HashMap getTreePathData(LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, SupportedHierarchy hierarchyDefn,
String focusCode) throws LBException {
return getTreePathData(lbsvc, lbscm, scheme, csvt, hierarchyDefn,
focusCode, -1);
}
public HashMap getTreePathData(LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, SupportedHierarchy hierarchyDefn,
String focusCode, int maxLevel) throws LBException {
HashMap hmap = new HashMap();
TreeItem ti = new TreeItem("<Root>", "Root node");
long ms = System.currentTimeMillis();
int pathsResolved = 0;
try {
// Resolve 'is_a' hierarchy info. This example will
// need to make some calls outside of what is covered
// by existing convenience methods, but we use the
// registered hierarchy to prevent need to hard code
// relationship and direction info used on lookup ...
String hierarchyID = hierarchyDefn.getLocalId();
String[] associationsToNavigate = hierarchyDefn.getAssociationNames();
boolean associationsNavigatedFwd = hierarchyDefn
.getIsForwardNavigable();
// Identify the set of all codes on path from root
// to the focus code ...
Map<String, EntityDescription> codesToDescriptions = new HashMap<String, EntityDescription>();
AssociationList pathsFromRoot = getPathsFromRoot(lbsvc, lbscm,
scheme, csvt, hierarchyID, focusCode, codesToDescriptions,
maxLevel);
// Typically there will be one path, but handle multiple just in
// case. Each path from root provides a 'backbone', from focus
// code to root, for additional nodes to hang off of in our
// printout. For every backbone node, one level of children is
// printed, along with an indication of whether those nodes can
// be expanded.
for (Iterator<Association> paths = pathsFromRoot
.iterateAssociation(); paths.hasNext();) {
addPathFromRoot(ti, lbsvc, lbscm, scheme, csvt, paths.next(),
associationsToNavigate, associationsNavigatedFwd,
codesToDescriptions);
pathsResolved++;
}
} finally {
System.out.println("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms) + " to resolve "
+ pathsResolved + " paths from root.");
}
hmap.put(focusCode, ti);
return hmap;
}
public void run(String scheme, String version, String hierarchyId,
String focusCode) throws LBException {
HashMap hmap = getTreePathData(scheme, version, hierarchyId, focusCode);
Set keyset = hmap.keySet();
Object[] objs = keyset.toArray();
String code = (String) objs[0];
TreeItem ti = (TreeItem) hmap.get(code);
printTree(ti, focusCode, 0);
}
public static void printTree(HashMap hmap) {
if (hmap == null) {
System.out.println("ERROR printTree -- hmap is null.");
return;
}
Object[] objs = hmap.keySet().toArray();
String code = (String) objs[0];
TreeItem ti = (TreeItem) hmap.get(code);
printTree(ti, code, 0);
}
protected void addPathFromRoot(TreeItem ti, LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, Association path,
String[] associationsToNavigate, boolean associationsNavigatedFwd,
Map<String, EntityDescription> codesToDescriptions)
throws LBException {
// First, add the branch point from the path ...
ConceptReference branchRoot = path.getAssociationReference();
//=======================================================================v.50
String branchCode = branchRoot.getConceptCode();
String branchCodeDescription = codesToDescriptions
.containsKey(branchCode) ? codesToDescriptions.get(branchCode)
.getContent() : getCodeDescription(lbsvc, scheme, csvt,
branchCode);
TreeItem branchPoint = new TreeItem(branchCode, branchCodeDescription);
String branchNavText = getDirectionalLabel(lbscm, scheme, csvt, path,
associationsNavigatedFwd);
// Now process elements in the branch ...
AssociatedConceptList concepts = path.getAssociatedConcepts();
for (int i = 0; i < concepts.getAssociatedConceptCount(); i++) {
// Determine the next concept in the branch and
// add a corresponding item to the tree.
AssociatedConcept concept = concepts.getAssociatedConcept(i);
String code = concept.getConceptCode();
TreeItem branchItem = new TreeItem(code,
getCodeDescription(concept));
branchPoint.addChild(branchNavText, branchItem);
// Recurse to process the remainder of the backbone ...
AssociationList nextLevel = concept.getSourceOf();
if (nextLevel != null) {
if (nextLevel.getAssociationCount() != 0) {
// Add immediate children of the focus code with an
// indication of sub-nodes (+). Codes already
// processed as part of the path are ignored since
// they are handled through recursion.
addChildren(branchItem, lbsvc, lbscm, scheme, csvt, code,
codesToDescriptions.keySet(),
associationsToNavigate, associationsNavigatedFwd);
// More levels left to process ...
for (int j = 0; j < nextLevel.getAssociationCount(); j++)
addPathFromRoot(branchPoint, lbsvc, lbscm, scheme,
csvt, nextLevel.getAssociation(j),
associationsToNavigate,
associationsNavigatedFwd, codesToDescriptions);
} else {
// End of the line ...
// Always add immediate children of the focus code,
// in this case with no exclusions since we are moving
// beyond the path to root and allowed to duplicate
// nodes that may have occurred in the path to root.
addChildren(branchItem, lbsvc, lbscm, scheme, csvt, code,
Collections.EMPTY_SET, associationsToNavigate,
associationsNavigatedFwd);
}
} else {
// Add immediate children of the focus code with an
// indication of sub-nodes (+). Codes already
// processed as part of the path are ignored since
// they are handled through recursion.
addChildren(branchItem, lbsvc, lbscm, scheme, csvt, code,
codesToDescriptions.keySet(), associationsToNavigate,
associationsNavigatedFwd);
}
}
// Add immediate children of the node being processed,
// and indication of sub-nodes.
addChildren(branchPoint, lbsvc, lbscm, scheme, csvt, branchCode,
codesToDescriptions.keySet(), associationsToNavigate,
associationsNavigatedFwd);
// Add the populated tree item to those tracked from root.
ti.addChild(branchNavText, branchPoint);
}
/**
* Populate child nodes for a single branch of the tree, and indicates
* whether further expansion (to grandchildren) is possible.
*/
protected void addChildren(TreeItem ti, LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, String branchRootCode,
Set<String> codesToExclude, String[] associationsToNavigate,
boolean associationsNavigatedFwd) throws LBException {
// Resolve the next branch, representing children of the given
// code, navigated according to the provided relationship and
// direction. Resolve the children as a code graph, looking 2
// levels deep but leaving the final level unresolved.
CodedNodeGraph cng = lbsvc.getNodeGraph(scheme, csvt, null);
ConceptReference focus = Constructors.createConceptReference(
branchRootCode, scheme);
cng = cng.restrictToAssociations(Constructors
.createNameAndValueList(associationsToNavigate), null);
ResolvedConceptReferenceList branch = cng.resolveAsList(focus,
associationsNavigatedFwd,
//!associationsNavigatedFwd, -1, 2, noopList_, null, null, null, -1, true);
!associationsNavigatedFwd, -1, 2, noopList_, null, null, null,
-1, false);
// The resolved branch will be represented by the first node in
// the resolved list. The node will be subdivided by source or
// target associations (depending on direction). The associated
// nodes define the children.
for (Iterator<ResolvedConceptReference> nodes = branch
.iterateResolvedConceptReference(); nodes.hasNext();) {
ResolvedConceptReference node = nodes.next();
AssociationList childAssociationList = associationsNavigatedFwd ? node
.getSourceOf()
: node.getTargetOf();
//KLO 091509
if (childAssociationList == null) return;
// Process each association defining children ...
for (Iterator<Association> pathsToChildren = childAssociationList
.iterateAssociation(); pathsToChildren.hasNext();) {
Association child = pathsToChildren.next();
String childNavText = getDirectionalLabel(lbscm, scheme, csvt,
child, associationsNavigatedFwd);
// Each association may have multiple children ...
AssociatedConceptList branchItemList = child
.getAssociatedConcepts();
for (Iterator<AssociatedConcept> branchNodes = branchItemList
.iterateAssociatedConcept(); branchNodes.hasNext();) {
AssociatedConcept branchItemNode = branchNodes.next();
String branchItemCode = branchItemNode.getConceptCode();
// Add here if not in the list of excluded codes.
// This is also where we look to see if another level
// was indicated to be available. If so, mark the
// entry with a '+' to indicate it can be expanded.
//if (!branchItemNode.getReferencedEntry().getIsAnonymous()) {
if (!branchItemCode.startsWith("@")) {
if (!codesToExclude.contains(branchItemCode)) {
TreeItem childItem = new TreeItem(branchItemCode,
getCodeDescription(branchItemNode));
AssociationList grandchildBranch = associationsNavigatedFwd ? branchItemNode
.getSourceOf()
: branchItemNode.getTargetOf();
if (grandchildBranch != null)
childItem.expandable = true;
ti.addChild(childNavText, childItem);
}
}
}
}
}
}
/**
* Prints the given tree item, recursing through all branches.
* @param ti
*/
//protected void printTree(TreeItem ti, String focusCode, int depth) {
public static void printTree(TreeItem ti, String focusCode, int depth) {
StringBuffer indent = new StringBuffer();
for (int i = 0; i < depth * 2; i++)
indent.append("| ");
StringBuffer codeAndText = new StringBuffer(indent).append(
focusCode.equals(ti.code) ? ">>>>" : "").append(ti.code)
.append(':').append(
ti.text.length() > 64 ? ti.text.substring(0, 62)
+ "..." : ti.text).append(
ti.expandable ? " [+]" : "");
System.out.println(codeAndText.toString());
indent.append("| ");
for (String association : ti.assocToChildMap.keySet()) {
System.out.println(indent.toString() + association);
List<TreeItem> children = ti.assocToChildMap.get(association);
Collections.sort(children);
for (TreeItem childItem : children)
printTree(childItem, focusCode, depth + 1);
}
}
///////////////////////////////////////////////////////
// Helper Methods
///////////////////////////////////////////////////////
/**
* Returns the entity description for the given code.
*/
protected static String getCodeDescription(LexBIGService lbsvc, String scheme,
CodingSchemeVersionOrTag csvt, String code) throws LBException {
CodedNodeSet cns = lbsvc.getCodingSchemeConcepts(scheme, csvt);
cns = cns.restrictToCodes(Constructors.createConceptReferenceList(code,
scheme));
ResolvedConceptReferenceList rcrl = null;
try {
rcrl = cns.resolveToList(null, noopList_, null, 1);
} catch (Exception ex) {
System.out.println("WARNING: TreeUtils getCodeDescription cns.resolveToList throws exceptions");
return "null";
}
if (rcrl != null && rcrl.getResolvedConceptReferenceCount() > 0) {
EntityDescription desc = rcrl.getResolvedConceptReference(0)
.getEntityDescription();
if (desc != null)
return desc.getContent();
}
return "<Not assigned>";
}
/**
* Returns the entity description for the given resolved concept reference.
*/
protected static String getCodeDescription(ResolvedConceptReference ref)
throws LBException {
EntityDescription desc = ref.getEntityDescription();
if (desc != null)
return desc.getContent();
return "<Not assigned>";
}
public static boolean isBlank(String str) {
if ((str == null) || str.matches("^\\s*$")) {
return true;
} else {
return false;
}
}
/**
* Returns the label to display for the given association and directional
* indicator.
*/
protected static String getDirectionalLabel(LexBIGServiceConvenienceMethods lbscm,
String scheme, CodingSchemeVersionOrTag csvt, Association assoc,
boolean navigatedFwd) throws LBException {
String assocLabel = navigatedFwd ? lbscm.getAssociationForwardName(
assoc.getAssociationName(), scheme, csvt) : lbscm
.getAssociationReverseName(assoc.getAssociationName(), scheme,
csvt);
//if (StringUtils.isBlank(assocLabel))
if (isBlank(assocLabel))
assocLabel = (navigatedFwd ? "" : "[Inverse]")
+ assoc.getAssociationName();
return assocLabel;
}
/**
* Resolves one or more paths from the hierarchy root to the given code
* through a list of connected associations defined by the hierarchy.
*/
protected AssociationList getPathsFromRoot(LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, String hierarchyID,
String focusCode, Map<String, EntityDescription> codesToDescriptions)
throws LBException {
return getPathsFromRoot(lbsvc, lbscm, scheme, csvt, hierarchyID,
focusCode, codesToDescriptions, -1);
}
protected AssociationList getPathsFromRoot(LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, String hierarchyID,
String focusCode,
Map<String, EntityDescription> codesToDescriptions, int maxLevel)
throws LBException {
// Get paths from the focus code to the root from the
// convenience method. All paths are resolved. If only
// one path is required, it would be possible to use
// HierarchyPathResolveOption.ONE to reduce processing
// and improve overall performance.
AssociationList pathToRoot = lbscm.getHierarchyPathToRoot(scheme, csvt,
null, focusCode, false, HierarchyPathResolveOption.ALL, null);
// But for purposes of this example we need to display info
// in order coming from root direction. Process the paths to root
// recursively to reverse the order for processing ...
AssociationList pathFromRoot = new AssociationList();
for (int i = pathToRoot.getAssociationCount() - 1; i >= 0; i--)
reverseAssoc(lbsvc, lbscm, scheme, csvt, pathToRoot
.getAssociation(i), pathFromRoot, codesToDescriptions,
maxLevel, 0);
return pathFromRoot;
}
/**
* Returns a description of the hierarchy defined by the given coding
* scheme and matching the specified ID.
*/
protected static SupportedHierarchy getSupportedHierarchy(
LexBIGService lbsvc, String scheme, CodingSchemeVersionOrTag csvt,
String hierarchyID) throws LBException {
CodingScheme cs = lbsvc.resolveCodingScheme(scheme, csvt);
if (cs == null) {
throw new LBResourceUnavailableException(
"Coding scheme not found: " + scheme);
}
for (SupportedHierarchy h : cs.getMappings().getSupportedHierarchy())
if (h.getLocalId().equals(hierarchyID))
return h;
throw new LBResourceUnavailableException("Hierarchy not defined: "
+ hierarchyID);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public boolean hasSubconcepts(String scheme, String version, String code) {
HashMap hmap = getSubconcepts(scheme, version, code);
if (hmap == null) return false;
TreeItem item = (TreeItem) hmap.get(code);
return item.expandable;
}
public static HashMap getSubconcepts(String scheme, String version, String code) {
if (scheme.compareTo("NCI Thesaurus") == 0) {
return getAssociatedConcepts(scheme, version, code, "subClassOf", false);
}
else if (scheme.indexOf("MedDRA") != -1) {
return getAssociatedConcepts(scheme, version, code, "CHD", true);
}
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
if (cs == null) return null;
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
if (hierarchies == null || hierarchies.length == 0) return null;
SupportedHierarchy hierarchyDefn = hierarchies[0];
String hier_id = hierarchyDefn.getLocalId();
String[] associationsToNavigate = hierarchyDefn.getAssociationNames();
//String assocName = hier_id;//associationsToNavigate[0];
String assocName = associationsToNavigate[0];
if (assocName.compareTo("part_of") == 0) assocName = "is_a";
boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable();
if (assocName.compareTo("PAR") == 0) associationsNavigatedFwd = false;
return getAssociatedConcepts(scheme, version, code, assocName, associationsNavigatedFwd);
} catch (Exception ex) {
return null;
}
}
public static HashMap getSuperconcepts(String scheme, String version, String code) {
if (scheme.compareTo("NCI Thesaurus") == 0) {
return getAssociatedConcepts(scheme, version, code, "subClassOf", true);
}
else if (scheme.indexOf("MedDRA") != -1) {
return getAssociatedConcepts(scheme, version, code, "CHD", false);
}
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
if (cs == null) return null;
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
if (hierarchies == null || hierarchies.length == 0) return null;
SupportedHierarchy hierarchyDefn = hierarchies[0];
String[] associationsToNavigate = hierarchyDefn.getAssociationNames();
//String assocName = hier_id;//associationsToNavigate[0];
String assocName = associationsToNavigate[0];
if (assocName.compareTo("part_of") == 0) assocName = "is_a";
boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable();
if (assocName.compareTo("PAR") == 0) associationsNavigatedFwd = false;
return getAssociatedConcepts(scheme, version, code, assocName, !associationsNavigatedFwd);
} catch (Exception ex) {
return null;
}
}
/*
public static HashMap getSuperconcepts(String scheme, String version, String code) {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
if (cs == null) return null;
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
if (hierarchies == null || hierarchies.length == 0) return null;
SupportedHierarchy hierarchyDefn = hierarchies[0];
String hier_id = hierarchyDefn.getLocalId();
String[] associationsToNavigate = hierarchyDefn.getAssociationNames();
String assocName = associationsToNavigate[0];
boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable();
return getAssociatedConcepts(scheme, version, code, assocName, !associationsNavigatedFwd);
} catch (Exception ex) {
return null;
}
}
*/
public static String[] getAssociationsToNavigate(String scheme, String version) {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
if (cs == null) return null;
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
if (hierarchies == null || hierarchies.length == 0) {
System.out.println("TreeUtils mappings.getSupportedHierarchy() either returns null, or an empty array");
return null;
}
SupportedHierarchy hierarchyDefn = hierarchies[0];
String hier_id = hierarchyDefn.getLocalId();
String[] associationsToNavigate = hierarchyDefn.getAssociationNames();
return associationsToNavigate;
} catch (Exception ex) {
System.out.println("WARNING: TreeUtils getAssociationsToNavigate throws exceptions");
return null;
}
}
protected static Association processForAnonomousNodes(Association assoc) {
if (assoc == null) return null;
// clone Association except associatedConcepts
Association temp = new Association();
temp.setAssociatedData(assoc.getAssociatedData());
temp.setAssociationName(assoc.getAssociationName());
temp.setAssociationReference(assoc.getAssociationReference());
temp.setDirectionalName(assoc.getDirectionalName());
temp.setAssociatedConcepts(new AssociatedConceptList());
for (int i = 0; i < assoc.getAssociatedConcepts()
.getAssociatedConceptCount(); i++) {
// Conditionals to deal with anonymous nodes and UMLS top nodes
// "V-X"
// The first three allow UMLS traversal to top node.
// The last two are specific to owl anonymous nodes which can act
// like false
// top nodes.
/*
if (assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry() != null) {
System.out.println(assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry().getEntityDescription().getContent() + " === IsAnonymous? " + assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry().getIsAnonymous());
} else {
System.out.println("assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry() == null");
}
*/
/*
if (assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry() != null
&& assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry().getIsAnonymous() != false) {
// do nothing (NCI Thesaurus)
}
*/
if (assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry() != null
&& assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry().getIsAnonymous() != null
&& assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry().getIsAnonymous() != false
&& !assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getConceptCode().equals("@")
&& !assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getConceptCode().equals("@@")) {
// do nothing
} else {
temp.getAssociatedConcepts().addAssociatedConcept(
assoc.getAssociatedConcepts().getAssociatedConcept(i));
}
}
return temp;
}
/*
public static HashMap getAssociatedConcepts(String scheme, String version, String code, String assocName, boolean direction) {
HashMap hmap = new HashMap();
TreeItem ti = null;
long ms = System.currentTimeMillis();
Set<String> codesToExclude = Collections.EMPTY_SET;
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
String name = getCodeDescription(lbSvc, scheme, csvt, code);
ti = new TreeItem(code, name);
ti.expandable = false;
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
ConceptReference focus = Constructors.createConceptReference(code,
scheme);
cng = cng.restrictToAssociations(Constructors
.createNameAndValueList(assocName), null);
boolean associationsNavigatedFwd = direction;
// To remove anonymous classes (KLO, 091009), the resolveCodedEntryDepth parameter cannot be set to -1.
ResolvedConceptReferenceList branch = null;
try {
branch = cng.resolveAsList(focus,
associationsNavigatedFwd,
//!associationsNavigatedFwd, -1, 2, noopList_, null, null, null, -1, true);
!associationsNavigatedFwd, 1, 2, noopList_, null, null, null, -1, false);
} catch (Exception e) {
System.out.println("TreeUtils getAssociatedConcepts throws exceptions.");
return null;
}
for (Iterator<ResolvedConceptReference> nodes = branch
.iterateResolvedConceptReference(); nodes.hasNext();) {
ResolvedConceptReference node = nodes.next();
AssociationList childAssociationList = null;
//AssociationList childAssociationList = associationsNavigatedFwd ? node.getSourceOf(): node.getTargetOf();
if (associationsNavigatedFwd) {
childAssociationList = node.getSourceOf();
} else {
childAssociationList = node.getTargetOf();
}
if (childAssociationList != null) {
// Process each association defining children ...
for (Iterator<Association> pathsToChildren = childAssociationList
.iterateAssociation(); pathsToChildren.hasNext();) {
Association child = pathsToChildren.next();
//KLO 091009 remove anonomous nodes
child = processForAnonomousNodes(child);
String childNavText = getDirectionalLabel(lbscm, scheme,
csvt, child, associationsNavigatedFwd);
// Each association may have multiple children ...
AssociatedConceptList branchItemList = child
.getAssociatedConcepts();
List child_list = new ArrayList();
for (Iterator<AssociatedConcept> branchNodes = branchItemList
.iterateAssociatedConcept(); branchNodes.hasNext();) {
AssociatedConcept branchItemNode = branchNodes.next();
child_list.add(branchItemNode);
}
SortUtils.quickSort(child_list);
for (int i = 0; i < child_list.size(); i++) {
AssociatedConcept branchItemNode = (AssociatedConcept) child_list
.get(i);
String branchItemCode = branchItemNode.getConceptCode();
// Add here if not in the list of excluded codes.
// This is also where we look to see if another level
// was indicated to be available. If so, mark the
// entry with a '+' to indicate it can be expanded.
if (!codesToExclude.contains(branchItemCode)) {
TreeItem childItem = new TreeItem(branchItemCode,
getCodeDescription(branchItemNode));
ti.expandable = true;
AssociationList grandchildBranch = associationsNavigatedFwd ? branchItemNode
.getSourceOf()
: branchItemNode.getTargetOf();
if (grandchildBranch != null)
childItem.expandable = true;
ti.addChild(childNavText, childItem);
}
}
}
} else {
System.out.println("WARNING: childAssociationList == null.");
}
}
hmap.put(code, ti);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Run time (milliseconds) getSubconcepts: "
+ (System.currentTimeMillis() - ms) + " to resolve ");
return hmap;
}
*/
public static HashMap getAssociatedConcepts(String scheme, String version, String code, String assocName, boolean direction) {
HashMap hmap = new HashMap();
TreeItem ti = null;
long ms = System.currentTimeMillis();
Set<String> codesToExclude = Collections.EMPTY_SET;
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
String name = getCodeDescription(lbSvc, scheme, csvt, code);
ti = new TreeItem(code, name);
ti.expandable = false;
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
ConceptReference focus = Constructors.createConceptReference(code,
scheme);
cng = cng.restrictToAssociations(Constructors
.createNameAndValueList(assocName), null);
boolean associationsNavigatedFwd = direction;
// To remove anonymous classes (KLO, 091009), the resolveCodedEntryDepth parameter cannot be set to -1.
/*
ResolvedConceptReferenceList branch = cng.resolveAsList(focus,
associationsNavigatedFwd,
//!associationsNavigatedFwd, -1, 2, noopList_, null, null, null, -1, true);
!associationsNavigatedFwd, -1, 2, noopList_, null, null, null, -1, false);
*/
ResolvedConceptReferenceList branch = null;
try {
branch = cng.resolveAsList(focus,
associationsNavigatedFwd,
!associationsNavigatedFwd, 1, 2, noopList_, null, null, null, -1, false);
} catch (Exception e) {
System.out.println("TreeUtils getAssociatedConcepts throws exceptions.");
return null;
}
for (Iterator<ResolvedConceptReference> nodes = branch
.iterateResolvedConceptReference(); nodes.hasNext();) {
ResolvedConceptReference node = nodes.next();
AssociationList childAssociationList = null;
//AssociationList childAssociationList = associationsNavigatedFwd ? node.getSourceOf(): node.getTargetOf();
if (associationsNavigatedFwd) {
childAssociationList = node.getSourceOf();
} else {
childAssociationList = node.getTargetOf();
}
if (childAssociationList != null) {
// Process each association defining children ...
for (Iterator<Association> pathsToChildren = childAssociationList
.iterateAssociation(); pathsToChildren.hasNext();) {
Association child = pathsToChildren.next();
//KLO 091009 remove anonomous nodes
child = processForAnonomousNodes(child);
String childNavText = getDirectionalLabel(lbscm, scheme,
csvt, child, associationsNavigatedFwd);
// Each association may have multiple children ...
AssociatedConceptList branchItemList = child
.getAssociatedConcepts();
/*
for (Iterator<AssociatedConcept> branchNodes = branchItemList.iterateAssociatedConcept(); branchNodes
.hasNext();) {
AssociatedConcept branchItemNode = branchNodes.next();
*/
List child_list = new ArrayList();
for (Iterator<AssociatedConcept> branchNodes = branchItemList
.iterateAssociatedConcept(); branchNodes.hasNext();) {
AssociatedConcept branchItemNode = branchNodes.next();
child_list.add(branchItemNode);
}
SortUtils.quickSort(child_list);
for (int i = 0; i < child_list.size(); i++) {
AssociatedConcept branchItemNode = (AssociatedConcept) child_list
.get(i);
String branchItemCode = branchItemNode.getConceptCode();
if (!branchItemCode.startsWith("@")) {
// Add here if not in the list of excluded codes.
// This is also where we look to see if another level
// was indicated to be available. If so, mark the
// entry with a '+' to indicate it can be expanded.
if (!codesToExclude.contains(branchItemCode)) {
TreeItem childItem = new TreeItem(branchItemCode,
getCodeDescription(branchItemNode));
ti.expandable = true;
AssociationList grandchildBranch = associationsNavigatedFwd ? branchItemNode
.getSourceOf()
: branchItemNode.getTargetOf();
if (grandchildBranch != null)
childItem.expandable = true;
ti.addChild(childNavText, childItem);
}
}
}
}
} else {
System.out.println("WARNING: childAssociationList == null.");
}
}
hmap.put(code, ti);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Run time (milliseconds) getSubconcepts: "
+ (System.currentTimeMillis() - ms) + " to resolve ");
return hmap;
}
public HashMap getAssociationSources(String scheme, String version,
String code, String assocName) {
return getAssociatedConcepts(scheme, version, code, assocName, false);
}
public HashMap getAssociationTargets(String scheme, String version,
String code, String assocName) {
return getAssociatedConcepts(scheme, version, code, assocName, true);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Configurable tree size (MAXIMUM_TREE_LEVEL)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static ConceptReferenceList createConceptReferenceList(
String[] codes, String codingSchemeName) {
if (codes == null) {
return null;
}
ConceptReferenceList list = new ConceptReferenceList();
for (int i = 0; i < codes.length; i++) {
ConceptReference cr = new ConceptReference();
cr.setCodingSchemeName(codingSchemeName);
cr.setConceptCode(codes[i]);
list.addConceptReference(cr);
}
return list;
}
public static Concept getConceptByCode(String codingSchemeName,
String vers, String ltag, String code) {
try {
LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
if (lbSvc == null) {
System.out.println("lbSvc == null???");
return null;
}
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(vers);
ConceptReferenceList crefs = createConceptReferenceList(
new String[] { code }, codingSchemeName);
CodedNodeSet cns = null;
try {
cns = lbSvc.getCodingSchemeConcepts(codingSchemeName,
versionOrTag);
} catch (Exception e1) {
e1.printStackTrace();
}
cns = cns.restrictToCodes(crefs);
ResolvedConceptReferenceList matches = cns.resolveToList(null,
null, null, 1);
if (matches == null) {
System.out.println("Concep not found.");
return null;
}
// Analyze the result ...
if (matches.getResolvedConceptReferenceCount() > 0) {
ResolvedConceptReference ref = (ResolvedConceptReference) matches
.enumerateResolvedConceptReference().nextElement();
Concept entry = ref.getReferencedEntry();
return entry;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public static NameAndValueList createNameAndValueList(String[] names,
String[] values) {
NameAndValueList nvList = new NameAndValueList();
for (int i = 0; i < names.length; i++) {
NameAndValue nv = new NameAndValue();
nv.setName(names[i]);
if (values != null) {
nv.setContent(values[i]);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
protected AssociationList reverseAssoc(LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm, String scheme,
CodingSchemeVersionOrTag csvt, Association assoc,
AssociationList addTo,
Map<String, EntityDescription> codeToEntityDescriptionMap,
int maxLevel, int currLevel) throws LBException {
if (maxLevel != -1 && currLevel >= maxLevel)
return addTo;
ConceptReference acRef = assoc.getAssociationReference();
AssociatedConcept acFromRef = new AssociatedConcept();
//===============================================================================v5.0
acFromRef.setConceptCode(acRef.getConceptCode());
AssociationList acSources = new AssociationList();
acFromRef.setIsNavigable(Boolean.TRUE);
acFromRef.setSourceOf(acSources);
// Use cached description if available (should be cached
// for all but original root) ...
if (codeToEntityDescriptionMap.containsKey(acRef.getConceptCode()))
acFromRef.setEntityDescription(codeToEntityDescriptionMap.get(acRef
.getConceptCode()));
// Otherwise retrieve on demand ...
else
acFromRef.setEntityDescription(Constructors
.createEntityDescription(getCodeDescription(lbsvc, scheme,
csvt, acRef.getConceptCode())));
AssociatedConceptList acl = assoc.getAssociatedConcepts();
for (AssociatedConcept ac : acl.getAssociatedConcept()) {
// Create reverse association (same non-directional name)
Association rAssoc = new Association();
rAssoc.setAssociationName(assoc.getAssociationName());
// On reverse, old associated concept is new reference point.
ConceptReference ref = new ConceptReference();
//===============================================================================v5.0
//ref.setCodingSchemeName(ac.getCodingSchemeName());
ref.setConceptCode(ac.getConceptCode());
rAssoc.setAssociationReference(ref);
// And old reference is new associated concept.
AssociatedConceptList rAcl = new AssociatedConceptList();
rAcl.addAssociatedConcept(acFromRef);
rAssoc.setAssociatedConcepts(rAcl);
// Set reverse directional name, if available.
String dirName = assoc.getDirectionalName();
if (dirName != null)
try {
rAssoc.setDirectionalName(lbscm.isForwardName(scheme, csvt,
dirName) ? lbscm.getAssociationReverseName(assoc
.getAssociationName(), scheme, csvt) : lbscm
.getAssociationReverseName(assoc
.getAssociationName(), scheme, csvt));
} catch (LBException e) {
}
// Save code desc for future reference when setting up
// concept references in recursive calls ...
codeToEntityDescriptionMap.put(ac.getConceptCode(), ac
.getEntityDescription());
AssociationList sourceOf = ac.getSourceOf();
if (sourceOf != null)
for (Association sourceAssoc : sourceOf.getAssociation()) {
AssociationList pos = reverseAssoc(lbsvc, lbscm, scheme,
csvt, sourceAssoc, addTo,
codeToEntityDescriptionMap, maxLevel, currLevel + 1);
pos.addAssociation(rAssoc);
}
else
addTo.addAssociation(rAssoc);
}
return acSources;
}
public Vector getHierarchyAssociationId(String scheme, String version) {
Vector association_vec = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
// Will handle secured ontologies later.
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(version);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag);
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
for (int k = 0; k < hierarchies.length; k++) {
java.lang.String[] ids = hierarchies[k].getAssociationNames();
for (int i = 0; i < ids.length; i++) {
if (!association_vec.contains(ids[i])) {
association_vec.add(ids[i]);
//System.out.println(ids[i]);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return association_vec;
}
public String getHierarchyAssociationId(String scheme, String version,
int index) {
try {
Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme,
version);
if (hierarchicalAssoName_vec != null
&& hierarchicalAssoName_vec.size() > 0) {
String hierarchicalAssoName = (String) hierarchicalAssoName_vec
.elementAt(0);
return hierarchicalAssoName;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public List getTopNodes(TreeItem ti) {
List list = new ArrayList();
getTopNodes(ti, list, 0, 1);
return list;
}
public void getTopNodes(TreeItem ti, List list, int currLevel, int maxLevel) {
if (list == null)
list = new ArrayList();
if (currLevel > maxLevel)
return;
if (ti.assocToChildMap.keySet().size() > 0) {
if (ti.text.compareTo("Root node") != 0) {
ResolvedConceptReference rcr = new ResolvedConceptReference();
rcr.setConceptCode(ti.code);
EntityDescription entityDescription = new EntityDescription();
entityDescription.setContent(ti.text);
rcr.setEntityDescription(entityDescription);
//System.out.println("Root: " + ti.text);
list.add(rcr);
}
}
for (String association : ti.assocToChildMap.keySet()) {
List<TreeItem> children = ti.assocToChildMap.get(association);
Collections.sort(children);
for (TreeItem childItem : children) {
getTopNodes(childItem, list, currLevel + 1, maxLevel);
}
}
}
public void dumpTree(HashMap hmap, String focusCode, int level) {
try {
Set keyset = hmap.keySet();
Object[] objs = keyset.toArray();
String code = (String) objs[0];
TreeItem ti = (TreeItem) hmap.get(code);
for (String association : ti.assocToChildMap.keySet()) {
System.out.println("\nassociation: " + association);
List<TreeItem> children = ti.assocToChildMap.get(association);
for (TreeItem childItem : children) {
System.out.println(childItem.text + "(" + childItem.code + ")");
int knt = 0;
if (childItem.expandable)
{
knt = 1;
System.out.println("\tnode.expandable");
printTree(childItem, focusCode, level);
List list = getTopNodes(childItem);
for (int i=0; i<list.size(); i++) {
Object obj = list.get(i);
String nd_code = "";
String nd_name = "";
if (obj instanceof ResolvedConceptReference)
{
ResolvedConceptReference node = (ResolvedConceptReference) list.get(i);
nd_code = node.getConceptCode();
nd_name = node.getEntityDescription().getContent();
}
else if (obj instanceof Concept) {
Concept node = (Concept) list.get(i);
nd_code = node.getEntityCode();
nd_name = node.getEntityDescription().getContent();
}
System.out.println("TOP NODE: " + nd_name + " (" + nd_code + ")" );
}
} else {
System.out.println("\tnode.NOT expandable");
}
}
}
} catch (Exception e) {
}
}
//====================================================================================================================
public static String[] getHierarchyIDs(String codingScheme, CodingSchemeVersionOrTag versionOrTag) throws LBException {
String[] hier = null;
Set<String> ids = new HashSet<String>();
SupportedHierarchy[] sh = null;
try {
sh = getSupportedHierarchies(codingScheme, versionOrTag);
if (sh != null)
{
for (int i = 0; i < sh.length; i++)
{
ids.add(sh[i].getLocalId());
}
// Cache and return the new value ...
hier = ids.toArray(new String[ids.size()]);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return hier;
}
protected static SupportedHierarchy[] getSupportedHierarchies(String codingScheme, CodingSchemeVersionOrTag versionOrTag) throws LBException {
CodingScheme cs = null;
try {
cs = getCodingScheme(codingScheme, versionOrTag);
} catch (Exception ex) {
}
if(cs == null){
throw new LBResourceUnavailableException("Coding scheme not found -- " + codingScheme);
}
Mappings mappings = cs.getMappings();
return mappings.getSupportedHierarchy();
}
protected static CodingScheme getCodingScheme(String codingScheme, CodingSchemeVersionOrTag versionOrTag) throws LBException {
CodingScheme cs = null;
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
cs = lbSvc.resolveCodingScheme(codingScheme, versionOrTag);
} catch (Exception ex) {
ex.printStackTrace();
}
return cs;
}
public static String getHierarchyID(String codingScheme, String version) {
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (version != null) versionOrTag.setVersion(version);
try {
String[] ids = getHierarchyIDs(codingScheme, versionOrTag);
if (ids.length > 0) return ids[0];
} catch (Exception e) {
}
return null;
}
public static ResolvedConceptReferenceList getHierarchyRoots(java.lang.String codingScheme, String version) {
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (version != null) versionOrTag.setVersion(version);
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
String hierarchyID = getHierarchyID(codingScheme, version);
return lbscm.getHierarchyRoots(codingScheme, versionOrTag, hierarchyID);
} catch (Exception e) {
return null;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
public void traverseUp(LexBIGService lbsvc,
LexBIGServiceConvenienceMethods lbscm,
java.lang.String codingScheme,
CodingSchemeVersionOrTag versionOrTag,
java.lang.String hierarchyID,
java.lang.String conceptCode,
TreeItem root,
TreeItem ti,
Set<String> codesToExclude,
String[] associationsToNavigate,
boolean associationsNavigatedFwd,
Set<String> visited_links,
HashMap<String, TreeItem> visited_nodes, int maxLevel, int currLevel) {
if (maxLevel != -1 && currLevel >= maxLevel) {
root.addChild("CHD", ti);
root.expandable = true;
return;
}
boolean resolveConcepts = false;
NameAndValueList associationQualifiers = null;
try {
AssociationList list = null;
list = lbscm.getHierarchyLevelPrev(codingScheme, versionOrTag, hierarchyID, conceptCode, resolveConcepts,
associationQualifiers);
int parent_knt = 0;
if (list != null && list.getAssociationCount() > 0) {
Association[] associations = list.getAssociation();
for (int k=0; k<associations.length; k++) {
Association association = associations[k];
AssociatedConceptList acl = association.getAssociatedConcepts();
for (int i = 0; i < acl.getAssociatedConceptCount(); i++) {
//child_knt = child_knt + acl.getAssociatedConceptCount();
// Determine the next concept in the branch and
// add a corresponding item to the tree.
AssociatedConcept concept = acl.getAssociatedConcept(i);
String parentCode = concept.getConceptCode();
String link = conceptCode + "|" + parentCode;
if (!visited_links.contains(link)) {
visited_links.add(link);
//System.out.println( getCodeDescription(concept) + "(" + parentCode + ")");
TreeItem branchItem = null;
if (visited_nodes.containsKey(parentCode)) {
branchItem = (TreeItem) visited_nodes.get(parentCode);
} else {
branchItem = new TreeItem(parentCode, getCodeDescription(concept));
branchItem.expandable = false;
visited_nodes.put(parentCode, branchItem);
}
try {
codesToExclude.add(conceptCode);
addChildren(branchItem, lbsvc,
lbscm, codingScheme,
versionOrTag,
parentCode,
codesToExclude,
associationsToNavigate,
associationsNavigatedFwd);
} catch (Exception ex) {
}
branchItem.addChild("CHD", ti);
parent_knt++;
//ti.addChild("PAR", branchItem);
branchItem.expandable = true;
traverseUp(lbsvc, lbscm, codingScheme, versionOrTag, hierarchyID, parentCode, root, branchItem, codesToExclude,
associationsToNavigate, associationsNavigatedFwd, visited_links, visited_nodes, maxLevel, currLevel+1);
}
}
}
}
if (parent_knt == 0) {
root.addChild("CHD", ti);
root.expandable = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public HashMap getTreePathData2(String scheme, String version, String code, int maxLevel) {
HashMap hmap = new HashMap();
TreeItem root = new TreeItem("<Root>", "Root node");
root.expandable = false;
long ms = System.currentTimeMillis();
Set<String> codesToExclude = new HashSet<String>();
HashMap<String, TreeItem> visited_nodes = new HashMap<String, TreeItem>();
Set<String> visited_links = new HashSet<String>();
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (version != null) versionOrTag.setVersion(version);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
if (cs == null) return null;
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
if (hierarchies == null || hierarchies.length == 0) return null;
SupportedHierarchy hierarchyDefn = hierarchies[0];
String hierarchyID = hierarchyDefn.getLocalId();
String[] associationsToNavigate = hierarchyDefn.getAssociationNames();
boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable();
String name = getCodeDescription(lbSvc, scheme, csvt, code);
TreeItem ti = new TreeItem(code, name);
//ti.expandable = false;
ti.expandable = hasSubconcepts(scheme, version, code);
System.out.println(name + "(" + code + ")");
traverseUp(lbSvc, lbscm, scheme, csvt, hierarchyID, code, root, ti, codesToExclude, associationsToNavigate, associationsNavigatedFwd, visited_links, visited_nodes, maxLevel, 0);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms) + " to resolve "
//+ pathsResolved + " paths from root.");
+ " paths from root.");
}
hmap.put(code, root);
return hmap;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
String url = "http://lexevsapi-dev.nci.nih.gov/lexevsapi42";
url = "http://lexevsapi-qa.nci.nih.gov/lexevsapi50";
HashMap hmap = null;
String scheme = "NCI Thesaurus";
String version = null;
String code = "C26709";
TreeUtils test = new TreeUtils();
//hmap = test.getSubconcepts(scheme, version, code);
//test.printTree(hmap);
code = "C2910";
code = "C9335";
String hierarchyID = test.getHierarchyID(scheme, null);
System.out.println("(*) " + scheme + " Hierarchy ID: " + hierarchyID);
hmap = test.getSubconcepts(scheme, version, code);
test.printTree(hmap);
System.out.println("=============================================================");
scheme = "Gene Ontology";
code = "GO:0008150";
hierarchyID = test.getHierarchyID(scheme, null);
System.out.println("Hierarchy ID: " + hierarchyID);
hmap = test.getSubconcepts(scheme, version, code);
test.printTree(hmap);
System.out.println("=============================================================");
scheme = "HL7 Reference Information Model ";
code = "AcknowledgementType";
hierarchyID = test.getHierarchyID(scheme, null);
System.out.println("Hierarchy ID: " + hierarchyID);
hmap = test.getSubconcepts(scheme, version, code);
test.printTree(hmap);
}
}
| GF#23365 [KLO, 111009]
git-svn-id: 8a910031c78bbe8a754298bb28800c1494820db3@939 0604bb77-1110-461e-859e-28c50bf9b280
| software/ncitbrowser/src/java/gov/nih/nci/evs/browser/utils/TreeUtils.java | GF#23365 [KLO, 111009] |
|
Java | bsd-3-clause | 0b174f8153a935c2945d10366eb848786e47a825 | 0 | frc-88/2014-Robot | package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.PIDOutput;
import edu.wpi.first.wpilibj.PIDSource;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* @author TJ^2 Programming Team
*/
public class JagPair implements PIDOutput {
private static final double P_DEFAULT = .05;
private static final double I_DEFAULT = 0.0;
private static final double D_DEFAULT = 0.0;
private static final double f = 0.2;
private static final double CYCLE_TIME = .020;
private static final int DRIVE_ENCODER_LINES = 250;
private static final double FEET_PER_REVOLUTION = 1.57;
//feet per revolution over encoder lines
private static final double DISTANCE_PER_PULSE = FEET_PER_REVOLUTION / DRIVE_ENCODER_LINES;
private static final int SAMPLES_TO_AVERAGE = 6;
private static final double RAMP_RATE = 0.1;
private static final double MAX_SPEED_HIGH_GEAR = 12.4; // feet per second
private static final double MAX_SPEED_LOW_GEAR = 5.2; // feet per second
private final Jaguar jag1, jag2;
private final Encoder encoder;
private final String name;
private PIDController controller;
private boolean m_closedLoop = false;
// We never set m_fault...can we remove it?
private boolean m_fault = false;
private double last_speed = 0.0;
public JagPair(String nameIn, int jag1In, int jag2In, int encoderA, int encoderB) {
name = nameIn;
jag1 = new Jaguar(jag1In);
jag2 = new Jaguar(jag2In);
encoder = new Encoder(encoderA, encoderB);
encoder.setDistancePerPulse(DISTANCE_PER_PULSE);
encoder.setSamplesToAverage(SAMPLES_TO_AVERAGE);
encoder.setPIDSourceParameter(PIDSource.PIDSourceParameter.kRate);
encoder.reset();
encoder.start();
}
/**
* Enables ClosedLoop control Driving. It sets it to speed.
*/
public void enableClosedLoop() {
enableClosedLoop(P_DEFAULT, I_DEFAULT, D_DEFAULT);
}
public void enableClosedLoop(double p, double i, double d) {
if (m_closedLoop) {
System.out.println(name + " closed loop already enabled!");
} else {
// set the motors to closed loop
//may be percent v bus
controller = new PIDController(p, i, d, f, encoder, this, CYCLE_TIME);
// set the enable flag
m_closedLoop = true;
controller.enable();
System.out.println(name + " closed loop enabled.");
}
}
/**
* Disables the Drive closed loop and puts it into open loop.
*/
public void disableClosedLoop() {
if (!m_closedLoop) {
System.out.println(name + " closed loop already disabled!");
} else {
// set the enable flag to false
m_closedLoop = false;
controller.disable();
System.out.println(name + " closed loop disabled.");
}
}
/**
* Returns the value of the fault flag
* @return true if there is a fault
*/
public boolean getFault() {
return m_fault;
}
/**
* Drives the robot in open loop
*
* @param x usually joystick value passed in
*/
public void setX(double x) {
SmartDashboard.putNumber(name + " speed requested", x);
x = applyRampRate(x);
SmartDashboard.putNumber(name + " speed adjusted", x);
jag1.set(x);
jag2.set(x);
}
/**
* Drives the robot in closed loop
*
* @param speedIn usually joystick value passed in
* @param isHighGear true if in high gear
*/
public void setSpeed(double speedIn, boolean isHighGear) {
double maxSpeed = isHighGear ? MAX_SPEED_HIGH_GEAR : MAX_SPEED_LOW_GEAR;
double speed = applyRampRate(speedIn);
speed = speed * maxSpeed;
SmartDashboard.putNumber(name + " speed requested ", speedIn);
SmartDashboard.putNumber(name + " speed actual ", getSpeed());
SmartDashboard.putNumber(name + " new setpoint ", speed);
controller.setSetpoint(speed);
}
private double applyRampRate(double speed) {
if(speed - last_speed > RAMP_RATE) {
speed = last_speed + RAMP_RATE;
} else if(speed - last_speed < -RAMP_RATE) {
speed = last_speed - RAMP_RATE;
}
last_speed = speed;
return speed;
}
/**
* @return speed of wheels
*/
public double getSpeed() {
return encoder.getRate();
}
public double getDistance() {
return encoder.getDistance();
}
/**
* Reset the encoders to 0
*/
public void resetDistance() {
encoder.reset();
}
public void pidWrite(double output) {
jag1.pidWrite(output);
jag2.pidWrite(output);
}
}
| src/edu/wpi/first/wpilibj/templates/JagPair.java | package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.PIDOutput;
import edu.wpi.first.wpilibj.PIDSource;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* @author TJ^2 Programming Team
*/
public class JagPair implements PIDOutput {
private static final double P_DEFAULT = .05;
private static final double I_DEFAULT = 0.0;
private static final double D_DEFAULT = 0.0;
private static final double f = 0.2;
private static final double CYCLE_TIME = .020;
private static final int DRIVE_ENCODER_LINES = 250;
private static final double FEET_PER_REVOLUTION = 1.57;
//feet per revolution over encoder lines
private static final double DISTANCE_PER_PULSE = FEET_PER_REVOLUTION / DRIVE_ENCODER_LINES;
private static final double RAMP_RATE = 0.1;
private Jaguar jag1, jag2;
private Encoder encoder;
private PIDController controller;
private String name;
private boolean m_closedLoop = false;
private boolean m_fault = false;
private double last_speed = 0.0;
public JagPair(String nameIn, int jag1In, int jag2In, int encoderA, int encoderB) {
name = nameIn;
jag1 = new Jaguar(jag1In);
jag2 = new Jaguar(jag2In);
encoder = new Encoder(encoderA, encoderB);
encoder.setDistancePerPulse(DISTANCE_PER_PULSE);
encoder.setSamplesToAverage(6);
encoder.setPIDSourceParameter(PIDSource.PIDSourceParameter.kRate);
encoder.reset();
encoder.start();
}
/**
* Enables ClosedLoop control Driving. It sets it to speed.
*/
public void enableClosedLoop() {
enableClosedLoop(P_DEFAULT, I_DEFAULT, D_DEFAULT);
}
public void enableClosedLoop(double p, double i, double d) {
if (m_closedLoop) {
System.out.println(name + " closed loop already enabled!");
} else {
// set the motors to closed loop
//may be percent v bus
controller = new PIDController(p, i, d, f, encoder, this, CYCLE_TIME);
// set the enable flag
m_closedLoop = true;
controller.enable();
System.out.println(name + " closed loop enabled.");
}
}
/**
* Disables the Drive closed loop and puts it into open loop.
*/
public void disableClosedLoop() {
if (!m_closedLoop) {
System.out.println(name + " closed loop already disabled!");
} else {
// set the enable flag to false
m_closedLoop = false;
controller.disable();
System.out.println(name + " closed loop disabled.");
}
}
/**
* Returns the value of the fault flag
*/
public boolean getFault() {
return m_fault;
}
public void setX(double x) {
SmartDashboard.putNumber(name + " speed requested", x);
x = applyRampRate(x);
SmartDashboard.putNumber(name + " speed adjusted", x);
jag1.set(x);
jag2.set(x);
}
/**
* Drives the robot in closed loop
*
* @param speed usually joystick value passed in
*/
public void setSpeed(double speedIn, boolean isHighGear) {
double maxSpeedHighGear = 12.4; // feet per second
double maxSpeedLowGear = 5.2; // feet per second
double maxSpeed;
double speed;
if (isHighGear) {
maxSpeed = maxSpeedHighGear;
} else {
maxSpeed = maxSpeedLowGear;
}
speed = applyRampRate(speedIn);
speed = speed * maxSpeed;
SmartDashboard.putNumber(name + " speed requested ", speedIn);
SmartDashboard.putNumber(name + " speed actual ", getSpeed());
SmartDashboard.putNumber(name + " new setpoint ", speed);
controller.setSetpoint(speed);
}
private double applyRampRate(double speed) {
if(speed - last_speed > RAMP_RATE) {
speed = last_speed + RAMP_RATE;
} else if(speed - last_speed < -RAMP_RATE) {
speed = last_speed - RAMP_RATE;
}
last_speed = speed;
return speed;
}
/**
* @returns speed of wheels
*/
public double getSpeed() {
return encoder.getRate();
}
public double getDistance() {
return encoder.getDistance();
}
/**
* Reset the encoders to 0
*/
public void resetDistance() {
encoder.reset();
}
public void pidWrite(double output) {
jag1.pidWrite(output);
jag2.pidWrite(output);
}
}
| Clean JagPair | src/edu/wpi/first/wpilibj/templates/JagPair.java | Clean JagPair |
|
Java | bsd-3-clause | 6a138d83f302308c2c5f0acac1e00a6878256a85 | 0 | APNIC-net/whois,APNIC-net/whois,APNIC-net/whois | package net.ripe.db.whois.update.handler;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.ripe.db.whois.common.DateTimeProvider;
import net.ripe.db.whois.common.dao.RpslObjectUpdateDao;
import net.ripe.db.whois.common.domain.attrs.Changed;
import net.ripe.db.whois.common.rpsl.AttributeType;
import net.ripe.db.whois.common.rpsl.ObjectType;
import net.ripe.db.whois.common.rpsl.RpslAttribute;
import net.ripe.db.whois.common.rpsl.RpslObject;
import net.ripe.db.whois.update.domain.Action;
import net.ripe.db.whois.update.domain.PreparedUpdate;
import net.ripe.db.whois.update.domain.UpdateContext;
import net.ripe.db.whois.update.domain.UpdateMessages;
import net.ripe.db.whois.update.handler.validator.BusinessRuleValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
@Component
class UpdateObjectHandlerImpl implements UpdateObjectHandler {
private final DateTimeProvider dateTimeProvider;
private final RpslObjectUpdateDao rpslObjectUpdateDao;
private final Map<Action, Map<ObjectType, List<BusinessRuleValidator>>> validatorsByActionAndType;
@Autowired
public UpdateObjectHandlerImpl(final RpslObjectUpdateDao rpslObjectUpdateDao, final List<BusinessRuleValidator> businessRuleValidators,
final DateTimeProvider dateTimeProvider) {
// Sort the business rules in some predictable order so they are processed for end-to-end error checking
Collections.sort(businessRuleValidators, new Comparator<BusinessRuleValidator>(){
public int compare(BusinessRuleValidator b1, BusinessRuleValidator b2) {
return b1.getClass().getName().compareToIgnoreCase(b2.getClass().getName());
}
});
this.rpslObjectUpdateDao = rpslObjectUpdateDao;
this.dateTimeProvider = dateTimeProvider;
validatorsByActionAndType = Maps.newEnumMap(Action.class);
for (final Action action : Action.values()) {
final Map<ObjectType, List<BusinessRuleValidator>> validatorsByType = Maps.newEnumMap(ObjectType.class);
for (final ObjectType objectType : ObjectType.values()) {
validatorsByType.put(objectType, Lists.<BusinessRuleValidator>newArrayList());
}
validatorsByActionAndType.put(action, validatorsByType);
}
for (final BusinessRuleValidator businessRuleValidator : businessRuleValidators) {
final List<Action> actions = businessRuleValidator.getActions();
for (final Action action : actions) {
for (final ObjectType objectType : businessRuleValidator.getTypes()) {
validatorsByActionAndType.get(action).get(objectType).add(businessRuleValidator);
}
}
}
}
RpslObject updateLastChangedAttribute(final RpslObject submittedObject) {
final List<RpslAttribute> attributes = submittedObject.findAttributes(AttributeType.CHANGED);
if (attributes.isEmpty()) {
return submittedObject;
}
final RpslAttribute attributeToUpdate = getChangedAttributeToUpdate(attributes);
if (attributeToUpdate == null) {
return submittedObject;
}
final ArrayList<RpslAttribute> rpslAttributes = Lists.newArrayList(submittedObject.getAttributes());
final Changed newAttributeValue = new Changed(attributeToUpdate.getCleanValue(), dateTimeProvider.getCurrentDate());
rpslAttributes.set(rpslAttributes.indexOf(attributeToUpdate), new RpslAttribute(AttributeType.CHANGED, newAttributeValue.toString()));
return new RpslObject(submittedObject, rpslAttributes);
}
private RpslAttribute getChangedAttributeToUpdate(final List<RpslAttribute> attributes) {
for (final RpslAttribute attribute : attributes) {
final Changed changed = Changed.parse(attribute.getCleanValue());
if (changed.getDate() == null) {
return attribute;
}
}
return null;
}
@Override
@Transactional(propagation = Propagation.MANDATORY)
public void execute(final PreparedUpdate update, final UpdateContext updateContext) {
if (isValid(update, updateContext)) {
switch (update.getAction()) {
case CREATE:
rpslObjectUpdateDao.createObject(updateLastChangedAttribute(update.getUpdatedObject()));
break;
case MODIFY:
rpslObjectUpdateDao.updateObject(update.getReferenceObject().getObjectId(), updateLastChangedAttribute(update.getUpdatedObject()));
break;
case DELETE:
final RpslObject object = update.getReferenceObject();
rpslObjectUpdateDao.deleteObject(object.getObjectId(), object.getKey().toString());
break;
case NOOP:
updateContext.addMessage(update, UpdateMessages.updateIsIdentical());
break;
default:
throw new IllegalStateException("Unhandled action: " + update.getAction());
}
}
}
private boolean isValid(final PreparedUpdate update, final UpdateContext updateContext) {
for (final BusinessRuleValidator businessRuleValidator : validatorsByActionAndType.get(update.getAction()).get(update.getType())) {
businessRuleValidator.validate(update, updateContext);
}
return !updateContext.hasErrors(update);
}
}
| whois-update/src/main/java/net/ripe/db/whois/update/handler/UpdateObjectHandlerImpl.java | package net.ripe.db.whois.update.handler;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.ripe.db.whois.common.DateTimeProvider;
import net.ripe.db.whois.common.dao.RpslObjectUpdateDao;
import net.ripe.db.whois.common.domain.attrs.Changed;
import net.ripe.db.whois.common.rpsl.AttributeType;
import net.ripe.db.whois.common.rpsl.ObjectType;
import net.ripe.db.whois.common.rpsl.RpslAttribute;
import net.ripe.db.whois.common.rpsl.RpslObject;
import net.ripe.db.whois.update.domain.Action;
import net.ripe.db.whois.update.domain.PreparedUpdate;
import net.ripe.db.whois.update.domain.UpdateContext;
import net.ripe.db.whois.update.domain.UpdateMessages;
import net.ripe.db.whois.update.handler.validator.BusinessRuleValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
@Component
class UpdateObjectHandlerImpl implements UpdateObjectHandler {
private final DateTimeProvider dateTimeProvider;
private final RpslObjectUpdateDao rpslObjectUpdateDao;
private final Map<Action, Map<ObjectType, List<BusinessRuleValidator>>> validatorsByActionAndType;
@Autowired
public UpdateObjectHandlerImpl(final RpslObjectUpdateDao rpslObjectUpdateDao, final List<BusinessRuleValidator> businessRuleValidators,
final DateTimeProvider dateTimeProvider) {
// Sort the business rules in some predictable order so they are processed for end-to-end error checking
Collections.sort(businessRuleValidators, new Comparator<BusinessRuleValidator>(){
public int compare(BusinessRuleValidator b1, BusinessRuleValidator b2) {
return b1.getClass().getName().compareToIgnoreCase(b2.getClass().getName());
}
});
this.rpslObjectUpdateDao = rpslObjectUpdateDao;
this.dateTimeProvider = dateTimeProvider;
validatorsByActionAndType = Maps.newEnumMap(Action.class);
for (final Action action : Action.values()) {
final Map<ObjectType, List<BusinessRuleValidator>> validatorsByType = Maps.newEnumMap(ObjectType.class);
for (final ObjectType objectType : ObjectType.values()) {
validatorsByType.put(objectType, Lists.<BusinessRuleValidator>newArrayList());
}
validatorsByActionAndType.put(action, validatorsByType);
}
for (final BusinessRuleValidator businessRuleValidator : businessRuleValidators) {
final List<Action> actions = businessRuleValidator.getActions();
for (final Action action : actions) {
for (final ObjectType objectType : businessRuleValidator.getTypes()) {
validatorsByActionAndType.get(action).get(objectType).add(businessRuleValidator);
}
}
}
}
RpslObject updateLastChangedAttribute(final RpslObject submittedObject) {
final List<RpslAttribute> attributes = submittedObject.findAttributes(AttributeType.CHANGED);
if (attributes.isEmpty()) {
return submittedObject;
}
final RpslAttribute attributeToUpdate = getChangedAttributeToUpdate(attributes);
if (attributeToUpdate == null) {
return submittedObject;
}
final ArrayList<RpslAttribute> rpslAttributes = Lists.newArrayList(submittedObject.getAttributes());
final Changed newAttributeValue = new Changed(attributeToUpdate.getCleanValue(), dateTimeProvider.getCurrentDate());
rpslAttributes.set(rpslAttributes.indexOf(attributeToUpdate), new RpslAttribute(AttributeType.CHANGED, newAttributeValue.toString()));
return new RpslObject(submittedObject, rpslAttributes);
}
private RpslAttribute getChangedAttributeToUpdate(final List<RpslAttribute> attributes) {
for (final RpslAttribute attribute : attributes) {
final Changed changed = Changed.parse(attribute.getCleanValue());
if (changed.getDate() == null) {
return attribute;
}
}
return null;
}
@Override
@Transactional(propagation = Propagation.MANDATORY)
public void execute(final PreparedUpdate update, final UpdateContext updateContext) {
if (isValid(update, updateContext)) {
switch (update.getAction()) {
case CREATE:
rpslObjectUpdateDao.createObject(updateLastChangedAttribute(update.getUpdatedObject()));
break;
case MODIFY:
rpslObjectUpdateDao.updateObject(update.getReferenceObject().getObjectId(), updateLastChangedAttribute(update.getUpdatedObject()));
break;
case DELETE:
final RpslObject object = update.getReferenceObject();
rpslObjectUpdateDao.deleteObject(object.getObjectId(), object.getKey().toString());
break;
case NOOP:
updateContext.addMessage(update, UpdateMessages.updateIsIdentical());
break;
default:
throw new IllegalStateException("Unhandled action: " + update.getAction());
}
}
}
private boolean isValid(final PreparedUpdate update, final UpdateContext updateContext) {
for (final BusinessRuleValidator businessRuleValidator : validatorsByActionAndType.get(update.getAction()).get(update.getType())) {
businessRuleValidator.validate(update, updateContext);
}
return !updateContext.hasErrors(update);
}
}
| Fix for "out of sequence" error message checking on a few end-to-end tests (only seems to affect linux and windows)
| whois-update/src/main/java/net/ripe/db/whois/update/handler/UpdateObjectHandlerImpl.java | Fix for "out of sequence" error message checking on a few end-to-end tests (only seems to affect linux and windows) |
|
Java | mit | c71258ee3692d6729b4fde36554a02485ac5aefb | 0 | berryma4/diirt,diirt/diirt,diirt/diirt,diirt/diirt,berryma4/diirt,richardfearn/diirt,richardfearn/diirt,berryma4/diirt,ControlSystemStudio/diirt,ControlSystemStudio/diirt,ControlSystemStudio/diirt,ControlSystemStudio/diirt,richardfearn/diirt,berryma4/diirt,diirt/diirt | /**
* Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.diirt.pods.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Entry point for all configuration in diirt.
* <p>
* The configuration directory used is given by:
* <ul>
* <li>The Java property <b>diirt.home</b> if set. It can either be
* set when creating the JVM using -D or programmatically using
* <code>System.setProperty</code>. When set programmatically, one
* must make sure that it is set before any call to {@link #configurationDirectory()},
* since the property is only read once and then cached.</li>
* <li>The environment variable <b>DIIRT_HOME</b> if set.</li>
* <li>The default <b>$USER_HOME/.diirt</b></li>
* </ul>
*
* @author carcassi
*/
public class Configuration {
private static Logger log = Logger.getLogger(Configuration.class.getName());
private static final File configurationDirectory = configurationDirectory();
private static File configurationDirectory() {
// First look for java property
String diirtHome = System.getProperty("diirt.home");
// Second look for environment variable
if (diirtHome == null) {
diirtHome = System.getenv("DIIRT_HOME");
}
File dir;
if (diirtHome != null) {
dir = new File(diirtHome);
} else {
// Third use default in home directory
dir = new File(System.getProperty("user.home"), ".diirt");
}
dir.mkdirs();
return dir;
}
public static File getDirectory() {
return configurationDirectory;
}
public static InputStream getFileAsStream(String relativeFilePath, Object obj, String defaultResource) throws IOException {
File mappings = new File(Configuration.getDirectory(), relativeFilePath);
if (!mappings.exists()) {
try (InputStream input = obj.getClass().getResourceAsStream(defaultResource);
OutputStream output = new FileOutputStream(mappings)) {
byte[] buffer = new byte[8 * 1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
log.log(Level.INFO, "Initializing configuration file " + mappings);
}
log.log(Level.INFO, "Loading " + mappings);
return new FileInputStream(mappings);
}
}
| pods-common/src/main/java/org/diirt/pods/common/Configuration.java | /**
* Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.diirt.pods.common;
import java.io.File;
/**
* Entry point for all configuration in diirt.
* <p>
* The configuration directory used is given by:
* <ul>
* <li>The Java property <b>diirt.home</b> if set. It can either be
* set when creating the JVM using -D or programmatically using
* <code>System.setProperty</code>. When set programmatically, one
* must make sure that it is set before any call to {@link #configurationDirectory()},
* since the property is only read once and then cached.</li>
* <li>The environment variable <b>DIIRT_HOME</b> if set.</li>
* <li>The default <b>$USER_HOME/.diirt</b></li>
* </ul>
*
* @author carcassi
*/
public class Configuration {
private static final File configurationDirectory = configurationDirectory();
private static File configurationDirectory() {
// First look for java property
String diirtHome = System.getProperty("diirt.home");
// Second look for environment variable
if (diirtHome == null) {
diirtHome = System.getenv("DIIRT_HOME");
}
File dir;
if (diirtHome != null) {
dir = new File(diirtHome);
} else {
// Third use default in home directory
dir = new File(System.getProperty("user.home"), ".diirt");
}
dir.mkdirs();
return dir;
}
public static File getDirectory() {
return configurationDirectory;
}
}
| pods-common: added logic to initialize configuration file with default. | pods-common/src/main/java/org/diirt/pods/common/Configuration.java | pods-common: added logic to initialize configuration file with default. |
|
Java | mit | afc61b976cd77c83c5f886156928262b7fd26448 | 0 | s4ke/moar | /*
The MIT License (MIT)
Copyright (c) 2016 Martin Braun
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.github.s4ke.moar.regex;
import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import com.github.s4ke.moar.MoaMatcher;
import com.github.s4ke.moar.MoaPattern;
import com.github.s4ke.moar.NonDeterministicException;
import com.github.s4ke.moar.moa.Moa;
import com.github.s4ke.moar.regex.parser.RegexLexer;
import com.github.s4ke.moar.regex.parser.RegexParser;
import com.github.s4ke.moar.regex.parser.RegexTreeListener;
import com.github.s4ke.moar.strings.EfficientString;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.junit.Assert;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Martin Braun
*/
public class ParserTest {
@Test
public void test() {
MoaPattern pattern = MoaPattern.compile( "^Deterministic|OrNot$" );
MoaMatcher matcher = pattern.matcher( "Deterministic" );
assertTrue( matcher.nextMatch() );
assertTrue( matcher.matches() );
}
@Test
public void testTusker() {
//from: http://tusker.org/regex/regex_benchmark.html
//adapted the syntax though
//FIXME: fix syntax of our regexes to be more compatible?
//or just throw out the PCRE syntax alltogether in favour
//of a more readable alternative
{
Regex regex = parseRegex( "^(([^:]+)://)?([^:/]+)(:([0-9]+))?(/.*)" );
TestUtil.assertNonDet( regex );
}
{
//this is non deterministic (see the start)
Regex regex = parseRegex( "(([^:]+)://)?([^:/]+)(:([0-9]+))?(/.*)" );
TestUtil.assertNonDet( regex );
}
{
//the original has this bounded by word: \\b(\\w+)(\\s+\\1)+\\b
//this is non deterministic by our current definition
Regex regex = parseRegex( "(\\w+)(\\s+\\1)+" );
TestUtil.assertNonDet( regex );
}
{
//adapted the [+-] to [\\+\\-] (our ANTLR grammar is not that clever
//we also treat the dot as the any metachar.
Regex regex = parseRegex( "usd [\\+\\-]?[0-9]+\\.[0-9][0-9]" );
TestUtil.assertDet( regex );
Moa moa = regex.toMoa();
TestUtil.assertMatch( true, moa, "usd 1234.00" );
TestUtil.assertMatch( true, moa, "usd +1234.00" );
TestUtil.assertMatch( true, moa, "usd -1234.00" );
TestUtil.assertMatch( true, moa, "usd 1.00" );
TestUtil.assertMatch( true, moa, "usd +1.00" );
TestUtil.assertMatch( true, moa, "usd -1.00" );
TestUtil.assertMatch( false, moa, "1234.00" );
TestUtil.assertMatch( false, moa, "usd .00" );
TestUtil.assertMatch( false, moa, "usd +.00" );
TestUtil.assertMatch( false, moa, "usd -.00" );
TestUtil.assertMatch( false, moa, "usd 1." );
}
}
@Test
public void testTooHarshDeterminism() {
//these were wrongly identified as non deterministic
//but this was only wrong for non matching groups
TestUtil.assertDet( parseRegex( "(?:)|(?:)" ) );
TestUtil.assertNonDet( parseRegex( "()|()" ) );
TestUtil.assertDet( parseRegex( "(?:a+)+" ) );
TestUtil.assertNonDet( parseRegex( "(a+)+" ) );
TestUtil.assertDet( parseRegex( "(?:a|(?:))+" ) );
TestUtil.assertNonDet( parseRegex( "(a|())+" ) );
}
@Test
public void testCaret() {
Moa moa = parseRegex( "^a" ).toMoa();
assertMatch( true, moa, "a" );
{
String tmp = "aa";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
assertEquals( 1, cnt );
}
for ( EfficientString eff : BoundConstants.LINE_BREAK_CHARS ) {
String tmp = "a" + eff.toString() + "a";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
assertEquals( 2, cnt );
}
}
@Test
public void testDollar() {
Moa moa = parseRegex( "a$" ).toMoa();
assertMatch( true, moa, "a" );
for ( EfficientString eff : BoundConstants.LINE_BREAK_CHARS ) {
String tmp = "a" + eff.toString() + "ab";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
Assert.assertEquals( 1, cnt );
}
}
@Test
public void testEndOfLastMatch() {
Moa moa = parseRegex( "\\Ga" ).toMoa();
assertTrue( moa.check( "a" ) );
{
String tmp = "aa";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
Assert.assertEquals( 2, cnt );
}
{
String tmp = "a a";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
Assert.assertEquals( 1, cnt );
}
}
@Test
public void testEndOfInput() {
Moa moa = parseRegex( "a\\z" ).toMoa();
assertTrue( moa.check( "a" ) );
{
String tmp = "aa";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
Assert.assertEquals( 1, cnt );
}
}
@Test
public void testCaretAndDollar() {
Moa moa = parseRegex( "^a$" ).toMoa();
assertTrue( moa.check( "a" ) );
for ( EfficientString eff : BoundConstants.LINE_BREAK_CHARS ) {
String tmp = "a" + eff.toString() + "a";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
assertEquals( 2, cnt );
}
}
@Test
public void testUTF32() {
Moa moa;
{
int[] codePoints = "someStuff~\uD801\uDC28~someOtherStuff".codePoints().toArray();
moa = parseRegex( new String( codePoints, 0, codePoints.length ) ).toMoa();
}
{
int[] codePoints = "someStuff\uD801\uDC28someOtherStuff".codePoints().toArray();
assertMatch( true, moa, new String( codePoints, 0, codePoints.length ) );
}
}
@Test
public void testSingleChar() {
Regex regex = parseRegex( "a" );
assertMatch( true, regex, "a" );
assertMatch( false, regex, "b" );
assertMatch( false, regex, "" );
}
@Test
public void testSimpleConcat() {
Regex regex = parseRegex( "abc" );
Moa moa = regex.toMoa();
assertTrue( moa.check( "abc" ) );
assertFalse( moa.check( "ab" ) );
}
@Test
public void testSimpleOr() {
Regex regex = parseRegex( "a|b" );
assertMatch( true, regex, "a" );
assertMatch( true, regex, "b" );
assertMatch( false, regex, "c" );
assertMatch( false, regex, "" );
}
@Test
public void testSimpleGroup() {
Regex regex = parseRegex( "(a)" );
Moa moa = regex.toMoa();
assertTrue( moa.check( "a" ) );
{
MoaMatcher matcher = moa.matcher( "a" );
assertTrue( matcher.nextMatch() );
assertTrue( matcher.matches() );
assertEquals( "a", matcher.getVariableContent( 1 ) );
assertEquals( "a", matcher.getVariableContent( "1" ) );
}
}
@Test
public void testSimplePositiveSet() {
Regex regex = parseRegex( "[abc]" );
assertMatch( true, regex, "a" );
assertMatch( true, regex, "b" );
assertMatch( true, regex, "c" );
assertMatch( false, regex, "d" );
assertMatch( false, regex, "" );
}
@Test
public void testAStarBStarStar() {
Regex regex = parseRegex( "(?:a*b*)*" );
TestUtil.assertDet( regex );
}
@Test
public void testRangePositiveSet() {
Moa moa = parseRegex( "[ac-zAC-Z]" ).toMoa();
for ( char c = 'a'; c <= 'z'; ++c ) {
if ( c == 'b' ) {
assertMatch( false, moa, String.valueOf( c ) );
}
else {
assertMatch( true, moa, String.valueOf( c ) );
}
}
for ( char c = 'A'; c <= 'Z'; ++c ) {
if ( c == 'B' ) {
assertMatch( false, moa, String.valueOf( c ) );
}
else {
assertMatch( true, moa, String.valueOf( c ) );
}
}
assertMatch( false, moa, "!" );
}
@Test
public void testRangeNegativeset() {
//reuse this, the non-determinism check is quite expensive if a set
//is used
Moa moa = parseRegex( "[^a]" ).toMoa();
for ( int i = 0; i <= Character.MAX_VALUE; ++i ) {
if ( i == 'a' ) {
assertMatch( false, moa, String.valueOf( (char) i ) );
}
else {
assertMatch( true, moa, String.valueOf( (char) i ) );
}
}
}
@Test
public void testNumericalRegex() {
Moa moa = parseRegex( "1" ).toMoa();
assertMatch( true, moa, "1" );
}
@Test
public void testBackRefIndexed() {
Moa moa = parseRegex( "(a*)b\\1" ).toMoa();
assertMatch( false, moa, "ab" );
assertMatch( true, moa, "aba" );
assertMatch( false, moa, "aaba" );
assertMatch( false, moa, "abaa" );
assertMatch( true, moa, "aabaa" );
}
@Test
public void testBackRefNamed() {
Moa moa = parseRegex( "(?<zA1>a*)b\\k<zA1>" ).toMoa();
assertMatch( false, moa, "ab" );
assertMatch( true, moa, "aba" );
assertMatch( false, moa, "aaba" );
assertMatch( false, moa, "abaa" );
assertMatch( true, moa, "aabaa" );
}
@Test
public void testNonCapturingGroup() {
Moa moa = parseRegex( "(?:ab|d)*c" ).toMoa();
assertMatch( true, moa, "c" );
assertMatch( true, moa, "abc" );
assertMatch( true, moa, "ababc" );
assertMatch( true, moa, "abdabc" );
}
@Test
public void testEscapeSimple() {
Regex regex = parseRegex( "\\^" );
assertMatch( true, regex, "^" );
}
@Test
public void testEscapeBackslash() {
Regex regex = parseRegex( "\\\\" );
assertMatch( true, regex, "\\" );
}
@Test
public void testOrNothing() {
Moa moa = parseRegex( "a?" ).toMoa();
assertMatch( true, moa, "" );
assertMatch( true, moa, "a" );
assertMatch( false, moa, "b" );
}
@Test
public void testPrecedenceAndOr() {
Regex regex = parseRegex( "ab|bcd" );
Moa moa = regex.toMoa();
assertMatch( true, moa, "ab" );
assertMatch( true, moa, "bcd" );
assertMatch( false, moa, "abbcd" );
}
@Test
public void testEpsilon() {
Moa moa = parseRegex( "" ).toMoa();
assertMatch( true, moa, "" );
assertMatch( false, moa, "a" );
}
@Test
public void testWhitespace() {
Moa moa = parseRegex( "\\s" ).toMoa();
assertMatch( true, moa, " " );
assertMatch( false, moa, "a" );
assertMatch( false, moa, "" );
}
@Test
public void testNonWhitespace() {
Moa moa = parseRegex( "\\S" ).toMoa();
assertMatch( false, moa, " " );
assertMatch( true, moa, "a" );
assertMatch( false, moa, "" );
}
@Test
public void testEmail() {
Moa moa = parseRegex( "\\w+@\\w\\w+\\.\\w\\w+" ).toMoa();
assertMatch( true, moa, "[email protected]" );
assertMatch( false, moa, "test.com" );
}
@Test
public void testWordCharacter() {
Moa moa = parseRegex( "\\w" ).toMoa();
assertMatch( false, moa, " " );
assertMatch( true, moa, "a" );
assertMatch( false, moa, "" );
}
@Test
public void testNonWordCharacter() {
Moa moa = parseRegex( "\\W" ).toMoa();
assertMatch( true, moa, " " );
assertMatch( false, moa, "a" );
assertMatch( false, moa, "" );
}
@Test
public void testNumeric() {
Moa moa = parseRegex( "\\d" ).toMoa();
assertMatch( true, moa, "1" );
assertMatch( false, moa, "a" );
assertMatch( false, moa, "" );
}
@Test
public void testNonNumeric() {
Moa moa = parseRegex( "\\D" ).toMoa();
assertMatch( false, moa, "1" );
assertMatch( true, moa, "a" );
assertMatch( false, moa, "" );
}
@Test
public void testAny() {
Moa moa = parseRegex( "." ).toMoa();
assertMatch( false, moa, "" );
assertMatch( true, moa, "a" );
}
@Test
public void testSpecialChars() {
char[] specialChars = {'s', 'S', 'w', 'W', 'd', 'D', 'k'};
for ( char specialChar : specialChars ) {
Moa moa = parseRegex( String.valueOf( specialChar ) ).toMoa();
assertMatch( false, moa, "" );
assertMatch( true, moa, String.valueOf( specialChar ) );
}
}
@Test
public void testDeterminismPreMoa() {
//The one that failed while Dominik tested the cli tool
Regex regex = parseRegex(
"(?<1>)(?<2>)(?<3>)(?<4>)(?<5>)(?<6>)(?<7>)(?<8>)(?<9>)(?<10>)(?<11>)(?<12>)(?<13>)(?<14>)(?<15>)(?<16>)(?<17>)(?<18>)(?<19>)(?<20>)" +
"a" +
"(()|(?<1>))(()|(?<2>))(()|(?<3>))(()|(?<4>))(()|(?<5>))(()|(?<6>))(()|(?<7>))(()|(?<8>))(()|(?<9>))(()|(?<10>))(()|(?<11>))(()|(?<12>))(()|(?<13>))(()|(?<14>))(()|(?<15>))(()|(?<16>))(()|(?<17>))(()|(?<18>))(()|(?<19>))(()|(?<20>))" +
"b"
);
try {
regex.toMoa();
fail( "failed to recognize a non deterministic regex as non deterministic" );
}
catch (NonDeterministicException e) {
System.out.println( "successfully got Exception while building the MOA: " + e.getMessage() );
}
}
@Test
public void testEscapeNonBrackets() {
char[] escapees = {'*', '+', '?', '\\', '.' | '$'};
for ( char escapee : escapees ) {
{
Moa moa = parseRegex( "\\" + escapee ).toMoa();
assertMatch( false, moa, "" );
assertMatch( true, moa, String.valueOf( escapee ) );
}
}
Regex regex = parseRegex( "\\^" );
assertMatch( true, regex, "^" );
}
private static final String COOL_REGEX = "((?<y>\\k<x>)(?<x>\\k<y>a))+";
private static final String COOL_REGEX_2 = "(?<x>)((?<y>\\k<x>)(?<x>\\k<y>a))+";
private static final String[] COOL_REGEXES = {COOL_REGEX, COOL_REGEX_2};
@Test
public void testCool() {
for ( String regexStr : COOL_REGEXES ) {
Regex regex = parseRegex( regexStr );
Moa moa = regex.toMoa();
assertTrue( moa.check( "aaaa" ) );
boolean tmp = false;
for ( int i = 0; i < 100; ++i ) {
String str = repeat( "a", i );
boolean res = moa.check( str );
if ( res ) {
tmp = true;
System.out.println( str );
}
}
assertTrue( tmp );
}
}
@Test
public void testSpecialCharsWithoutEscaping() {
for ( String str : Arrays.asList( ":", "<", ">" ) ) {
Regex regex = parseRegex( str );
Moa moa = regex.toMoa();
assertTrue( moa.check( str ) );
}
}
@Test
public void testCoolLanguagesJava() {
for ( String regexStr : COOL_REGEXES ) {
try {
{
Pattern pattern = Pattern.compile( regexStr );
boolean tmp = false;
for ( int i = 0; i < 100; ++i ) {
String str = repeat( "a", i );
boolean res = pattern.matcher( str ).matches();
if ( res ) {
tmp = true;
System.out.println( str );
}
}
assertTrue( tmp );
}
}
catch (PatternSyntaxException e) {
System.out.println( "Java Pattern doesn't like " + regexStr + ", with message: " + e.getMessage() );
}
}
}
private static String repeat(String str, int times) {
String ret = "";
for ( int i = 0; i < times; ++i ) {
ret += str;
}
return ret;
}
@Test
public void testEscapeBrackets() {
char[] brackets = {'[', ']', '(', ')'};
for ( char bracket : brackets ) {
{
Moa moa = parseRegex( "\\" + bracket ).toMoa();
assertMatch( false, moa, "" );
assertMatch( true, moa, String.valueOf( bracket ) );
}
}
}
private static void assertMatch(boolean shouldMatch, Regex regex, String input) {
assertEquals( shouldMatch, regex.toMoa().check( input ) );
}
private static void assertMatch(boolean shouldMatch, Moa moa, String input) {
assertEquals( shouldMatch, moa.check( input ) );
}
private static RegexParser regexParser(String regexStr) {
RegexLexer lexer = new RegexLexer( new ANTLRInputStream( regexStr ) );
RegexParser parser = new RegexParser( new CommonTokenStream( lexer ) );
parser.setBuildParseTree( true );
return parser;
}
private static Regex parseRegex(String regexStr) {
RegexParser parser = regexParser( regexStr );
RegexParser.RegexContext regexTree = parser.regex();
System.out.println( regexTree.toStringTree( parser ) );
RegexTreeListener listener = new RegexTreeListener();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk( listener, regexTree );
return listener.finalRegex();
}
}
| engine/src/test/java/com/github/s4ke/moar/regex/ParserTest.java | /*
The MIT License (MIT)
Copyright (c) 2016 Martin Braun
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.github.s4ke.moar.regex;
import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import com.github.s4ke.moar.MoaMatcher;
import com.github.s4ke.moar.MoaPattern;
import com.github.s4ke.moar.NonDeterministicException;
import com.github.s4ke.moar.moa.Moa;
import com.github.s4ke.moar.regex.parser.RegexLexer;
import com.github.s4ke.moar.regex.parser.RegexParser;
import com.github.s4ke.moar.regex.parser.RegexTreeListener;
import com.github.s4ke.moar.strings.EfficientString;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.junit.Assert;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Martin Braun
*/
public class ParserTest {
@Test
public void test() {
MoaPattern pattern = MoaPattern.compile( "^Deterministic|OrNot$" );
MoaMatcher matcher = pattern.matcher( "Deterministic" );
assertTrue( matcher.nextMatch() );
assertTrue( matcher.matches() );
}
@Test
public void testTusker() {
//from: http://tusker.org/regex/regex_benchmark.html
//adapted the syntax though
//FIXME: fix syntax of our regexes to be more compatible?
//or just throw out the PCRE syntax alltogether in favour
//of a more readable alternative
{
Regex regex = parseRegex( "^(([^:]+)://)?([^:/]+)(:([0-9]+))?(/.*)" );
TestUtil.assertNonDet( regex );
}
{
//this is non deterministic (see the start)
Regex regex = parseRegex( "(([^:]+)://)?([^:/]+)(:([0-9]+))?(/.*)" );
TestUtil.assertNonDet( regex );
}
{
//the original has this bounded by word: \\b(\\w+)(\\s+\\1)+\\b
//this is non deterministic by our current definition
Regex regex = parseRegex( "(\\w+)(\\s+\\1)+" );
TestUtil.assertNonDet( regex );
}
{
//adapted the [+-] to [\\+\\-] (our ANTLR grammar is not that clever
//we also treat the dot as the any metachar.
Regex regex = parseRegex( "usd [\\+\\-]?[0-9]+\\.[0-9][0-9]" );
TestUtil.assertDet( regex );
Moa moa = regex.toMoa();
TestUtil.assertMatch( true, moa, "usd 1234.00" );
TestUtil.assertMatch( true, moa, "usd +1234.00" );
TestUtil.assertMatch( true, moa, "usd -1234.00" );
TestUtil.assertMatch( true, moa, "usd 1.00" );
TestUtil.assertMatch( true, moa, "usd +1.00" );
TestUtil.assertMatch( true, moa, "usd -1.00" );
TestUtil.assertMatch( false, moa, "1234.00" );
TestUtil.assertMatch( false, moa, "usd .00" );
TestUtil.assertMatch( false, moa, "usd +.00" );
TestUtil.assertMatch( false, moa, "usd -.00" );
TestUtil.assertMatch( false, moa, "usd 1." );
}
}
@Test
public void testTooHarshDeterminism() {
//these were wrongly identified as non deterministic
//but this was only wrong for non matching groups
TestUtil.assertDet( parseRegex( "(?:)|(?:)" ) );
TestUtil.assertNonDet( parseRegex( "()|()" ) );
TestUtil.assertDet( parseRegex( "(?:a+)+" ) );
TestUtil.assertNonDet( parseRegex( "(a+)+" ) );
TestUtil.assertDet( parseRegex( "(?:a|(?:))+" ) );
TestUtil.assertNonDet( parseRegex( "(a|())+" ) );
}
@Test
public void testCaret() {
Moa moa = parseRegex( "^a" ).toMoa();
assertMatch( true, moa, "a" );
{
String tmp = "aa";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
assertEquals( 1, cnt );
}
for ( EfficientString eff : BoundConstants.LINE_BREAK_CHARS ) {
String tmp = "a" + eff.toString() + "a";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
assertEquals( 2, cnt );
}
}
@Test
public void testDollar() {
Moa moa = parseRegex( "a$" ).toMoa();
assertMatch( true, moa, "a" );
for ( EfficientString eff : BoundConstants.LINE_BREAK_CHARS ) {
String tmp = "a" + eff.toString() + "ab";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
Assert.assertEquals( 1, cnt );
}
}
@Test
public void testEndOfLastMatch() {
Moa moa = parseRegex( "\\Ga" ).toMoa();
assertTrue( moa.check( "a" ) );
{
String tmp = "aa";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
Assert.assertEquals( 2, cnt );
}
{
String tmp = "a a";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
Assert.assertEquals( 1, cnt );
}
}
@Test
public void testEndOfInput() {
Moa moa = parseRegex( "a\\z" ).toMoa();
assertTrue( moa.check( "a" ) );
{
String tmp = "aa";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
Assert.assertEquals( 1, cnt );
}
}
@Test
public void testCaretAndDollar() {
Moa moa = parseRegex( "^a$" ).toMoa();
assertTrue( moa.check( "a" ) );
for ( EfficientString eff : BoundConstants.LINE_BREAK_CHARS ) {
String tmp = "a" + eff.toString() + "a";
MoaMatcher matcher = moa.matcher( tmp );
int cnt = 0;
while ( matcher.nextMatch() ) {
++cnt;
}
assertEquals( 2, cnt );
}
}
@Test
public void testUTF32() {
Moa moa;
{
int[] codePoints = "someStuff~\uD801\uDC28~someOtherStuff".codePoints().toArray();
moa = parseRegex( new String( codePoints, 0, codePoints.length ) ).toMoa();
}
{
int[] codePoints = "someStuff\uD801\uDC28someOtherStuff".codePoints().toArray();
assertMatch( true, moa, new String( codePoints, 0, codePoints.length ) );
}
}
@Test
public void testSingleChar() {
Regex regex = parseRegex( "a" );
assertMatch( true, regex, "a" );
assertMatch( false, regex, "b" );
assertMatch( false, regex, "" );
}
@Test
public void testSimpleConcat() {
Regex regex = parseRegex( "abc" );
Moa moa = regex.toMoa();
assertTrue( moa.check( "abc" ) );
assertFalse( moa.check( "ab" ) );
}
@Test
public void testSimpleOr() {
Regex regex = parseRegex( "a|b" );
assertMatch( true, regex, "a" );
assertMatch( true, regex, "b" );
assertMatch( false, regex, "c" );
assertMatch( false, regex, "" );
}
@Test
public void testSimpleGroup() {
Regex regex = parseRegex( "(a)" );
Moa moa = regex.toMoa();
assertTrue( moa.check( "a" ) );
{
MoaMatcher matcher = moa.matcher( "a" );
assertTrue( matcher.nextMatch() );
assertTrue( matcher.matches() );
assertEquals( "a", matcher.getVariableContent( 1 ) );
assertEquals( "a", matcher.getVariableContent( "1" ) );
}
}
@Test
public void testSimplePositiveSet() {
Regex regex = parseRegex( "[abc]" );
assertMatch( true, regex, "a" );
assertMatch( true, regex, "b" );
assertMatch( true, regex, "c" );
assertMatch( false, regex, "d" );
assertMatch( false, regex, "" );
}
@Test
public void testMultipleStars() {
//Regex regex = parseRegex( "a***" );
}
@Test
public void testAStarBStarStar() {
Regex regex = parseRegex( "(?:a*b*)*" );
TestUtil.assertDet( regex );
}
@Test
public void testRangePositiveSet() {
Moa moa = parseRegex( "[ac-zAC-Z]" ).toMoa();
for ( char c = 'a'; c <= 'z'; ++c ) {
if ( c == 'b' ) {
assertMatch( false, moa, String.valueOf( c ) );
}
else {
assertMatch( true, moa, String.valueOf( c ) );
}
}
for ( char c = 'A'; c <= 'Z'; ++c ) {
if ( c == 'B' ) {
assertMatch( false, moa, String.valueOf( c ) );
}
else {
assertMatch( true, moa, String.valueOf( c ) );
}
}
assertMatch( false, moa, "!" );
}
@Test
public void testRangeNegativeset() {
//reuse this, the non-determinism check is quite expensive if a set
//is used
Moa moa = parseRegex( "[^a]" ).toMoa();
for ( int i = 0; i <= Character.MAX_VALUE; ++i ) {
if ( i == 'a' ) {
assertMatch( false, moa, String.valueOf( (char) i ) );
}
else {
assertMatch( true, moa, String.valueOf( (char) i ) );
}
}
}
@Test
public void testNumericalRegex() {
Moa moa = parseRegex( "1" ).toMoa();
assertMatch( true, moa, "1" );
}
@Test
public void testBackRefIndexed() {
Moa moa = parseRegex( "(a*)b\\1" ).toMoa();
assertMatch( false, moa, "ab" );
assertMatch( true, moa, "aba" );
assertMatch( false, moa, "aaba" );
assertMatch( false, moa, "abaa" );
assertMatch( true, moa, "aabaa" );
}
@Test
public void testBackRefNamed() {
Moa moa = parseRegex( "(?<zA1>a*)b\\k<zA1>" ).toMoa();
assertMatch( false, moa, "ab" );
assertMatch( true, moa, "aba" );
assertMatch( false, moa, "aaba" );
assertMatch( false, moa, "abaa" );
assertMatch( true, moa, "aabaa" );
}
@Test
public void testNonCapturingGroup() {
Moa moa = parseRegex( "(?:ab|d)*c" ).toMoa();
assertMatch( true, moa, "c" );
assertMatch( true, moa, "abc" );
assertMatch( true, moa, "ababc" );
assertMatch( true, moa, "abdabc" );
}
@Test
public void testEscapeSimple() {
Regex regex = parseRegex( "\\^" );
assertMatch( true, regex, "^" );
}
@Test
public void testEscapeBackslash() {
Regex regex = parseRegex( "\\\\" );
assertMatch( true, regex, "\\" );
}
@Test
public void testOrNothing() {
Moa moa = parseRegex( "a?" ).toMoa();
assertMatch( true, moa, "" );
assertMatch( true, moa, "a" );
assertMatch( false, moa, "b" );
}
@Test
public void testPrecedenceAndOr() {
Regex regex = parseRegex( "ab|bcd" );
Moa moa = regex.toMoa();
assertMatch( true, moa, "ab" );
assertMatch( true, moa, "bcd" );
assertMatch( false, moa, "abbcd" );
}
@Test
public void testEpsilon() {
Moa moa = parseRegex( "" ).toMoa();
assertMatch( true, moa, "" );
assertMatch( false, moa, "a" );
}
@Test
public void testWhitespace() {
Moa moa = parseRegex( "\\s" ).toMoa();
assertMatch( true, moa, " " );
assertMatch( false, moa, "a" );
assertMatch( false, moa, "" );
}
@Test
public void testNonWhitespace() {
Moa moa = parseRegex( "\\S" ).toMoa();
assertMatch( false, moa, " " );
assertMatch( true, moa, "a" );
assertMatch( false, moa, "" );
}
@Test
public void testEmail() {
Moa moa = parseRegex( "\\w+@\\w\\w+\\.\\w\\w+" ).toMoa();
assertMatch( true, moa, "[email protected]" );
assertMatch( false, moa, "test.com" );
}
@Test
public void testWordCharacter() {
Moa moa = parseRegex( "\\w" ).toMoa();
assertMatch( false, moa, " " );
assertMatch( true, moa, "a" );
assertMatch( false, moa, "" );
}
@Test
public void testNonWordCharacter() {
Moa moa = parseRegex( "\\W" ).toMoa();
assertMatch( true, moa, " " );
assertMatch( false, moa, "a" );
assertMatch( false, moa, "" );
}
@Test
public void testNumeric() {
Moa moa = parseRegex( "\\d" ).toMoa();
assertMatch( true, moa, "1" );
assertMatch( false, moa, "a" );
assertMatch( false, moa, "" );
}
@Test
public void testNonNumeric() {
Moa moa = parseRegex( "\\D" ).toMoa();
assertMatch( false, moa, "1" );
assertMatch( true, moa, "a" );
assertMatch( false, moa, "" );
}
@Test
public void testAny() {
Moa moa = parseRegex( "." ).toMoa();
assertMatch( false, moa, "" );
assertMatch( true, moa, "a" );
}
@Test
public void testSpecialChars() {
char[] specialChars = {'s', 'S', 'w', 'W', 'd', 'D', 'k'};
for ( char specialChar : specialChars ) {
Moa moa = parseRegex( String.valueOf( specialChar ) ).toMoa();
assertMatch( false, moa, "" );
assertMatch( true, moa, String.valueOf( specialChar ) );
}
}
@Test
public void testDeterminismPreMoa() {
//The one that failed while Dominik tested the cli tool
Regex regex = parseRegex(
"(?<1>)(?<2>)(?<3>)(?<4>)(?<5>)(?<6>)(?<7>)(?<8>)(?<9>)(?<10>)(?<11>)(?<12>)(?<13>)(?<14>)(?<15>)(?<16>)(?<17>)(?<18>)(?<19>)(?<20>)" +
"a" +
"(()|(?<1>))(()|(?<2>))(()|(?<3>))(()|(?<4>))(()|(?<5>))(()|(?<6>))(()|(?<7>))(()|(?<8>))(()|(?<9>))(()|(?<10>))(()|(?<11>))(()|(?<12>))(()|(?<13>))(()|(?<14>))(()|(?<15>))(()|(?<16>))(()|(?<17>))(()|(?<18>))(()|(?<19>))(()|(?<20>))" +
"b"
);
try {
regex.toMoa();
fail( "failed to recognize a non deterministic regex as non deterministic" );
}
catch (NonDeterministicException e) {
System.out.println( "successfully got Exception while building the MOA: " + e.getMessage() );
}
}
@Test
public void testEscapeNonBrackets() {
char[] escapees = {'*', '+', '?', '\\', '.' | '$'};
for ( char escapee : escapees ) {
{
Moa moa = parseRegex( "\\" + escapee ).toMoa();
assertMatch( false, moa, "" );
assertMatch( true, moa, String.valueOf( escapee ) );
}
}
Regex regex = parseRegex( "\\^" );
assertMatch( true, regex, "^" );
}
private static final String COOL_REGEX = "((?<y>\\k<x>)(?<x>\\k<y>a))+";
private static final String COOL_REGEX_2 = "(?<x>)((?<y>\\k<x>)(?<x>\\k<y>a))+";
private static final String[] COOL_REGEXES = {COOL_REGEX, COOL_REGEX_2};
@Test
public void testCool() {
for ( String regexStr : COOL_REGEXES ) {
Regex regex = parseRegex( regexStr );
Moa moa = regex.toMoa();
assertTrue( moa.check( "aaaa" ) );
boolean tmp = false;
for ( int i = 0; i < 100; ++i ) {
String str = repeat( "a", i );
boolean res = moa.check( str );
if ( res ) {
tmp = true;
System.out.println( str );
}
}
assertTrue( tmp );
}
}
@Test
public void testSpecialCharsWithoutEscaping() {
for ( String str : Arrays.asList( ":", "<", ">" ) ) {
Regex regex = parseRegex( str );
Moa moa = regex.toMoa();
assertTrue( moa.check( str ) );
}
}
@Test
public void testCoolLanguagesJava() {
for ( String regexStr : COOL_REGEXES ) {
try {
{
Pattern pattern = Pattern.compile( regexStr );
boolean tmp = false;
for ( int i = 0; i < 100; ++i ) {
String str = repeat( "a", i );
boolean res = pattern.matcher( str ).matches();
if ( res ) {
tmp = true;
System.out.println( str );
}
}
assertTrue( tmp );
}
}
catch (PatternSyntaxException e) {
System.out.println( "Java Pattern doesn't like " + regexStr + ", with message: " + e.getMessage() );
}
}
}
private static String repeat(String str, int times) {
String ret = "";
for ( int i = 0; i < times; ++i ) {
ret += str;
}
return ret;
}
@Test
public void testEscapeBrackets() {
char[] brackets = {'[', ']', '(', ')'};
for ( char bracket : brackets ) {
{
Moa moa = parseRegex( "\\" + bracket ).toMoa();
assertMatch( false, moa, "" );
assertMatch( true, moa, String.valueOf( bracket ) );
}
}
}
private static void assertMatch(boolean shouldMatch, Regex regex, String input) {
assertEquals( shouldMatch, regex.toMoa().check( input ) );
}
private static void assertMatch(boolean shouldMatch, Moa moa, String input) {
assertEquals( shouldMatch, moa.check( input ) );
}
private static RegexParser regexParser(String regexStr) {
RegexLexer lexer = new RegexLexer( new ANTLRInputStream( regexStr ) );
RegexParser parser = new RegexParser( new CommonTokenStream( lexer ) );
parser.setBuildParseTree( true );
return parser;
}
private static Regex parseRegex(String regexStr) {
RegexParser parser = regexParser( regexStr );
RegexParser.RegexContext regexTree = parser.regex();
System.out.println( regexTree.toStringTree( parser ) );
RegexTreeListener listener = new RegexTreeListener();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk( listener, regexTree );
return listener.finalRegex();
}
}
| minor
| engine/src/test/java/com/github/s4ke/moar/regex/ParserTest.java | minor |
|
Java | mit | b055a360188cbb762a2c6a9456854a9db1ccb908 | 0 | InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service | package com.worth.ifs.application.controller;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.worth.ifs.BaseControllerIntegrationTest;
import com.worth.ifs.application.constant.ApplicationStatusConstants;
import com.worth.ifs.application.domain.Application;
import com.worth.ifs.application.domain.ApplicationStatus;
import com.worth.ifs.application.mapper.ApplicationStatusMapper;
import com.worth.ifs.application.resource.ApplicationResource;
import com.worth.ifs.commons.rest.RestResult;
import com.worth.ifs.user.domain.ProcessRole;
import com.worth.ifs.user.domain.User;
import com.worth.ifs.user.domain.UserRoleType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static com.worth.ifs.security.SecuritySetter.swapOutForUser;
import static org.junit.Assert.*;
@Rollback
public class ApplicationControllerIntegrationTest extends BaseControllerIntegrationTest<ApplicationController> {
@Autowired
ApplicationStatusMapper applicationStatusMapper;
public static final long APPLICATION_ID = 1L;
private QuestionController questionController;
private Long leadApplicantProcessRole;
private Long leadApplicantId;
@Before
public void setUp() throws Exception {
leadApplicantId = 1L;
leadApplicantProcessRole = 1L;
List<ProcessRole> proccessRoles = new ArrayList<>();
proccessRoles.add(
new ProcessRole(
leadApplicantProcessRole,
null,
new Application(
APPLICATION_ID,
"",
new ApplicationStatus(
ApplicationStatusConstants.CREATED.getId(),
ApplicationStatusConstants.CREATED.getName()
)
),
null,
null
)
);
User user = new User(leadApplicantId, "steve", "smith", "[email protected]", "", proccessRoles, "123abc");
proccessRoles.get(0).setUser(user);
swapOutForUser(new User(leadApplicantId, "steve", "smith", "[email protected]", "", proccessRoles, "123abc"));
}
@After
public void tearDown() throws Exception {
swapOutForUser(null);
}
@Override
@Autowired
protected void setControllerUnderTest(ApplicationController controller) {
this.controller = controller;
}
@Autowired
public void setQuestionController(QuestionController questionController) {
this.questionController = questionController;
}
@Test
public void testFindAll() {
RestResult<List<ApplicationResource>> all = controller.findAll();
assertEquals(5, all.getSuccessObject().size());
}
@Test
public void testUpdateApplication() {
String originalTitle= "A novel solution to an old problem";
String newTitle = "A new title";
ApplicationResource application = controller.getApplicationById(APPLICATION_ID).getSuccessObject();
assertEquals(originalTitle, application.getName());
application.setName(newTitle);
controller.saveApplicationDetails(APPLICATION_ID, application);
ApplicationResource updated = controller.getApplicationById(APPLICATION_ID).getSuccessObject();
assertEquals(newTitle, updated.getName());
}
/**
* Check if progress decreases when marking a question as incomplete.
*/
@Test
public void testGetProgressPercentageByApplicationId() throws Exception {
ObjectNode response = controller.getProgressPercentageByApplicationId(APPLICATION_ID).getSuccessObject();
double completedPercentage = response.get("completedPercentage").asDouble();
double delta = 0.10;
assertEquals(36.206896551, completedPercentage, delta); //Changed after enabling mark as complete on some more questions for INFUND-446
questionController.markAsInComplete(28L, APPLICATION_ID, leadApplicantProcessRole);
response = controller.getProgressPercentageByApplicationId(APPLICATION_ID).getSuccessObject();
completedPercentage = response.get("completedPercentage").asDouble();
assertEquals(34.48275862, completedPercentage, delta); //Changed after enabling mark as complete on some more questions for INFUND-446
}
@Test
public void testUpdateApplicationStatusApproved() throws Exception {
controller.updateApplicationStatus(APPLICATION_ID, ApplicationStatusConstants.APPROVED.getId());
assertEquals(ApplicationStatusConstants.APPROVED.getName(), applicationStatusMapper.mapIdToDomain(controller.getApplicationById(APPLICATION_ID).getSuccessObject().getApplicationStatus()).getName());
}
@Test
public void testUpdateApplicationStatusRejected() throws Exception {
controller.updateApplicationStatus(APPLICATION_ID, ApplicationStatusConstants.REJECTED.getId());
assertEquals(ApplicationStatusConstants.REJECTED.getName(), applicationStatusMapper.mapIdToDomain(controller.getApplicationById(APPLICATION_ID).getSuccessObject().getApplicationStatus()).getName());
}
@Test
public void testUpdateApplicationStatusCreated() throws Exception {
controller.updateApplicationStatus(APPLICATION_ID, ApplicationStatusConstants.CREATED.getId());
assertEquals(ApplicationStatusConstants.CREATED.getName(), applicationStatusMapper.mapIdToDomain(controller.getApplicationById(APPLICATION_ID).getSuccessObject().getApplicationStatus()).getName());
}
@Test
public void testUpdateApplicationStatusSubmitted() throws Exception {
ApplicationResource applicationBefore = controller.getApplicationById(APPLICATION_ID).getSuccessObject();
assertNull(applicationBefore.getSubmittedDate());
controller.updateApplicationStatus(APPLICATION_ID, ApplicationStatusConstants.SUBMITTED.getId());
assertEquals(ApplicationStatusConstants.SUBMITTED.getName(), applicationStatusMapper.mapIdToDomain(controller.getApplicationById(APPLICATION_ID).getSuccessObject().getApplicationStatus()).getName());
ApplicationResource applicationAfter = controller.getApplicationById(APPLICATION_ID).getSuccessObject();
assertNotNull(applicationAfter.getSubmittedDate());
}
@Test
public void testGetApplicationsByCompetitionIdAndUserId() throws Exception {
Long competitionId = 1L;
Long userId = 1L ;
UserRoleType role = UserRoleType.LEADAPPLICANT;
List<ApplicationResource> applications = controller.getApplicationsByCompetitionIdAndUserId(competitionId, userId, role).getSuccessObject();
assertEquals(5, applications.size());
Optional<ApplicationResource> application = applications.stream().filter(a -> a.getId().equals(APPLICATION_ID)).findAny();
assertTrue(application.isPresent());
assertEquals(competitionId, application.get().getCompetition());
}
}
| ifs-data-service/src/test/java/com/worth/ifs/application/controller/ApplicationControllerIntegrationTest.java | package com.worth.ifs.application.controller;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.worth.ifs.BaseControllerIntegrationTest;
import com.worth.ifs.application.constant.ApplicationStatusConstants;
import com.worth.ifs.application.domain.Application;
import com.worth.ifs.application.domain.ApplicationStatus;
import com.worth.ifs.application.mapper.ApplicationStatusMapper;
import com.worth.ifs.application.resource.ApplicationResource;
import com.worth.ifs.commons.rest.RestResult;
import com.worth.ifs.user.domain.ProcessRole;
import com.worth.ifs.user.domain.User;
import com.worth.ifs.user.domain.UserRoleType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static com.worth.ifs.security.SecuritySetter.swapOutForUser;
import static org.junit.Assert.*;
@Rollback
public class ApplicationControllerIntegrationTest extends BaseControllerIntegrationTest<ApplicationController> {
@Autowired
ApplicationStatusMapper applicationStatusMapper;
public static final long APPLICATION_ID = 1L;
private QuestionController questionController;
private Long leadApplicantProcessRole;
private Long leadApplicantId;
@Before
public void setUp() throws Exception {
leadApplicantId = 1L;
leadApplicantProcessRole = 1L;
List<ProcessRole> proccessRoles = new ArrayList<>();
proccessRoles.add(
new ProcessRole(
leadApplicantProcessRole,
null,
new Application(
APPLICATION_ID,
"",
new ApplicationStatus(
ApplicationStatusConstants.CREATED.getId(),
ApplicationStatusConstants.CREATED.getName()
)
),
null,
null
)
);
User user = new User(leadApplicantId, "steve", "smith", "[email protected]", "", proccessRoles, "123abc");
proccessRoles.get(0).setUser(user);
swapOutForUser(new User(leadApplicantId, "steve", "smith", "[email protected]", "", proccessRoles, "123abc"));
}
@After
public void tearDown() throws Exception {
swapOutForUser(null);
}
@Override
@Autowired
protected void setControllerUnderTest(ApplicationController controller) {
this.controller = controller;
}
@Autowired
public void setQuestionController(QuestionController questionController) {
this.questionController = questionController;
}
@Test
public void testFindAll() {
RestResult<List<ApplicationResource>> all = controller.findAll();
assertEquals(5, all.getSuccessObject().size());
}
@Test
public void testUpdateApplication() {
String originalTitle= "A novel solution to an old problem";
String newTitle = "A new title";
ApplicationResource application = controller.getApplicationById(APPLICATION_ID).getSuccessObject();
assertEquals(originalTitle, application.getName());
application.setName(newTitle);
controller.saveApplicationDetails(APPLICATION_ID, application);
ApplicationResource updated = controller.getApplicationById(APPLICATION_ID).getSuccessObject();
assertEquals(newTitle, updated.getName());
}
/**
* Check if progress decreases when marking a question as incomplete.
*/
@Test
public void testGetProgressPercentageByApplicationId() throws Exception {
ObjectNode response = controller.getProgressPercentageByApplicationId(APPLICATION_ID).getSuccessObject();
double completedPercentage = response.get("completedPercentage").asDouble();
double delta = 0.10;
assertEquals(38.1818181822, completedPercentage, delta); //Changed after enabling mark as complete on some more questions for INFUND-446
questionController.markAsInComplete(28L, APPLICATION_ID, leadApplicantProcessRole);
response = controller.getProgressPercentageByApplicationId(APPLICATION_ID).getSuccessObject();
completedPercentage = response.get("completedPercentage").asDouble();
assertEquals(36.363636364, completedPercentage, delta); //Changed after enabling mark as complete on some more questions for INFUND-446
}
@Test
public void testUpdateApplicationStatusApproved() throws Exception {
controller.updateApplicationStatus(APPLICATION_ID, ApplicationStatusConstants.APPROVED.getId());
assertEquals(ApplicationStatusConstants.APPROVED.getName(), applicationStatusMapper.mapIdToDomain(controller.getApplicationById(APPLICATION_ID).getSuccessObject().getApplicationStatus()).getName());
}
@Test
public void testUpdateApplicationStatusRejected() throws Exception {
controller.updateApplicationStatus(APPLICATION_ID, ApplicationStatusConstants.REJECTED.getId());
assertEquals(ApplicationStatusConstants.REJECTED.getName(), applicationStatusMapper.mapIdToDomain(controller.getApplicationById(APPLICATION_ID).getSuccessObject().getApplicationStatus()).getName());
}
@Test
public void testUpdateApplicationStatusCreated() throws Exception {
controller.updateApplicationStatus(APPLICATION_ID, ApplicationStatusConstants.CREATED.getId());
assertEquals(ApplicationStatusConstants.CREATED.getName(), applicationStatusMapper.mapIdToDomain(controller.getApplicationById(APPLICATION_ID).getSuccessObject().getApplicationStatus()).getName());
}
@Test
public void testUpdateApplicationStatusSubmitted() throws Exception {
ApplicationResource applicationBefore = controller.getApplicationById(APPLICATION_ID).getSuccessObject();
assertNull(applicationBefore.getSubmittedDate());
controller.updateApplicationStatus(APPLICATION_ID, ApplicationStatusConstants.SUBMITTED.getId());
assertEquals(ApplicationStatusConstants.SUBMITTED.getName(), applicationStatusMapper.mapIdToDomain(controller.getApplicationById(APPLICATION_ID).getSuccessObject().getApplicationStatus()).getName());
ApplicationResource applicationAfter = controller.getApplicationById(APPLICATION_ID).getSuccessObject();
assertNotNull(applicationAfter.getSubmittedDate());
}
@Test
public void testGetApplicationsByCompetitionIdAndUserId() throws Exception {
Long competitionId = 1L;
Long userId = 1L ;
UserRoleType role = UserRoleType.LEADAPPLICANT;
List<ApplicationResource> applications = controller.getApplicationsByCompetitionIdAndUserId(competitionId, userId, role).getSuccessObject();
assertEquals(5, applications.size());
Optional<ApplicationResource> application = applications.stream().filter(a -> a.getId().equals(APPLICATION_ID)).findAny();
assertTrue(application.isPresent());
assertEquals(competitionId, application.get().getCompetition());
}
}
| INFUND-917 fix the unit tests
| ifs-data-service/src/test/java/com/worth/ifs/application/controller/ApplicationControllerIntegrationTest.java | INFUND-917 fix the unit tests |
|
Java | mit | fbd1d0defb36c8f453d74bcd33dea51550304e3b | 0 | mmig/mmir-plugin-speech-android,mmig/mmir-plugin-speech-android | /**
* The MIT License
*
* Copyright (c) 2014-2016
* DFKI (github.com/mmig)
*
*
* based on work of:
*
* Copyright (c) 2011-2013
* Colin Turner (github.com/koolspin)
* Guillaume Charhon (github.com/poiuytrez)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
*/
package de.dfki.iui.mmir.plugins.speech.android;
import java.util.Locale;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.LOG;
import org.json.JSONArray;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.os.Vibrator;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
/**
* Style and such borrowed from the TTS and PhoneListener plugins
*/
public class AndroidSpeechRecognizer extends CordovaPlugin {
public static final String ACTION_GET_LANGUAGES = "getSupportedLanguages";
public static final String ACTION_RECOGNIZE = "recognize";
public static final String ACTION_START_RECORDING = "startRecording";
public static final String ACTION_STOP_RECORDING = "stopRecording";
public static final String ACTION_CANCEL = "cancel";
// public static final String ACTION_MIC_LEVEL = "getMicLevels";
public static final String ACTION_MIC_LEVEL_LISTENER = "setMicLevelsListener";
private static final String PLUGIN_NAME = AndroidSpeechRecognizer.class.getSimpleName();
private static final int SDK_VERSION = Build.VERSION.SDK_INT;
// private static int REQUEST_CODE = 1001;
// private CallbackContext callbackContext;
private LanguageDetailsReceiver languageDetailsChecker;
private int recCounter = 0;
private SpeechRecognizer speech;
private Object speechLock = new Object();
private ASRHandler currentRecognizer;
/**
* enable / disable sending RMS change events to the JavaScript plugin implementation.
*
* This attribute will be set by the {@link AndroidSpeechRecognizer#ACTION_MIC_LEVEL_LISTENER ACTION_MIC_LEVEL_LISTENER}
* and all new {@link ASRHandler} will be initialized with the new value.
*
* @see ASRHandler#setRmsChangedEnabled(boolean)
* @see #setMicLevelsListener(boolean, CallbackContext)
*/
private boolean enableMicLevelsListeners = false;
CordovaInterface _cordova;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
this._cordova = cordova;
this.mAudioManager = (AudioManager) this._cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);
super.initialize(cordova, webView);
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
boolean isValidAction = true;
// this.callbackContext= callbackContext;
// //FIXM DEBUG:
// try{
// LOG.d(PLUGIN_NAME + "_DEBUG", String.format("action '%s' with arguments: %s)", action, args.toString(2)));
// }catch(Exception e){}
// Action selector
if (ACTION_RECOGNIZE.equals(action)) {
// recognize speech
startSpeechRecognitionActivity(args, callbackContext, true);
} else if (ACTION_GET_LANGUAGES.equals(action)) {
getSupportedLanguages(callbackContext);
} else if (ACTION_START_RECORDING.equals(action)) {
startSpeechRecognitionActivity(args, callbackContext, false);
} else if (ACTION_STOP_RECORDING.equals(action)) {
stopSpeechInput(callbackContext);
} else if (ACTION_CANCEL.equals(action)) {
cancelSpeechInput(callbackContext);
// } else if (ACTION_MIC_LEVEL.equals(action)) {
// returnMicLevels(callbackContext);
} else if (ACTION_MIC_LEVEL_LISTENER.equals(action)) {
setMicLevelsListener(args, callbackContext);
} else {
// Invalid action
callbackContext.error("Unknown action: " + action);
isValidAction = false;
}
return isValidAction;
}
// private void returnMicLevels(CallbackContext callbackContext) {
// JSONArray list;
// if(currentRecognizer != null){
// list = AudioLevelChange.toJSON(currentRecognizer.getAudioLevels());
// }
// else {
// list = new JSONArray();
// }
//
// callbackContext.success(list);
// }
// Get the list of supported languages
private void getSupportedLanguages(CallbackContext callbackContext) {
if (languageDetailsChecker == null ){
languageDetailsChecker = new LanguageDetailsReceiver(callbackContext);
}
else {
languageDetailsChecker.setCallbackContext(callbackContext);
}
// Create and launch get languages intent
Intent detailsIntent = new Intent(RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS);
cordova.getActivity().sendOrderedBroadcast(detailsIntent, null, languageDetailsChecker, null, Activity.RESULT_OK, null, null);
}
/**
* Fire an intent to start the speech recognition activity.
*
* @param args Argument array with the following string args: [req code][number of matches][prompt string]
*/
private void startSpeechRecognitionActivity(final JSONArray args, final CallbackContext callbackContext, final boolean isWithEndOfSpeechDetection) {
//need to run recognition on UI thread (Android's SpeechRecognizer must run on main thread)
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
_startSpeechRecognitionActivity(args, callbackContext, isWithEndOfSpeechDetection);
}
});
}
private void _startSpeechRecognitionActivity(JSONArray args, CallbackContext callbackContext, boolean isWithEndOfSpeechDetection) {
int maxMatches = 0;
String prompt = "";//TODO remove? (not used when ASR is directly used as service here...)
String language = Locale.getDefault().toString();
boolean isIntermediate = false;
try {
if (args.length() > 0) {
// Optional language specified
language = args.getString(0);
}
if (args.length() > 1) {
isIntermediate = args.getBoolean(1);
}
if (args.length() > 2) {
// Maximum number of matches, 0 means that the recognizer "decides"
String temp = args.getString(2);
maxMatches = Integer.parseInt(temp);
}
if (args.length() > 3) {
// Optional text prompt
prompt = args.getString(3);
}
//TODO if ... withoutEndOfSpeechDetection = ...
}
catch (Exception e) {
Log.e(PLUGIN_NAME, String.format("startSpeechRecognitionActivity exception: %s", e.toString()));
}
// Create the intent and set parameters
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
if(!isWithEndOfSpeechDetection){
// try to simulate start/stop-recording behavior (without end-of-speech detection)
//NOTE these setting do not seem to have any effect for default Google Recognizer API level > 16
intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, new Long(10000));
intent.putExtra(RecognizerIntent. EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS , new Long(6 * 1000));
}
if (maxMatches > 0)
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxMatches);
if (!prompt.equals(""))
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
if(isIntermediate)
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
//NOTE the extra package seems to be required for older Android versions, but not since API level 17(?)
if(SDK_VERSION <= Build.VERSION_CODES.JELLY_BEAN)
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, cordova.getActivity().getPackageName());
synchronized (speechLock){
if(speech != null){
speech.destroy();
}
speech = SpeechRecognizer.createSpeechRecognizer(cordova.getActivity());
disableSoundFeedback();
++recCounter;
currentRecognizer = new ASRHandler(recCounter, enableMicLevelsListeners, callbackContext, this);
currentRecognizer.setHapticPrompt( (Vibrator) this.cordova.getActivity().getSystemService(Context.VIBRATOR_SERVICE));
speech.setRecognitionListener(currentRecognizer);
speech.startListening(intent);
}
}
private void stopSpeechInput(final CallbackContext callbackContext){
if(this.speech != null && this.currentRecognizer != null){
//TODO synchronize access on currentRecognizer?
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
synchronized (speechLock) {
if(currentRecognizer != null){
currentRecognizer.stopRecording(callbackContext);
}
if(speech != null){
speech.stopListening();
// speech = null;
}
if(AndroidSpeechRecognizer.this != null){
AndroidSpeechRecognizer.this.enableSoundFeedback();
}
}
}
});
}
else {
callbackContext.error("recording was not started yet");
}
}
private void setMicLevelsListener(final JSONArray args, final CallbackContext callbackContext) {
try {
boolean enabled;
if (args.length() > 0) {
//extract enabled/disabled setting from args
enabled = args.getBoolean(0);
}
else {
callbackContext.error("setMicLevelsListener: missing argument BOOLEAN.");
return; /////////////////// EARLY EXIT //////////////////////////
}
setMicLevelsListener(enabled, callbackContext);
}
catch (Exception e) {
String msg = String.format("setMicLevelsListener exception: %s", e.toString());
Log.e(PLUGIN_NAME, msg);
callbackContext.error(msg);
}
}
private void setMicLevelsListener(final boolean enabled, final CallbackContext callbackContext){
enableMicLevelsListeners = enabled;
if(this.speech != null && this.currentRecognizer != null){
//TODO synchronize access on currentRecognizer?
cordova.getActivity().runOnUiThread(new Runnable() {//TODO test if this can run a background-thread via cordova.getThreadPool()
@Override
public void run() {
synchronized (speechLock) {
if(speech != null && currentRecognizer != null){
currentRecognizer.setRmsChangedEnabled(enabled);
}
}
if(AndroidSpeechRecognizer.this != null){
AndroidSpeechRecognizer.this.enableSoundFeedback();
}
callbackContext.success();
}
});
}
else {
callbackContext.success("recognition is currently not running");
}
}
private void cancelSpeechInput(final CallbackContext callbackContext){
if(speech != null){
//need to run stop-recognition on UI thread (Android's SpeechRecognizer must run on main thread)
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try{
synchronized (speechLock) {
if(speech != null){
speech.destroy();
speech = null;
}
}
if(AndroidSpeechRecognizer.this != null){
AndroidSpeechRecognizer.this.enableSoundFeedback();
}
callbackContext.success();
}
catch(Exception e){
LOG.e(PLUGIN_NAME, "cancelRecoginition: an error occured "+e, e);
callbackContext.error(e.toString());
}
}
});
} else {
callbackContext.success();
}
}
//FIXME TEST private/package-level method that allows canceling recognition
void cancelSpeechInput(){
synchronized (speechLock) {
if(this.speech != null){
speech.destroy();//FIXME russa: speech.stopListening() and speech.cancel() do not seem to do the trick -> onRmsChanged is still called!
speech = null;
}
}
enableSoundFeedback();
}
// /**
// * Handle the results from the recognition activity.
// */
// @Override
// public void onActivityResult(int requestCode, int resultCode, Intent data) {
// if (resultCode == Activity.RESULT_OK) {
// // Fill the list view with the strings the recognizer thought it could have heard
// ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
//
//
// float[] scores = data.getFloatArrayExtra(RecognizerIntent.EXTRA_CONFIDENCE_SCORES);
//
// returnSpeechResults(matches, toList(scores) );
// }
// else {
// // Failure - Let the caller know
// this.callbackContext.error(Integer.toString(resultCode));
// }
//
// super.onActivityResult(requestCode, resultCode, data);
// }
@Override
public void onPause(boolean multitasking) {
enableSoundFeedback();
synchronized (speechLock) {
if(speech != null){
speech.destroy();
speech = null;
}
}
}
@Override
public void onDestroy() {
enableSoundFeedback();
synchronized (speechLock) {
if(speech != null){
speech.destroy();
speech = null;
}
}
}
protected AudioManager mAudioManager;
protected volatile boolean mIsCountDownOn;
private boolean mIsStreamSolo;
private boolean isDisableSoundPrompt(){
//TODO impl. "smarter" detection? (russa: which version added the sounds?)
return SDK_VERSION >= Build.VERSION_CODES.JELLY_BEAN;
}
int soloCounter = 0;
void disableSoundFeedback() {
if(!mIsStreamSolo && isDisableSoundPrompt()){
if(delayedEnableSoundHandler != null){
delayedEnableSoundHandler.cancel();
delayedEnableSoundHandler = null;
}
mAudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
mIsStreamSolo = true;
Log.e(PLUGIN_NAME + "_debug-solostream", "DISABLE SOUND -> solo-counter: "+(++soloCounter));
}
}
void enableSoundFeedback() {
if (mIsStreamSolo){
mAudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);
mIsStreamSolo = false;
Log.e(PLUGIN_NAME + "_debug-solostream", "ENABLE SOUND -> solo-counter: "+(--soloCounter));
}
}
// private Object delayedEnableSoundLock = new Object(); FIXME use lock/synchronized when accessing delayedEnableSoundHandler?
private DelayedEnableSound delayedEnableSoundHandler = null;
private int reenableSoundDelay = 500;//ms <- delay for re-enabling sound after recognition has finished (the delay needs to be long enough to suppress the last (un-wanted) sound-feedback of the recognition)
void enableSoundFeedbackDelayed() {
// TODO implement without running on UI thread & scheduling another
// "thread" (would need Looper impl. when running delayed?)
if(delayedEnableSoundHandler != null){
delayedEnableSoundHandler.cancel();
}
delayedEnableSoundHandler = new DelayedEnableSound();
cordova.getActivity().runOnUiThread(delayedEnableSoundHandler);
}
static Handler delayedSoundHandler = null;
private class DelayedEnableSound implements Runnable {
private Object delayedSoundLock = new Object();
private boolean isCanceled = false;
@Override
public void run() {
synchronized(delayedSoundLock){
if(isCanceled){
return; ////////////////// EARLY EXIT /////////////////////
}
if(delayedSoundHandler == null){
delayedSoundHandler = new Handler();
}
}
boolean isScheduled = delayedSoundHandler.postDelayed(new Runnable() {
@Override
public void run() {
synchronized(delayedSoundLock){
if(isCanceled){
return; ////////////////// EARLY EXIT /////////////////////
}
isCanceled = true;
if (AndroidSpeechRecognizer.this != null) {
AndroidSpeechRecognizer.this.enableSoundFeedback();
}
}
}
}, reenableSoundDelay);
if (!isScheduled) {
synchronized(delayedSoundLock){
if(isCanceled){
return; ////////////////// EARLY EXIT /////////////////////
}
isCanceled = true;
if (AndroidSpeechRecognizer.this != null) {
AndroidSpeechRecognizer.this.enableSoundFeedback();
}
}
}
}
public void cancel(){
synchronized(delayedSoundLock){
if(isCanceled){
return; ////////////////// EARLY EXIT /////////////////////
}
isCanceled = true;
if(delayedSoundHandler != null){
delayedSoundHandler.removeCallbacks(this);
}
}
}
}
}
| src/android/de/dfki/iui/mmir/plugins/speech/android/AndroidSpeechRecognizer.java | /**
* The MIT License
*
* Copyright (c) 2014-2016
* DFKI (github.com/mmig)
*
*
* based on work of:
*
* Copyright (c) 2011-2013
* Colin Turner (github.com/koolspin)
* Guillaume Charhon (github.com/poiuytrez)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
*/
package de.dfki.iui.mmir.plugins.speech.android;
import java.util.Locale;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.LOG;
import org.json.JSONArray;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.os.Vibrator;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
/**
* Style and such borrowed from the TTS and PhoneListener plugins
*/
public class AndroidSpeechRecognizer extends CordovaPlugin {
public static final String ACTION_GET_LANGUAGES = "getSupportedLanguages";
public static final String ACTION_RECOGNIZE = "recognize";
public static final String ACTION_START_RECORDING = "startRecording";
public static final String ACTION_STOP_RECORDING = "stopRecording";
public static final String ACTION_CANCEL = "cancel";
// public static final String ACTION_MIC_LEVEL = "getMicLevels";
public static final String ACTION_MIC_LEVEL_LISTENER = "setMicLevelsListener";
private static final String PLUGIN_NAME = AndroidSpeechRecognizer.class.getSimpleName();
private static final int SDK_VERSION = Build.VERSION.SDK_INT;
// private static int REQUEST_CODE = 1001;
// private CallbackContext callbackContext;
private LanguageDetailsReceiver languageDetailsChecker;
private int recCounter = 0;
private SpeechRecognizer speech;
private Object speechLock = new Object();
private ASRHandler currentRecognizer;
/**
* enable / disable sending RMS change events to the JavaScript plugin implementation.
*
* This attribute will be set by the {@link AndroidSpeechRecognizer#ACTION_MIC_LEVEL_LISTENER ACTION_MIC_LEVEL_LISTENER}
* and all new {@link ASRHandler} will be initialized with the new value.
*
* @see ASRHandler#setRmsChangedEnabled(boolean)
* @see #setMicLevelsListener(boolean, CallbackContext)
*/
private boolean enableMicLevelsListeners = false;
CordovaInterface _cordova;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
this._cordova = cordova;
this.mAudioManager = (AudioManager) this._cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);
super.initialize(cordova, webView);
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
boolean isValidAction = true;
// this.callbackContext= callbackContext;
// //FIXM DEBUG:
// try{
// LOG.d(PLUGIN_NAME + "_DEBUG", String.format("action '%s' with arguments: %s)", action, args.toString(2)));
// }catch(Exception e){}
// Action selector
if (ACTION_RECOGNIZE.equals(action)) {
// recognize speech
startSpeechRecognitionActivity(args, callbackContext, true);
} else if (ACTION_GET_LANGUAGES.equals(action)) {
getSupportedLanguages(callbackContext);
} else if (ACTION_START_RECORDING.equals(action)) {
startSpeechRecognitionActivity(args, callbackContext, false);
} else if (ACTION_STOP_RECORDING.equals(action)) {
stopSpeechInput(callbackContext);
} else if (ACTION_CANCEL.equals(action)) {
cancelSpeechInput(callbackContext);
// } else if (ACTION_MIC_LEVEL.equals(action)) {
// returnMicLevels(callbackContext);
} else if (ACTION_MIC_LEVEL_LISTENER.equals(action)) {
setMicLevelsListener(args, callbackContext);
} else {
// Invalid action
callbackContext.error("Unknown action: " + action);
isValidAction = false;
}
return isValidAction;
}
// private void returnMicLevels(CallbackContext callbackContext) {
// JSONArray list;
// if(currentRecognizer != null){
// list = AudioLevelChange.toJSON(currentRecognizer.getAudioLevels());
// }
// else {
// list = new JSONArray();
// }
//
// callbackContext.success(list);
// }
// Get the list of supported languages
private void getSupportedLanguages(CallbackContext callbackContext) {
if (languageDetailsChecker == null ){
languageDetailsChecker = new LanguageDetailsReceiver(callbackContext);
}
else {
languageDetailsChecker.setCallbackContext(callbackContext);
}
// Create and launch get languages intent
Intent detailsIntent = new Intent(RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS);
cordova.getActivity().sendOrderedBroadcast(detailsIntent, null, languageDetailsChecker, null, Activity.RESULT_OK, null, null);
}
/**
* Fire an intent to start the speech recognition activity.
*
* @param args Argument array with the following string args: [req code][number of matches][prompt string]
*/
private void startSpeechRecognitionActivity(final JSONArray args, final CallbackContext callbackContext, final boolean isWithEndOfSpeechDetection) {
//need to run recognition on UI thread (Android's SpeechRecognizer must run on main thread)
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
_startSpeechRecognitionActivity(args, callbackContext, isWithEndOfSpeechDetection);
}
});
}
private void _startSpeechRecognitionActivity(JSONArray args, CallbackContext callbackContext, boolean isWithEndOfSpeechDetection) {
int maxMatches = 0;
String prompt = "";//TODO remove? (not used when ASR is directly used as service here...)
String language = Locale.getDefault().toString();
boolean isIntermediate = false;
try {
if (args.length() > 0) {
// Optional language specified
language = args.getString(0);
}
if (args.length() > 1) {
isIntermediate = args.getBoolean(1);
}
if (args.length() > 2) {
// Maximum number of matches, 0 means that the recognizer "decides"
String temp = args.getString(2);
maxMatches = Integer.parseInt(temp);
}
if (args.length() > 3) {
// Optional text prompt
prompt = args.getString(3);
}
//TODO if ... withoutEndOfSpeechDetection = ...
}
catch (Exception e) {
Log.e(PLUGIN_NAME, String.format("startSpeechRecognitionActivity exception: %s", e.toString()));
}
// Create the intent and set parameters
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
if(!isWithEndOfSpeechDetection){
// try to simulate start/stop-recording behavior (without end-of-speech detection)
//NOTE these setting do not seem to have any effect for default Google Recognizer API level > 16
intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 10000l);
intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, new Long(10000));
intent.putExtra(RecognizerIntent. EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS , new Long(6 * 1000));
}
if (maxMatches > 0)
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxMatches);
if (!prompt.equals(""))
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
if(isIntermediate)
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
//NOTE the extra package seems to be required for older Android versions, but not since API level 17(?)
if(SDK_VERSION <= Build.VERSION_CODES.JELLY_BEAN)
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, cordova.getActivity().getPackageName());
synchronized (speechLock){
if(speech != null){
speech.destroy();
}
speech = SpeechRecognizer.createSpeechRecognizer(cordova.getActivity());
disableSoundFeedback();
++recCounter;
currentRecognizer = new ASRHandler(recCounter, enableMicLevelsListeners, callbackContext, this);
currentRecognizer.setHapticPrompt( (Vibrator) this.cordova.getActivity().getSystemService(Context.VIBRATOR_SERVICE));
speech.setRecognitionListener(currentRecognizer);
speech.startListening(intent);
}
}
private void stopSpeechInput(final CallbackContext callbackContext){
if(this.speech != null && this.currentRecognizer != null){
//TODO synchronize access on currentRecognizer?
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
synchronized (speechLock) {
if(currentRecognizer != null){
currentRecognizer.stopRecording(callbackContext);
}
if(speech != null){
speech.stopListening();
// speech = null;
}
if(AndroidSpeechRecognizer.this != null){
AndroidSpeechRecognizer.this.enableSoundFeedback();
}
}
}
});
}
else {
callbackContext.error("recording was not started yet");
}
}
private void setMicLevelsListener(final JSONArray args, final CallbackContext callbackContext) {
try {
boolean enabled;
if (args.length() > 0) {
//extract enabled/disabled setting from args
enabled = args.getBoolean(0);
}
else {
callbackContext.error("setMicLevelsListener: missing argument BOOLEAN.");
return; /////////////////// EARLY EXIT //////////////////////////
}
setMicLevelsListener(enabled, callbackContext);
}
catch (Exception e) {
String msg = String.format("setMicLevelsListener exception: %s", e.toString());
Log.e(PLUGIN_NAME, msg);
callbackContext.error(msg);
}
}
private void setMicLevelsListener(final boolean enabled, final CallbackContext callbackContext){
enableMicLevelsListeners = enabled;
if(this.speech != null && this.currentRecognizer != null){
//TODO synchronize access on currentRecognizer?
cordova.getActivity().runOnUiThread(new Runnable() {//TODO test if this can run a background-thread via cordova.getThreadPool()
@Override
public void run() {
synchronized (speechLock) {
if(speech != null && currentRecognizer != null){
currentRecognizer.setRmsChangedEnabled(enabled);
}
}
if(AndroidSpeechRecognizer.this != null){
AndroidSpeechRecognizer.this.enableSoundFeedback();
}
callbackContext.success();
}
});
}
else {
callbackContext.success("recognition is currently not running");
}
}
private void cancelSpeechInput(final CallbackContext callbackContext){
if(speech != null){
//need to run stop-recognition on UI thread (Android's SpeechRecognizer must run on main thread)
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try{
synchronized (speechLock) {
if(speech != null){
speech.destroy();
speech = null;
}
}
if(AndroidSpeechRecognizer.this != null){
AndroidSpeechRecognizer.this.enableSoundFeedback();
}
callbackContext.success();
}
catch(Exception e){
LOG.e(PLUGIN_NAME, "cancelRecoginition: an error occured "+e, e);
callbackContext.error(e.toString());
}
}
});
} else {
callbackContext.success();
}
}
//FIXME TEST private/package-level method that allows canceling recognition
void cancelSpeechInput(){
synchronized (speechLock) {
if(this.speech != null){
speech.destroy();//FIXME russa: speech.stopListening() and speech.cancel() do not seem to do the trick -> onRmsChanged is still called!
speech = null;
}
}
enableSoundFeedback();
}
// /**
// * Handle the results from the recognition activity.
// */
// @Override
// public void onActivityResult(int requestCode, int resultCode, Intent data) {
// if (resultCode == Activity.RESULT_OK) {
// // Fill the list view with the strings the recognizer thought it could have heard
// ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
//
//
// float[] scores = data.getFloatArrayExtra(RecognizerIntent.EXTRA_CONFIDENCE_SCORES);
//
// returnSpeechResults(matches, toList(scores) );
// }
// else {
// // Failure - Let the caller know
// this.callbackContext.error(Integer.toString(resultCode));
// }
//
// super.onActivityResult(requestCode, resultCode, data);
// }
@Override
public void onPause(boolean multitasking) {
enableSoundFeedback();
synchronized (speechLock) {
if(speech != null){
speech.destroy();
speech = null;
}
}
}
@Override
public void onDestroy() {
enableSoundFeedback();
synchronized (speechLock) {
if(speech != null){
speech.destroy();
speech = null;
}
}
}
protected AudioManager mAudioManager;
protected volatile boolean mIsCountDownOn;
private boolean mIsStreamSolo;
private boolean isDisableSoundPrompt(){
//TODO impl. "smarter" detection? (russa: which version added the sounds?)
return SDK_VERSION >= Build.VERSION_CODES.JELLY_BEAN;
}
int soloCounter = 0;
void disableSoundFeedback() {
if(!mIsStreamSolo && isDisableSoundPrompt()){
if(delayedEnableSoundHandler != null){
delayedEnableSoundHandler.cancel();
delayedEnableSoundHandler = null;
}
mAudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
mIsStreamSolo = true;
Log.e(PLUGIN_NAME + "_debug-solostream", "DISABLE SOUND -> solo-counter: "+(++soloCounter));
}
}
void enableSoundFeedback() {
if (mIsStreamSolo){
mAudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);
mIsStreamSolo = false;
Log.e(PLUGIN_NAME + "_debug-solostream", "ENABLE SOUND -> solo-counter: "+(--soloCounter));
}
}
// private Object delayedEnableSoundLock = new Object(); FIXME use lock/synchronized when accessing delayedEnableSoundHandler?
private DelayedEnableSound delayedEnableSoundHandler = null;
private int reenableSoundDelay = 500;//ms <- delay for re-enabling sound after recognition has finished (the delay needs to be long enough to suppress the last (un-wanted) sound-feedback of the recognition)
void enableSoundFeedbackDelayed() {
// TODO implement without running on UI thread & scheduling another
// "thread" (would need Looper impl. when running delayed?)
if(delayedEnableSoundHandler != null){
delayedEnableSoundHandler.cancel();
}
delayedEnableSoundHandler = new DelayedEnableSound();
cordova.getActivity().runOnUiThread(delayedEnableSoundHandler);
}
static Handler delayedSoundHandler = null;
private class DelayedEnableSound implements Runnable {
private Object delayedSoundLock = new Object();
private boolean isCanceled = false;
@Override
public void run() {
synchronized(delayedSoundLock){
if(isCanceled){
return; ////////////////// EARLY EXIT /////////////////////
}
if(delayedSoundHandler == null){
delayedSoundHandler = new Handler();
}
}
boolean isScheduled = delayedSoundHandler.postDelayed(new Runnable() {
@Override
public void run() {
synchronized(delayedSoundLock){
if(isCanceled){
return; ////////////////// EARLY EXIT /////////////////////
}
isCanceled = true;
if (AndroidSpeechRecognizer.this != null) {
AndroidSpeechRecognizer.this.enableSoundFeedback();
}
}
}
}, reenableSoundDelay);
if (!isScheduled) {
synchronized(delayedSoundLock){
if(isCanceled){
return; ////////////////// EARLY EXIT /////////////////////
}
isCanceled = true;
if (AndroidSpeechRecognizer.this != null) {
AndroidSpeechRecognizer.this.enableSoundFeedback();
}
}
}
}
public void cancel(){
synchronized(delayedSoundLock){
if(isCanceled){
return; ////////////////// EARLY EXIT /////////////////////
}
isCanceled = true;
if(delayedSoundHandler != null){
delayedSoundHandler.removeCallbacks(this);
}
}
}
}
}
| FIX removed duplicate code | src/android/de/dfki/iui/mmir/plugins/speech/android/AndroidSpeechRecognizer.java | FIX removed duplicate code |
|
Java | epl-1.0 | 0a7bf9062905b01271f3684618ea36a2e9f27f73 | 0 | sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,Charling-Huang/birt | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.actions;
import java.text.MessageFormat;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.internal.ui.command.WrapperCommandStack;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.editors.ReportEditor;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.activity.ActivityStackEvent;
import org.eclipse.birt.report.model.api.activity.ActivityStackListener;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CommandStack;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;
/**
* Undo/Redo action for contribution of toolbar or menu.
*/
public abstract class StackWindowAction
implements
IWorkbenchWindowActionDelegate
{
private ActivityStackListener commandStackListener = new ActivityStackListener( ) {
public void stackChanged( ActivityStackEvent event )
{
setAction( iaction, canDo( ) );
}
};
private CommandStack commandStack;
private ReportDesignHandle designHandle;
private IAction iaction;
protected String getLabelForCommand( Command command )
{
if ( command == null )
return "";//$NON-NLS-1$
if ( command.getLabel( ) == null )
return "";//$NON-NLS-1$
return command.getLabel( );
}
/**
* Returns command stack listener.
*/
public ActivityStackListener getCommandStackListener( )
{
return commandStackListener;
}
/**
*
*/
public StackWindowAction( )
{
super( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose()
*/
public void dispose( )
{
WrapperCommandStack stack = (WrapperCommandStack) getCommandStack( );
if ( stack != null )
{
stack.removeCommandStackListener( getCommandStackListener( ) );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow)
*/
public void init( IWorkbenchWindow window )
{
WrapperCommandStack stack = (WrapperCommandStack) getCommandStack( );
if ( stack != null )
{
designHandle = getDesignHandle( );
stack.setActivityStack( getDesignHandle( ).getCommandStack( ) );
stack.addCommandStackListener( getCommandStackListener( ) );
}
}
private void resetCommandListener( )
{
WrapperCommandStack stack = (WrapperCommandStack) getCommandStack( );
if ( stack != null && getDesignHandle( ) != designHandle )
{
designHandle = getDesignHandle( );
stack.removeCommandStackListener( getCommandStackListener( ) );
stack.setActivityStack( getDesignHandle( ).getCommandStack( ) );
stack.addCommandStackListener( getCommandStackListener( ) );
}
}
protected CommandStack getCommandStack( )
{
if ( commandStack == null )
{
commandStack = new WrapperCommandStack( );
}
return commandStack;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run( IAction action )
{
if ( canDo( ) )
{
doStack( );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction,
* org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged( IAction action, ISelection selection )
{
iaction = action;
changeEnabled( action );
resetCommandListener( );
}
private void changeEnabled( IAction action )
{
IWorkbenchWindow window = PlatformUI.getWorkbench( )
.getActiveWorkbenchWindow( );
IWorkbenchPage[] pages = window.getPages( );
boolean isEnabled = false;
for ( int i = 0; i < pages.length; i++ )
{
IEditorReference[] refs = pages[i].getEditorReferences( );
for ( int j = 0; j < refs.length; j++ )
{
IEditorPart editor = refs[j].getEditor( false );
if ( editor != null
&& editor.getEditorInput( ) instanceof FileEditorInput )
{
if ( editor instanceof ReportEditor )
{
isEnabled = canDo( );
break;
}
}
}
}
setAction( action, isEnabled );
}
private void setAction( IAction action, boolean isEnabled )
{
action.setEnabled( isEnabled );
changeLabel( action );
}
protected ReportDesignHandle getDesignHandle( )
{
return SessionHandleAdapter.getInstance( ).getReportDesignHandle( );
}
abstract protected boolean canDo( );
abstract protected void doStack( );
abstract protected void changeLabel( IAction action );
public static class UndoWindowAction extends StackWindowAction
{
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.actions.StackWindowAction#canDo()
*/
protected boolean canDo( )
{
return getDesignHandle( ).getCommandStack( ).canUndo( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.actions.StackWindowAction#doStack()
*/
protected void doStack( )
{
getDesignHandle( ).getCommandStack( ).undo( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.actions.StackWindowAction#changeLabel(org.eclipse.jface.action.IAction)
*/
protected void changeLabel( IAction action )
{
Command undoCmd = getCommandStack( ).getUndoCommand( );
action.setToolTipText( MessageFormat.format( Messages.getString("UndoAction_Tooltip"),
new Object[]{
getLabelForCommand( undoCmd )
} )
.trim( ) );
}
}
public static class RedoWindowAction extends StackWindowAction
{
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.actions.StackWindowAction#canDo()
*/
protected boolean canDo( )
{
return getDesignHandle( ).getCommandStack( ).canRedo( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.actions.StackWindowAction#doStack()
*/
protected void doStack( )
{
getDesignHandle( ).getCommandStack( ).redo( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.actions.StackWindowAction#changeLabel(org.eclipse.jface.action.IAction)
*/
protected void changeLabel( IAction action )
{
Command redoCmd = getCommandStack( ).getRedoCommand( );
action.setToolTipText( MessageFormat.format( Messages.getString("RedoAction_Tooltip"),
new Object[]{
getLabelForCommand( redoCmd )
} )
.trim( ) );
}
}
} | UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/actions/StackWindowAction.java | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.actions;
import java.text.MessageFormat;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.internal.ui.command.WrapperCommandStack;
import org.eclipse.birt.report.designer.ui.editors.ReportEditor;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.activity.ActivityStackEvent;
import org.eclipse.birt.report.model.api.activity.ActivityStackListener;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CommandStack;
import org.eclipse.gef.internal.GEFMessages;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;
/**
* Undo/Redo action for contribution of toolbar or menu.
*/
public abstract class StackWindowAction
implements
IWorkbenchWindowActionDelegate
{
private ActivityStackListener commandStackListener = new ActivityStackListener( ) {
public void stackChanged( ActivityStackEvent event )
{
setAction( iaction, canDo( ) );
}
};
private CommandStack commandStack;
private ReportDesignHandle designHandle;
private IAction iaction;
protected String getLabelForCommand( Command command )
{
if ( command == null )
return "";//$NON-NLS-1$
if ( command.getLabel( ) == null )
return "";//$NON-NLS-1$
return command.getLabel( );
}
/**
* Returns command stack listener.
*/
public ActivityStackListener getCommandStackListener( )
{
return commandStackListener;
}
/**
*
*/
public StackWindowAction( )
{
super( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose()
*/
public void dispose( )
{
WrapperCommandStack stack = (WrapperCommandStack) getCommandStack( );
if ( stack != null )
{
stack.removeCommandStackListener( getCommandStackListener( ) );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow)
*/
public void init( IWorkbenchWindow window )
{
WrapperCommandStack stack = (WrapperCommandStack) getCommandStack( );
if ( stack != null )
{
designHandle = getDesignHandle( );
stack.setActivityStack( getDesignHandle( ).getCommandStack( ) );
stack.addCommandStackListener( getCommandStackListener( ) );
}
}
private void resetCommandListener( )
{
WrapperCommandStack stack = (WrapperCommandStack) getCommandStack( );
if ( stack != null && getDesignHandle( ) != designHandle )
{
designHandle = getDesignHandle( );
stack.removeCommandStackListener( getCommandStackListener( ) );
stack.setActivityStack( getDesignHandle( ).getCommandStack( ) );
stack.addCommandStackListener( getCommandStackListener( ) );
}
}
protected CommandStack getCommandStack( )
{
if ( commandStack == null )
{
commandStack = new WrapperCommandStack( );
}
return commandStack;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run( IAction action )
{
if ( canDo( ) )
{
doStack( );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction,
* org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged( IAction action, ISelection selection )
{
iaction = action;
changeEnabled( action );
resetCommandListener( );
}
private void changeEnabled( IAction action )
{
IWorkbenchWindow window = PlatformUI.getWorkbench( )
.getActiveWorkbenchWindow( );
IWorkbenchPage[] pages = window.getPages( );
boolean isEnabled = false;
for ( int i = 0; i < pages.length; i++ )
{
IEditorReference[] refs = pages[i].getEditorReferences( );
for ( int j = 0; j < refs.length; j++ )
{
IEditorPart editor = refs[j].getEditor( false );
if ( editor != null
&& editor.getEditorInput( ) instanceof FileEditorInput )
{
if ( editor instanceof ReportEditor )
{
isEnabled = canDo( );
break;
}
}
}
}
setAction( action, isEnabled );
}
private void setAction( IAction action, boolean isEnabled )
{
action.setEnabled( isEnabled );
changeLabel( action );
}
protected ReportDesignHandle getDesignHandle( )
{
return SessionHandleAdapter.getInstance( ).getReportDesignHandle( );
}
abstract protected boolean canDo( );
abstract protected void doStack( );
abstract protected void changeLabel( IAction action );
public static class UndoWindowAction extends StackWindowAction
{
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.actions.StackWindowAction#canDo()
*/
protected boolean canDo( )
{
return getDesignHandle( ).getCommandStack( ).canUndo( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.actions.StackWindowAction#doStack()
*/
protected void doStack( )
{
getDesignHandle( ).getCommandStack( ).undo( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.actions.StackWindowAction#changeLabel(org.eclipse.jface.action.IAction)
*/
protected void changeLabel( IAction action )
{
Command undoCmd = getCommandStack( ).getUndoCommand( );
action.setToolTipText( MessageFormat.format( GEFMessages.UndoAction_Tooltip,
new Object[]{
getLabelForCommand( undoCmd )
} )
.trim( ) );
}
}
public static class RedoWindowAction extends StackWindowAction
{
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.actions.StackWindowAction#canDo()
*/
protected boolean canDo( )
{
return getDesignHandle( ).getCommandStack( ).canRedo( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.actions.StackWindowAction#doStack()
*/
protected void doStack( )
{
getDesignHandle( ).getCommandStack( ).redo( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.actions.StackWindowAction#changeLabel(org.eclipse.jface.action.IAction)
*/
protected void changeLabel( IAction action )
{
Command redoCmd = getCommandStack( ).getRedoCommand( );
action.setToolTipText( MessageFormat.format( GEFMessages.RedoAction_Tooltip,
new Object[]{
getLabelForCommand( redoCmd )
} )
.trim( ) );
}
}
} | - SCR(s) Resolved:
- Description: Fix bug 78213.Remove reference to eclipse internal APIs in designer .
- Regression ( Yes/No ): no
- Code Owner: DaZhen Gao
- Code Reviewers: GUI SHA,Hongxia Wang, Sissi Zhu
- Tests: Yes
- Test Automated (Yes/No, if no then explain why): No, gui feature
- Branches Involved: Head
- Case Entries Resolved:
- Notes to Developers:
- Notes to QA:
- Notes to Documentation:
- Notes to Configuration Management:
- Notes to Support:
- Notes to Product Marketing:
| UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/actions/StackWindowAction.java | - SCR(s) Resolved: |
|
Java | epl-1.0 | 353fea16c143d34d3d831fec65b1f0754f1d56c4 | 0 | mdht/mdht,mdht/mdht,vadimnehta/mdht,mdht/mdht,drbgfc/mdht,drbgfc/mdht,mdht/mdht,drbgfc/mdht,vadimnehta/mdht,mdht/mdht,drbgfc/mdht,vadimnehta/mdht,vadimnehta/mdht,vadimnehta/mdht,drbgfc/mdht,vadimnehta/mdht,drbgfc/mdht | package org.openhealthtools.mdht.uml.ui.propertytesters;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.edit.provider.DelegatingWrapperItemProvider;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Generalization;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.Property;
import org.openhealthtools.mdht.uml.common.ui.util.IResourceConstants;
import org.openhealthtools.mdht.uml.ui.navigator.UMLDomainNavigatorItem;
public class UmlElement extends PropertyTester {
public boolean test(Object receiver, String propertyName, Object[] args, Object value) {
switch (propertyName) {
case "fromLocal":
return true;
case "isLocalised":
EObject obj = unwrap(receiver);
if (obj instanceof Association) {
Association association = (Association) obj;
for (Property property : association.getMemberEnds()) {
if (property.getType() != null && property.getType().getOwner().equals(property.getOwner())) {
return true;
}
}
}
return false;
case "instanceOf":
return false;
case "isAnAssociation":
return unwrap(receiver) instanceof Association;
case "isProperty":
return unwrap(receiver) instanceof Property;
case "isNamedElement":
return unwrap(receiver) instanceof NamedElement;
default:
return false;
}
//
// boolean ret = false;
//
// try {
// EObject obj = unwrap(receiver);
//
// if (obj == null)
// ;
// else if ("instanceOf".equals(propertyName)) {
// ret = Class.forName(value.toString()).isAssignableFrom(obj.getClass());
// } else if ("isLocalised".equals(propertyName)) {
// if (obj instanceof Association) {
// Property memberEnd = ((Association) obj).getMemberEnds().get(0);
// try {
//
// IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().getActivePart();
// IViewerProvider view = (IViewerProvider) part.getAdapter(IViewerProvider.class);
// TreeViewer tree = (TreeViewer) view.getViewer();
// // isLocalType(getCurrentModel(receiver),
// // memberEnd.getType()) &&
// ret = isLocalised(
// (ITreeContentProvider) tree.getContentProvider(), getCurrentMDHTModel(), receiver, null);
// } catch (Throwable e) {
// }
//
// }
// } else if ("fromLocal".equals(propertyName)) {
//
// try {
// IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().getActivePart();
// IViewerProvider view = (IViewerProvider) part.getAdapter(IViewerProvider.class);
// TreeViewer tree = (TreeViewer) view.getViewer();
// ret = fromCurrentModel(
// (ITreeContentProvider) tree.getContentProvider(), getCurrentMDHTModel(), receiver);
// } catch (Throwable e) {
// }
//
// }
//
// } catch (Throwable e) {
// e.printStackTrace(System.err);
// }
//
// return true;
}
private static EObject unwrap(Object wrapper) {
Object obj = null;
if (wrapper instanceof EObject)
return (EObject) wrapper;
if (wrapper instanceof DelegatingWrapperItemProvider) {
obj = ((DelegatingWrapperItemProvider) wrapper).getValue();
} else if (wrapper instanceof UMLDomainNavigatorItem) {
obj = ((UMLDomainNavigatorItem) wrapper).getEObject();
} else
return null;
return unwrap(obj);
}
private static Package getCurrentMDHTModel() {
TransactionalEditingDomain editingDomain = TransactionalEditingDomain.Registry.INSTANCE.getEditingDomain(
IResourceConstants.EDITING_DOMAIN_ID);
if (editingDomain == null)
return null;
IWorkbenchPart part = null;
try {
part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().getActivePart();
} catch (Throwable e) {
}
if (!(part instanceof IEditorPart) || !(((IEditorPart) part).getEditorInput() instanceof IFileEditorInput))
return null;
String modelFilePath = ((IFileEditorInput) ((IEditorPart) part).getEditorInput()).getFile().getFullPath().toString();
URI resourceURI = URI.createPlatformResourceURI(modelFilePath, false);
for (Resource resource : editingDomain.getResourceSet().getResources())
if (resource.getURI().equals(resourceURI))
for (EObject e : resource.getContents())
if (e instanceof Package)
return (Package) e;
return null;
}
/**
* A util method to test if the selected item from a UI tree structure is a
* descendant of the current IG model structure.
*
* @param provider
* - A model tree content provider where the selected item came
* from.
* @param localModel
* - Local IG model.
* @param selectedItem
* - The currently selected item from the model tree.
*
* @return TRUE if the item rooted from current local IG model. FALSE if the
* item rooted from import models.
*/
private static boolean fromCurrentModel(ITreeContentProvider provider, Package localModel, Object selectedItem) {
boolean rs = false;
EObject currentObj = unwrap(selectedItem);
Object child = selectedItem;
if (selectedItem instanceof UMLDomainNavigatorItem)
child = currentObj;
if (!(currentObj instanceof Association) && !(currentObj instanceof org.eclipse.uml2.uml.Class) &&
!(currentObj instanceof org.eclipse.uml2.uml.Generalization)) {
if (currentObj instanceof Package)
return currentObj == localModel;
return false;
}
rs = fromCurrentModel(provider, localModel, provider.getParent(child));
return rs;
}
/**
* A util method to test if a selected item from a UI tree structure has
* been localised to current IG model. A Nested class path from current
* selected element backward up to first localised element will be checked
* for existance.
*
* @param provider
* - A model tree content provider where the selected item came
* from.
* @param localModel
* - Local IG model.
* @param selectedItem
* - The currently selected item from the model tree.
* @return TRUE if the localised class for this item exist. FALSE otherwise.
*/
private static boolean isLocalised(ITreeContentProvider provider, Package localModel, Object selectedItem,
String previousTypeName) {
EObject currentObj = unwrap(selectedItem);
Object child = selectedItem;
if (selectedItem instanceof UMLDomainNavigatorItem)
child = currentObj;
if (!(currentObj instanceof Association) && !(currentObj instanceof org.eclipse.uml2.uml.Class) &&
!(currentObj instanceof org.eclipse.uml2.uml.Generalization)) {
return false;
}
String part1 = getTypeName(currentObj);
String part2 = (part1 != null) && (previousTypeName != null)
? "::"
: "";
part1 = part1 == null
? ""
: part1;
String part3 = previousTypeName == null
? ""
: previousTypeName;
String typeName = part1 + part2 + part3;
if (isLocalClass(localModel, currentObj)) {
return org.eclipse.uml2.uml.util.UMLUtil.findNamedElements(localModel.eResource(), typeName).size() > 0;
}
return isLocalised(provider, localModel, provider.getParent(child), typeName);
}
private static String getTypeName(EObject obj) {
if (obj instanceof Association) {
return ((Association) obj).getMemberEnds().get(0).getType().getName();
} else if (obj instanceof Generalization) {
return null;
} else if (obj instanceof org.eclipse.uml2.uml.Class) {
return ((org.eclipse.uml2.uml.Class) obj).getQualifiedName();
}
return "";
}
private static boolean isLocalType(Package currentModel, EObject type) {
return currentModel == getOwnerModel(type);
}
private static boolean isLocalClass(Package currentModel, EObject type) {
return isLocalType(currentModel, type) && (type instanceof org.eclipse.uml2.uml.Class);
}
private static Package getOwnerModel(EObject t) {
if (t.eContainer() instanceof Package)
return (Package) t.eContainer();
else
return getOwnerModel(t.eContainer());
}
}
| core/plugins/org.openhealthtools.mdht.uml.ui/src/org/openhealthtools/mdht/uml/ui/propertytesters/UmlElement.java | package org.openhealthtools.mdht.uml.ui.propertytesters;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.edit.provider.DelegatingWrapperItemProvider;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Generalization;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.Property;
import org.openhealthtools.mdht.uml.common.ui.util.IResourceConstants;
import org.openhealthtools.mdht.uml.ui.navigator.UMLDomainNavigatorItem;
public class UmlElement extends PropertyTester {
public boolean test(Object receiver, String propertyName, Object[] args, Object value) {
switch (propertyName) {
case "fromLocal":
return true;
case "isLocalised":
EObject obj = unwrap(receiver);
if (obj instanceof Association) {
Association association = (Association) obj;
for (Property property : association.getMemberEnds()) {
if (property.getType() != null && property.getType().getOwner().equals(property.getOwner())) {
return true;
}
}
}
return false;
case "instanceOf":
return false;
case "isAnAssociation":
return unwrap(receiver) instanceof Association;
default:
return false;
}
//
// boolean ret = false;
//
// try {
// EObject obj = unwrap(receiver);
//
// if (obj == null)
// ;
// else if ("instanceOf".equals(propertyName)) {
// ret = Class.forName(value.toString()).isAssignableFrom(obj.getClass());
// } else if ("isLocalised".equals(propertyName)) {
// if (obj instanceof Association) {
// Property memberEnd = ((Association) obj).getMemberEnds().get(0);
// try {
//
// IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().getActivePart();
// IViewerProvider view = (IViewerProvider) part.getAdapter(IViewerProvider.class);
// TreeViewer tree = (TreeViewer) view.getViewer();
// // isLocalType(getCurrentModel(receiver),
// // memberEnd.getType()) &&
// ret = isLocalised(
// (ITreeContentProvider) tree.getContentProvider(), getCurrentMDHTModel(), receiver, null);
// } catch (Throwable e) {
// }
//
// }
// } else if ("fromLocal".equals(propertyName)) {
//
// try {
// IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().getActivePart();
// IViewerProvider view = (IViewerProvider) part.getAdapter(IViewerProvider.class);
// TreeViewer tree = (TreeViewer) view.getViewer();
// ret = fromCurrentModel(
// (ITreeContentProvider) tree.getContentProvider(), getCurrentMDHTModel(), receiver);
// } catch (Throwable e) {
// }
//
// }
//
// } catch (Throwable e) {
// e.printStackTrace(System.err);
// }
//
// return true;
}
private static EObject unwrap(Object wrapper) {
Object obj = null;
if (wrapper instanceof EObject)
return (EObject) wrapper;
if (wrapper instanceof DelegatingWrapperItemProvider) {
obj = ((DelegatingWrapperItemProvider) wrapper).getValue();
} else if (wrapper instanceof UMLDomainNavigatorItem) {
obj = ((UMLDomainNavigatorItem) wrapper).getEObject();
} else
return null;
return unwrap(obj);
}
private static Package getCurrentMDHTModel() {
TransactionalEditingDomain editingDomain = TransactionalEditingDomain.Registry.INSTANCE.getEditingDomain(IResourceConstants.EDITING_DOMAIN_ID);
if (editingDomain == null)
return null;
IWorkbenchPart part = null;
try {
part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().getActivePart();
} catch (Throwable e) {
}
if (!(part instanceof IEditorPart) || !(((IEditorPart) part).getEditorInput() instanceof IFileEditorInput))
return null;
String modelFilePath = ((IFileEditorInput) ((IEditorPart) part).getEditorInput()).getFile().getFullPath().toString();
URI resourceURI = URI.createPlatformResourceURI(modelFilePath, false);
for (Resource resource : editingDomain.getResourceSet().getResources())
if (resource.getURI().equals(resourceURI))
for (EObject e : resource.getContents())
if (e instanceof Package)
return (Package) e;
return null;
}
/**
* A util method to test if the selected item from a UI tree structure is a
* descendant of the current IG model structure.
*
* @param provider
* - A model tree content provider where the selected item came
* from.
* @param localModel
* - Local IG model.
* @param selectedItem
* - The currently selected item from the model tree.
*
* @return TRUE if the item rooted from current local IG model. FALSE if the
* item rooted from import models.
*/
private static boolean fromCurrentModel(ITreeContentProvider provider, Package localModel, Object selectedItem) {
boolean rs = false;
EObject currentObj = unwrap(selectedItem);
Object child = selectedItem;
if (selectedItem instanceof UMLDomainNavigatorItem)
child = currentObj;
if (!(currentObj instanceof Association) && !(currentObj instanceof org.eclipse.uml2.uml.Class) &&
!(currentObj instanceof org.eclipse.uml2.uml.Generalization)) {
if (currentObj instanceof Package)
return currentObj == localModel;
return false;
}
rs = fromCurrentModel(provider, localModel, provider.getParent(child));
return rs;
}
/**
* A util method to test if a selected item from a UI tree structure has
* been localised to current IG model. A Nested class path from current
* selected element backward up to first localised element will be checked
* for existance.
*
* @param provider
* - A model tree content provider where the selected item came
* from.
* @param localModel
* - Local IG model.
* @param selectedItem
* - The currently selected item from the model tree.
* @return TRUE if the localised class for this item exist. FALSE otherwise.
*/
private static boolean isLocalised(ITreeContentProvider provider, Package localModel, Object selectedItem,
String previousTypeName) {
EObject currentObj = unwrap(selectedItem);
Object child = selectedItem;
if (selectedItem instanceof UMLDomainNavigatorItem)
child = currentObj;
if (!(currentObj instanceof Association) && !(currentObj instanceof org.eclipse.uml2.uml.Class) &&
!(currentObj instanceof org.eclipse.uml2.uml.Generalization)) {
return false;
}
String part1 = getTypeName(currentObj);
String part2 = (part1 != null) && (previousTypeName != null)
? "::"
: "";
part1 = part1 == null
? ""
: part1;
String part3 = previousTypeName == null
? ""
: previousTypeName;
String typeName = part1 + part2 + part3;
if (isLocalClass(localModel, currentObj)) {
return org.eclipse.uml2.uml.util.UMLUtil.findNamedElements(localModel.eResource(), typeName).size() > 0;
}
return isLocalised(provider, localModel, provider.getParent(child), typeName);
}
private static String getTypeName(EObject obj) {
if (obj instanceof Association) {
return ((Association) obj).getMemberEnds().get(0).getType().getName();
} else if (obj instanceof Generalization) {
return null;
} else if (obj instanceof org.eclipse.uml2.uml.Class) {
return ((org.eclipse.uml2.uml.Class) obj).getQualifiedName();
}
return "";
}
private static boolean isLocalType(Package currentModel, EObject type) {
return currentModel == getOwnerModel(type);
}
private static boolean isLocalClass(Package currentModel, EObject type) {
return isLocalType(currentModel, type) && (type instanceof org.eclipse.uml2.uml.Class);
}
private static Package getOwnerModel(EObject t) {
if (t.eContainer() instanceof Package)
return (Package) t.eContainer();
else
return getOwnerModel(t.eContainer());
}
}
| Added isProperty and isNamedElement to UML Property Tester | core/plugins/org.openhealthtools.mdht.uml.ui/src/org/openhealthtools/mdht/uml/ui/propertytesters/UmlElement.java | Added isProperty and isNamedElement to UML Property Tester |
|
Java | mpl-2.0 | e794171b8dbbbd88247ae4eb3a1135bd31081633 | 0 | anthonycr/Lightning-Browser,anthonycr/Lightning-Browser,anthonycr/Lightning-Browser,anthonycr/Lightning-Browser,t61p/Lightning-Browser | /*
* Copyright 2015 Anthony Restaino
*/
package acr.browser.lightning.activity;
import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.ColorInt;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebIconDatabase;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.VideoView;
import com.anthonycr.bonsai.Completable;
import com.anthonycr.bonsai.CompletableOnSubscribe;
import com.anthonycr.bonsai.Schedulers;
import com.anthonycr.bonsai.SingleOnSubscribe;
import com.anthonycr.grant.PermissionsManager;
import com.anthonycr.progress.AnimatedProgressBar;
import java.io.File;
import java.io.IOException;
import javax.inject.Inject;
import acr.browser.lightning.R;
import acr.browser.lightning.app.BrowserApp;
import acr.browser.lightning.browser.BookmarksView;
import acr.browser.lightning.browser.BrowserPresenter;
import acr.browser.lightning.browser.BrowserView;
import acr.browser.lightning.browser.TabsView;
import acr.browser.lightning.constant.BookmarkPage;
import acr.browser.lightning.constant.Constants;
import acr.browser.lightning.constant.HistoryPage;
import acr.browser.lightning.controller.UIController;
import acr.browser.lightning.database.HistoryItem;
import acr.browser.lightning.database.bookmark.BookmarkModel;
import acr.browser.lightning.database.history.HistoryModel;
import acr.browser.lightning.dialog.BrowserDialog;
import acr.browser.lightning.dialog.LightningDialogBuilder;
import acr.browser.lightning.fragment.BookmarksFragment;
import acr.browser.lightning.fragment.TabsFragment;
import acr.browser.lightning.interpolator.BezierDecelerateInterpolator;
import acr.browser.lightning.receiver.NetworkReceiver;
import acr.browser.lightning.search.SuggestionsAdapter;
import acr.browser.lightning.utils.DrawableUtils;
import acr.browser.lightning.utils.Preconditions;
import acr.browser.lightning.utils.ProxyUtils;
import acr.browser.lightning.utils.ThemeUtils;
import acr.browser.lightning.utils.UrlUtils;
import acr.browser.lightning.utils.Utils;
import acr.browser.lightning.utils.WebUtils;
import acr.browser.lightning.view.Handlers;
import acr.browser.lightning.view.LightningView;
import acr.browser.lightning.view.SearchView;
import butterknife.BindView;
import butterknife.ButterKnife;
public abstract class BrowserActivity extends ThemableBrowserActivity implements BrowserView, UIController, OnClickListener {
private static final String TAG = "BrowserActivity";
private static final String INTENT_PANIC_TRIGGER = "info.guardianproject.panic.action.TRIGGER";
private static final String TAG_BOOKMARK_FRAGMENT = "TAG_BOOKMARK_FRAGMENT";
private static final String TAG_TABS_FRAGMENT = "TAG_TABS_FRAGMENT";
// Static Layout
@BindView(R.id.drawer_layout) DrawerLayout mDrawerLayout;
@BindView(R.id.content_frame) FrameLayout mBrowserFrame;
@BindView(R.id.left_drawer) ViewGroup mDrawerLeft;
@BindView(R.id.right_drawer) ViewGroup mDrawerRight;
@BindView(R.id.ui_layout) ViewGroup mUiLayout;
@BindView(R.id.toolbar_layout) ViewGroup mToolbarLayout;
@BindView(R.id.progress_view) AnimatedProgressBar mProgressBar;
@BindView(R.id.search_bar) RelativeLayout mSearchBar;
// Toolbar Views
@BindView(R.id.toolbar) Toolbar mToolbar;
private View mSearchBackground;
private SearchView mSearch;
private ImageView mArrowImage;
// Current tab view being displayed
@Nullable private View mCurrentView;
// Full Screen Video Views
private FrameLayout mFullscreenContainer;
private VideoView mVideoView;
private View mCustomView;
// Adapter
private SuggestionsAdapter mSuggestionsAdapter;
// Callback
private CustomViewCallback mCustomViewCallback;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> mFilePathCallback;
// Primitives
private boolean mFullScreen;
private boolean mDarkTheme;
private boolean mIsFullScreen = false;
private boolean mIsImmersive = false;
private boolean mShowTabsInDrawer;
private boolean mSwapBookmarksAndTabs;
private int mOriginalOrientation;
private int mBackgroundColor;
private int mIconColor;
private int mDisabledIconColor;
private int mCurrentUiColor = Color.BLACK;
private long mKeyDownStartTime;
private String mSearchText;
private String mUntitledTitle;
private String mCameraPhotoPath;
// The singleton BookmarkManager
@Inject BookmarkModel mBookmarkManager;
@Inject LightningDialogBuilder mBookmarksDialogBuilder;
private TabsManager mTabsManager;
// Image
private Bitmap mWebpageBitmap;
private final ColorDrawable mBackground = new ColorDrawable();
private Drawable mDeleteIcon, mRefreshIcon, mClearIcon, mIcon;
private BrowserPresenter mPresenter;
private TabsView mTabsView;
private BookmarksView mBookmarksView;
// Proxy
@Inject ProxyUtils mProxyUtils;
// Constant
private static final int API = android.os.Build.VERSION.SDK_INT;
private static final String NETWORK_BROADCAST_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
private static final LayoutParams MATCH_PARENT = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
private static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
protected abstract boolean isIncognito();
public abstract void closeActivity();
public abstract void updateHistory(@Nullable final String title, @NonNull final String url);
@NonNull
abstract Completable updateCookiePreference();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BrowserApp.getAppComponent().inject(this);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mTabsManager = new TabsManager();
mPresenter = new BrowserPresenter(this, isIncognito());
initialize(savedInstanceState);
}
private synchronized void initialize(Bundle savedInstanceState) {
initializeToolbarHeight(getResources().getConfiguration());
setSupportActionBar(mToolbar);
ActionBar actionBar = getSupportActionBar();
//TODO make sure dark theme flag gets set correctly
mDarkTheme = mPreferences.getUseTheme() != 0 || isIncognito();
mIconColor = mDarkTheme ? ThemeUtils.getIconDarkThemeColor(this) : ThemeUtils.getIconLightThemeColor(this);
mDisabledIconColor = mDarkTheme ? ContextCompat.getColor(this, R.color.icon_dark_theme_disabled) :
ContextCompat.getColor(this, R.color.icon_light_theme_disabled);
mShowTabsInDrawer = mPreferences.getShowTabsInDrawer(!isTablet());
mSwapBookmarksAndTabs = mPreferences.getBookmarksAndTabsSwapped();
// initialize background ColorDrawable
int primaryColor = ThemeUtils.getPrimaryColor(this);
mBackground.setColor(primaryColor);
// Drawer stutters otherwise
mDrawerLeft.setLayerType(View.LAYER_TYPE_NONE, null);
mDrawerRight.setLayerType(View.LAYER_TYPE_NONE, null);
mDrawerLayout.addDrawerListener(new DrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {}
@Override
public void onDrawerOpened(View drawerView) {}
@Override
public void onDrawerClosed(View drawerView) {}
@Override
public void onDrawerStateChanged(int newState) {
if (newState == DrawerLayout.STATE_DRAGGING) {
mDrawerLeft.setLayerType(View.LAYER_TYPE_HARDWARE, null);
mDrawerRight.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (newState == DrawerLayout.STATE_IDLE) {
mDrawerLeft.setLayerType(View.LAYER_TYPE_NONE, null);
mDrawerRight.setLayerType(View.LAYER_TYPE_NONE, null);
}
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !mShowTabsInDrawer) {
getWindow().setStatusBarColor(Color.BLACK);
}
setNavigationDrawerWidth();
mDrawerLayout.addDrawerListener(new DrawerLocker());
mWebpageBitmap = ThemeUtils.getThemedBitmap(this, R.drawable.ic_webpage, mDarkTheme);
final FragmentManager fragmentManager = getSupportFragmentManager();
TabsFragment tabsFragment = (TabsFragment) fragmentManager.findFragmentByTag(TAG_TABS_FRAGMENT);
BookmarksFragment bookmarksFragment = (BookmarksFragment) fragmentManager.findFragmentByTag(TAG_BOOKMARK_FRAGMENT);
if (tabsFragment != null) {
fragmentManager.beginTransaction().remove(tabsFragment).commit();
}
tabsFragment = TabsFragment.createTabsFragment(isIncognito(), mShowTabsInDrawer);
mTabsView = tabsFragment;
if (bookmarksFragment != null) {
fragmentManager.beginTransaction().remove(bookmarksFragment).commit();
}
bookmarksFragment = BookmarksFragment.createFragment(isIncognito());
mBookmarksView = bookmarksFragment;
fragmentManager.executePendingTransactions();
fragmentManager
.beginTransaction()
.replace(getTabsFragmentViewId(), tabsFragment, TAG_TABS_FRAGMENT)
.replace(getBookmarksFragmentViewId(), bookmarksFragment, TAG_BOOKMARK_FRAGMENT)
.commit();
if (mShowTabsInDrawer) {
mToolbarLayout.removeView(findViewById(R.id.tabs_toolbar_container));
}
Preconditions.checkNonNull(actionBar);
// set display options of the ActionBar
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(R.layout.toolbar_content);
View customView = actionBar.getCustomView();
LayoutParams lp = customView.getLayoutParams();
lp.width = LayoutParams.MATCH_PARENT;
lp.height = LayoutParams.MATCH_PARENT;
customView.setLayoutParams(lp);
mArrowImage = (ImageView) customView.findViewById(R.id.arrow);
FrameLayout arrowButton = (FrameLayout) customView.findViewById(R.id.arrow_button);
if (mShowTabsInDrawer) {
if (mArrowImage.getWidth() <= 0) {
mArrowImage.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
}
updateTabNumber(0);
// Post drawer locking in case the activity is being recreated
Handlers.MAIN.post(new Runnable() {
@Override
public void run() {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, getTabDrawer());
}
});
} else {
// Post drawer locking in case the activity is being recreated
Handlers.MAIN.post(new Runnable() {
@Override
public void run() {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, getTabDrawer());
}
});
mArrowImage.setImageResource(R.drawable.ic_action_home);
mArrowImage.setColorFilter(mIconColor, PorterDuff.Mode.SRC_IN);
}
// Post drawer locking in case the activity is being recreated
Handlers.MAIN.post(new Runnable() {
@Override
public void run() {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, getBookmarkDrawer());
}
});
arrowButton.setOnClickListener(this);
// create the search EditText in the ToolBar
mSearch = (SearchView) customView.findViewById(R.id.search);
mSearchBackground = customView.findViewById(R.id.search_container);
// initialize search background color
mSearchBackground.getBackground().setColorFilter(getSearchBarColor(primaryColor, primaryColor), PorterDuff.Mode.SRC_IN);
mSearch.setHintTextColor(ThemeUtils.getThemedTextHintColor(mDarkTheme));
mSearch.setTextColor(mDarkTheme ? Color.WHITE : Color.BLACK);
mUntitledTitle = getString(R.string.untitled);
mBackgroundColor = ThemeUtils.getPrimaryColor(this);
mDeleteIcon = ThemeUtils.getThemedDrawable(this, R.drawable.ic_action_delete, mDarkTheme);
mRefreshIcon = ThemeUtils.getThemedDrawable(this, R.drawable.ic_action_refresh, mDarkTheme);
mClearIcon = ThemeUtils.getThemedDrawable(this, R.drawable.ic_action_delete, mDarkTheme);
int iconBounds = Utils.dpToPx(24);
mDeleteIcon.setBounds(0, 0, iconBounds, iconBounds);
mRefreshIcon.setBounds(0, 0, iconBounds, iconBounds);
mClearIcon.setBounds(0, 0, iconBounds, iconBounds);
mIcon = mRefreshIcon;
SearchListenerClass search = new SearchListenerClass();
mSearch.setCompoundDrawablePadding(Utils.dpToPx(3));
mSearch.setCompoundDrawables(null, null, mRefreshIcon, null);
mSearch.setOnKeyListener(search);
mSearch.setOnFocusChangeListener(search);
mSearch.setOnEditorActionListener(search);
mSearch.setOnTouchListener(search);
mSearch.setOnPreFocusListener(search);
initializeSearchSuggestions(mSearch);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_right_shadow, GravityCompat.END);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_left_shadow, GravityCompat.START);
if (API <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
//noinspection deprecation
WebIconDatabase.getInstance().open(getDir("icons", MODE_PRIVATE).getPath());
}
@SuppressWarnings("VariableNotUsedInsideIf")
Intent intent = savedInstanceState == null ? getIntent() : null;
boolean launchedFromHistory = intent != null && (intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0;
if (isPanicTrigger(intent)) {
setIntent(null);
panicClean();
} else {
if (launchedFromHistory) {
intent = null;
}
mPresenter.setupTabs(intent);
setIntent(null);
mProxyUtils.checkForProxy(this);
}
}
@IdRes
private int getBookmarksFragmentViewId() {
return mSwapBookmarksAndTabs ? R.id.left_drawer : R.id.right_drawer;
}
private int getTabsFragmentViewId() {
if (mShowTabsInDrawer) {
return mSwapBookmarksAndTabs ? R.id.right_drawer : R.id.left_drawer;
} else {
return R.id.tabs_toolbar_container;
}
}
/**
* Determines if an intent is originating
* from a panic trigger.
*
* @param intent the intent to check.
* @return true if the panic trigger sent
* the intent, false otherwise.
*/
static boolean isPanicTrigger(@Nullable Intent intent) {
return intent != null && INTENT_PANIC_TRIGGER.equals(intent.getAction());
}
void panicClean() {
Log.d(TAG, "Closing browser");
mTabsManager.newTab(this, "", false);
mTabsManager.switchToTab(0);
mTabsManager.clearSavedState();
HistoryPage.deleteHistoryPage(getApplication()).subscribe();
closeBrowser();
// System exit needed in the case of receiving
// the panic intent since finish() isn't completely
// closing the browser
System.exit(1);
}
private class SearchListenerClass implements OnKeyListener, OnEditorActionListener,
OnFocusChangeListener, OnTouchListener, SearchView.PreFocusListener {
@Override
public boolean onKey(View searchView, int keyCode, KeyEvent keyEvent) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mSearch.getWindowToken(), 0);
searchTheWeb(mSearch.getText().toString());
final LightningView currentView = mTabsManager.getCurrentTab();
if (currentView != null) {
currentView.requestFocus();
}
return true;
default:
break;
}
return false;
}
@Override
public boolean onEditorAction(TextView arg0, int actionId, KeyEvent arg2) {
// hide the keyboard and search the web when the enter key
// button is pressed
if (actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_DONE
|| actionId == EditorInfo.IME_ACTION_NEXT
|| actionId == EditorInfo.IME_ACTION_SEND
|| actionId == EditorInfo.IME_ACTION_SEARCH
|| (arg2.getAction() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mSearch.getWindowToken(), 0);
searchTheWeb(mSearch.getText().toString());
final LightningView currentView = mTabsManager.getCurrentTab();
if (currentView != null) {
currentView.requestFocus();
}
return true;
}
return false;
}
@Override
public void onFocusChange(final View v, final boolean hasFocus) {
final LightningView currentView = mTabsManager.getCurrentTab();
if (!hasFocus && currentView != null) {
setIsLoading(currentView.getProgress() < 100);
updateUrl(currentView.getUrl(), true);
} else if (hasFocus && currentView != null) {
// Hack to make sure the text gets selected
((SearchView) v).selectAll();
mIcon = mClearIcon;
mSearch.setCompoundDrawables(null, null, mClearIcon, null);
}
if (!hasFocus) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mSearch.getWindowToken(), 0);
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mSearch.getCompoundDrawables()[2] != null) {
boolean tappedX = event.getX() > (mSearch.getWidth()
- mSearch.getPaddingRight() - mIcon.getIntrinsicWidth());
if (tappedX) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mSearch.hasFocus()) {
mSearch.setText("");
} else {
refreshOrStop();
}
}
return true;
}
}
return false;
}
@Override
public void onPreFocus() {
final LightningView currentView = mTabsManager.getCurrentTab();
if (currentView == null) {
return;
}
String url = currentView.getUrl();
if (!UrlUtils.isSpecialUrl(url)) {
if (!mSearch.hasFocus()) {
mSearch.setText(url);
}
}
}
}
private class DrawerLocker implements DrawerListener {
@Override
public void onDrawerClosed(View v) {
View tabsDrawer = getTabDrawer();
View bookmarksDrawer = getBookmarkDrawer();
if (v == tabsDrawer) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, bookmarksDrawer);
} else if (mShowTabsInDrawer) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, tabsDrawer);
}
}
@Override
public void onDrawerOpened(View v) {
View tabsDrawer = getTabDrawer();
View bookmarksDrawer = getBookmarkDrawer();
if (v == tabsDrawer) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, bookmarksDrawer);
} else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, tabsDrawer);
}
}
@Override
public void onDrawerSlide(View v, float arg) {}
@Override
public void onDrawerStateChanged(int arg) {}
}
private void setNavigationDrawerWidth() {
int width = getResources().getDisplayMetrics().widthPixels - Utils.dpToPx(56);
int maxWidth;
if (isTablet()) {
maxWidth = Utils.dpToPx(320);
} else {
maxWidth = Utils.dpToPx(300);
}
if (width > maxWidth) {
DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerLeft
.getLayoutParams();
params.width = maxWidth;
mDrawerLeft.setLayoutParams(params);
mDrawerLeft.requestLayout();
DrawerLayout.LayoutParams paramsRight = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerRight
.getLayoutParams();
paramsRight.width = maxWidth;
mDrawerRight.setLayoutParams(paramsRight);
mDrawerRight.requestLayout();
} else {
DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerLeft
.getLayoutParams();
params.width = width;
mDrawerLeft.setLayoutParams(params);
mDrawerLeft.requestLayout();
DrawerLayout.LayoutParams paramsRight = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerRight
.getLayoutParams();
paramsRight.width = width;
mDrawerRight.setLayoutParams(paramsRight);
mDrawerRight.requestLayout();
}
}
private void initializePreferences() {
final LightningView currentView = mTabsManager.getCurrentTab();
mFullScreen = mPreferences.getFullScreenEnabled();
boolean colorMode = mPreferences.getColorModeEnabled();
colorMode &= !mDarkTheme;
if (!isIncognito() && !colorMode && !mDarkTheme && mWebpageBitmap != null) {
changeToolbarBackground(mWebpageBitmap, null);
} else if (!isIncognito() && currentView != null && !mDarkTheme) {
changeToolbarBackground(currentView.getFavicon(), null);
} else if (!isIncognito() && !mDarkTheme && mWebpageBitmap != null) {
changeToolbarBackground(mWebpageBitmap, null);
}
FragmentManager manager = getSupportFragmentManager();
Fragment tabsFragment = manager.findFragmentByTag(TAG_TABS_FRAGMENT);
if (tabsFragment instanceof TabsFragment) {
((TabsFragment) tabsFragment).reinitializePreferences();
}
Fragment bookmarksFragment = manager.findFragmentByTag(TAG_BOOKMARK_FRAGMENT);
if (bookmarksFragment instanceof BookmarksFragment) {
((BookmarksFragment) bookmarksFragment).reinitializePreferences();
}
// TODO layout transition causing memory leak
// mBrowserFrame.setLayoutTransition(new LayoutTransition());
setFullscreen(mPreferences.getHideStatusBarEnabled(), false);
switch (mPreferences.getSearchChoice()) {
case 0:
mSearchText = mPreferences.getSearchUrl();
if (!mSearchText.startsWith(Constants.HTTP)
&& !mSearchText.startsWith(Constants.HTTPS)) {
mSearchText = Constants.GOOGLE_SEARCH;
}
break;
case 1:
mSearchText = Constants.GOOGLE_SEARCH;
break;
case 2:
mSearchText = Constants.ASK_SEARCH;
break;
case 3:
mSearchText = Constants.BING_SEARCH;
break;
case 4:
mSearchText = Constants.YAHOO_SEARCH;
break;
case 5:
mSearchText = Constants.STARTPAGE_SEARCH;
break;
case 6:
mSearchText = Constants.STARTPAGE_MOBILE_SEARCH;
break;
case 7:
mSearchText = Constants.DUCK_SEARCH;
break;
case 8:
mSearchText = Constants.DUCK_LITE_SEARCH;
break;
case 9:
mSearchText = Constants.BAIDU_SEARCH;
break;
case 10:
mSearchText = Constants.YANDEX_SEARCH;
break;
}
updateCookiePreference().subscribeOn(Schedulers.worker()).subscribe();
mProxyUtils.updateProxySettings(this);
}
@Override
public void onWindowVisibleToUserAfterResume() {
super.onWindowVisibleToUserAfterResume();
mToolbarLayout.setTranslationY(0);
setWebViewTranslation(mToolbarLayout.getHeight());
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (mSearch.hasFocus()) {
searchTheWeb(mSearch.getText().toString());
}
} else if ((keyCode == KeyEvent.KEYCODE_MENU)
&& (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN)
&& (Build.MANUFACTURER.compareTo("LGE") == 0)) {
// Workaround for stupid LG devices that crash
return true;
} else if (keyCode == KeyEvent.KEYCODE_BACK) {
mKeyDownStartTime = System.currentTimeMillis();
Handlers.MAIN.postDelayed(mLongPressBackRunnable, ViewConfiguration.getLongPressTimeout());
}
return super.onKeyDown(keyCode, event);
}
private final Runnable mLongPressBackRunnable = new Runnable() {
@Override
public void run() {
final LightningView currentTab = mTabsManager.getCurrentTab();
showCloseDialog(mTabsManager.positionOf(currentTab));
}
};
@Override
public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_MENU)
&& (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN)
&& (Build.MANUFACTURER.compareTo("LGE") == 0)) {
// Workaround for stupid LG devices that crash
openOptionsMenu();
return true;
} else if (keyCode == KeyEvent.KEYCODE_BACK) {
Handlers.MAIN.removeCallbacks(mLongPressBackRunnable);
if ((System.currentTimeMillis() - mKeyDownStartTime) > ViewConfiguration.getLongPressTimeout()) {
return true;
}
}
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final LightningView currentView = mTabsManager.getCurrentTab();
final String currentUrl = currentView != null ? currentView.getUrl() : null;
// Handle action buttons
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(getBookmarkDrawer())) {
mDrawerLayout.closeDrawer(getBookmarkDrawer());
}
return true;
case R.id.action_back:
if (currentView != null && currentView.canGoBack()) {
currentView.goBack();
}
return true;
case R.id.action_forward:
if (currentView != null && currentView.canGoForward()) {
currentView.goForward();
}
return true;
case R.id.action_add_to_homescreen:
if (currentView != null) {
HistoryItem shortcut = new HistoryItem(currentView.getUrl(), currentView.getTitle());
shortcut.setBitmap(currentView.getFavicon());
Utils.createShortcut(this, shortcut);
}
return true;
case R.id.action_new_tab:
newTab(null, true);
return true;
case R.id.action_incognito:
startActivity(new Intent(this, IncognitoActivity.class));
overridePendingTransition(R.anim.slide_up_in, R.anim.fade_out_scale);
return true;
case R.id.action_share:
if (currentUrl != null && !UrlUtils.isSpecialUrl(currentUrl)) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, currentView.getTitle());
shareIntent.putExtra(Intent.EXTRA_TEXT, currentUrl);
startActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.dialog_title_share)));
}
return true;
case R.id.action_bookmarks:
openBookmarks();
return true;
case R.id.action_copy:
if (currentUrl != null && !UrlUtils.isSpecialUrl(currentUrl)) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", currentUrl);
clipboard.setPrimaryClip(clip);
Utils.showSnackbar(this, R.string.message_link_copied);
}
return true;
case R.id.action_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.action_history:
openHistory();
return true;
case R.id.action_add_bookmark:
if (currentUrl != null && !UrlUtils.isSpecialUrl(currentUrl)) {
addBookmark(currentView.getTitle(), currentUrl);
}
return true;
case R.id.action_find:
findInPage();
return true;
case R.id.action_reading_mode:
if (currentUrl != null) {
Intent read = new Intent(this, ReadingActivity.class);
read.putExtra(Constants.LOAD_READING_URL, currentUrl);
startActivity(read);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// By using a manager, adds a bookmark and notifies third parties about that
private void addBookmark(final String title, final String url) {
final HistoryItem item = new HistoryItem(url, title);
mBookmarkManager.addBookmarkIfNotExists(item)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.main())
.subscribe(new SingleOnSubscribe<Boolean>() {
@Override
public void onItem(@Nullable Boolean item) {
if (Boolean.TRUE.equals(item)) {
mSuggestionsAdapter.refreshBookmarks();
mBookmarksView.handleUpdatedUrl(url);
}
}
});
}
private void deleteBookmark(final String title, final String url) {
final HistoryItem item = new HistoryItem(url, title);
mBookmarkManager.deleteBookmark(item)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.main())
.subscribe(new SingleOnSubscribe<Boolean>() {
@Override
public void onItem(@Nullable Boolean item) {
if (Boolean.TRUE.equals(item)) {
mSuggestionsAdapter.refreshBookmarks();
mBookmarksView.handleUpdatedUrl(url);
}
}
});
}
private void putToolbarInRoot() {
if (mToolbarLayout.getParent() != mUiLayout) {
if (mToolbarLayout.getParent() != null) {
((ViewGroup) mToolbarLayout.getParent()).removeView(mToolbarLayout);
}
mUiLayout.addView(mToolbarLayout, 0);
mUiLayout.requestLayout();
}
setWebViewTranslation(0);
}
private void overlayToolbarOnWebView() {
if (mToolbarLayout.getParent() != mBrowserFrame) {
if (mToolbarLayout.getParent() != null) {
((ViewGroup) mToolbarLayout.getParent()).removeView(mToolbarLayout);
}
mBrowserFrame.addView(mToolbarLayout);
mBrowserFrame.requestLayout();
}
setWebViewTranslation(mToolbarLayout.getHeight());
}
private void setWebViewTranslation(float translation) {
if (mFullScreen && mCurrentView != null) {
mCurrentView.setTranslationY(translation);
} else if (mCurrentView != null) {
mCurrentView.setTranslationY(0);
}
}
/**
* method that shows a dialog asking what string the user wishes to search
* for. It highlights the text entered.
*/
private void findInPage() {
BrowserDialog.showEditText(this,
R.string.action_find,
R.string.search_hint,
R.string.search_hint, new BrowserDialog.EditorListener() {
@Override
public void onClick(String text) {
if (!TextUtils.isEmpty(text)) {
mPresenter.findInPage(text);
showFindInPageControls(text);
}
}
});
}
private void showFindInPageControls(@NonNull String text) {
mSearchBar.setVisibility(View.VISIBLE);
TextView tw = (TextView) findViewById(R.id.search_query);
tw.setText('\'' + text + '\'');
ImageButton up = (ImageButton) findViewById(R.id.button_next);
up.setOnClickListener(this);
ImageButton down = (ImageButton) findViewById(R.id.button_back);
down.setOnClickListener(this);
ImageButton quit = (ImageButton) findViewById(R.id.button_quit);
quit.setOnClickListener(this);
}
@Override
public TabsManager getTabModel() {
return mTabsManager;
}
@Override
public void showCloseDialog(final int position) {
if (position < 0) {
return;
}
BrowserDialog.show(this, R.string.dialog_title_close_browser,
new BrowserDialog.Item(R.string.close_tab) {
@Override
public void onClick() {
mPresenter.deleteTab(position);
}
},
new BrowserDialog.Item(R.string.close_other_tabs) {
@Override
public void onClick() {
mPresenter.closeAllOtherTabs();
}
},
new BrowserDialog.Item(R.string.close_all_tabs) {
@Override
public void onClick() {
closeBrowser();
}
});
}
@Override
public void notifyTabViewRemoved(int position) {
Log.d(TAG, "Notify Tab Removed: " + position);
mTabsView.tabRemoved(position);
}
@Override
public void notifyTabViewAdded() {
Log.d(TAG, "Notify Tab Added");
mTabsView.tabAdded();
}
@Override
public void notifyTabViewChanged(int position) {
Log.d(TAG, "Notify Tab Changed: " + position);
mTabsView.tabChanged(position);
}
@Override
public void notifyTabViewInitialized() {
Log.d(TAG, "Notify Tabs Initialized");
mTabsView.tabsInitialized();
}
@Override
public void tabChanged(LightningView tab) {
mPresenter.tabChangeOccurred(tab);
}
@Override
public void removeTabView() {
Log.d(TAG, "Remove the tab view");
// Set the background color so the color mode color doesn't show through
mBrowserFrame.setBackgroundColor(mBackgroundColor);
removeViewFromParent(mCurrentView);
mCurrentView = null;
// Use a delayed handler to make the transition smooth
// otherwise it will get caught up with the showTab code
// and cause a janky motion
Handlers.MAIN.postDelayed(new Runnable() {
@Override
public void run() {
mDrawerLayout.closeDrawers();
}
}, 200);
}
@Override
public void setTabView(@NonNull final View view) {
if (mCurrentView == view) {
return;
}
Log.d(TAG, "Setting the tab view");
// Set the background color so the color mode color doesn't show through
mBrowserFrame.setBackgroundColor(mBackgroundColor);
removeViewFromParent(view);
removeViewFromParent(mCurrentView);
mBrowserFrame.addView(view, 0, MATCH_PARENT);
if (mFullScreen) {
view.setTranslationY(mToolbarLayout.getHeight() + mToolbarLayout.getTranslationY());
} else {
view.setTranslationY(0);
}
view.requestFocus();
mCurrentView = view;
showActionBar();
// Use a delayed handler to make the transition smooth
// otherwise it will get caught up with the showTab code
// and cause a janky motion
Handlers.MAIN.postDelayed(new Runnable() {
@Override
public void run() {
mDrawerLayout.closeDrawers();
}
}, 200);
// Handlers.MAIN.postDelayed(new Runnable() {
// @Override
// public void run() {
// Remove browser frame background to reduce overdraw
//TODO evaluate performance
// mBrowserFrame.setBackgroundColor(Color.TRANSPARENT);
// }
// }, 300);
}
@Override
public void showBlockedLocalFileDialog(DialogInterface.OnClickListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
Dialog dialog = builder.setCancelable(true)
.setTitle(R.string.title_warning)
.setMessage(R.string.message_blocked_local)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.action_open, listener)
.show();
BrowserDialog.setDialogSize(this, dialog);
}
@Override
public void showSnackbar(@StringRes int resource) {
Utils.showSnackbar(this, resource);
}
@Override
public void tabCloseClicked(int position) {
mPresenter.deleteTab(position);
}
@Override
public void tabClicked(int position) {
showTab(position);
}
@Override
public void newTabButtonClicked() {
mPresenter.newTab(null, true);
}
@Override
public void newTabButtonLongClicked() {
String url = mPreferences.getSavedUrl();
if (url != null) {
newTab(url, true);
Utils.showSnackbar(this, R.string.deleted_tab);
}
mPreferences.setSavedUrl(null);
}
@Override
public void bookmarkButtonClicked() {
final LightningView currentTab = mTabsManager.getCurrentTab();
final String url = currentTab != null ? currentTab.getUrl() : null;
final String title = currentTab != null ? currentTab.getTitle() : null;
if (url == null) {
return;
}
if (!UrlUtils.isSpecialUrl(url)) {
mBookmarkManager.isBookmark(url)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.main())
.subscribe(new SingleOnSubscribe<Boolean>() {
@Override
public void onItem(@Nullable Boolean item) {
if (Boolean.TRUE.equals(item)) {
deleteBookmark(title, url);
} else {
addBookmark(title, url);
}
}
});
}
}
@Override
public void bookmarkItemClicked(@NonNull HistoryItem item) {
mPresenter.loadUrlInCurrentView(item.getUrl());
// keep any jank from happening when the drawer is closed after the
// URL starts to load
Handlers.MAIN.postDelayed(new Runnable() {
@Override
public void run() {
closeDrawers(null);
}
}, 150);
}
@Override
public void handleHistoryChange() {
openHistory();
}
/**
* displays the WebView contained in the LightningView Also handles the
* removal of previous views
*
* @param position the poition of the tab to display
*/
// TODO move to presenter
private synchronized void showTab(final int position) {
mPresenter.tabChanged(position);
}
private static void removeViewFromParent(@Nullable View view) {
if (view == null) {
return;
}
ViewParent parent = view.getParent();
if (parent instanceof ViewGroup) {
((ViewGroup) parent).removeView(view);
}
}
void handleNewIntent(Intent intent) {
mPresenter.onNewIntent(intent);
}
@Override
public void closeEmptyTab() {
// Currently do nothing
// Possibly closing the current tab might close the browser
// and mess stuff up
}
@Override
public void onTrimMemory(int level) {
if (level > TRIM_MEMORY_MODERATE && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
Log.d(TAG, "Low Memory, Free Memory");
mPresenter.onAppLowMemory();
}
}
// TODO move to presenter
private synchronized boolean newTab(String url, boolean show) {
return mPresenter.newTab(url, show);
}
void performExitCleanUp() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (mPreferences.getClearCacheExit() && currentTab != null && !isIncognito()) {
WebUtils.clearCache(currentTab.getWebView());
Log.d(TAG, "Cache Cleared");
}
if (mPreferences.getClearHistoryExitEnabled() && !isIncognito()) {
WebUtils.clearHistory(this);
Log.d(TAG, "History Cleared");
}
if (mPreferences.getClearCookiesExitEnabled() && !isIncognito()) {
WebUtils.clearCookies(this);
Log.d(TAG, "Cookies Cleared");
}
if (mPreferences.getClearWebStorageExitEnabled() && !isIncognito()) {
WebUtils.clearWebStorage();
Log.d(TAG, "WebStorage Cleared");
} else if (isIncognito()) {
WebUtils.clearWebStorage(); // We want to make sure incognito mode is secure
}
mSuggestionsAdapter.clearCache();
}
@Override
public void onConfigurationChanged(final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, "onConfigurationChanged");
if (mFullScreen) {
showActionBar();
mToolbarLayout.setTranslationY(0);
setWebViewTranslation(mToolbarLayout.getHeight());
}
supportInvalidateOptionsMenu();
initializeToolbarHeight(newConfig);
}
private void initializeToolbarHeight(@NonNull final Configuration configuration) {
// TODO externalize the dimensions
doOnLayout(mUiLayout, new Runnable() {
@Override
public void run() {
int toolbarSize;
if (configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
// In portrait toolbar should be 56 dp tall
toolbarSize = Utils.dpToPx(56);
} else {
// In landscape toolbar should be 48 dp tall
toolbarSize = Utils.dpToPx(52);
}
mToolbar.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, toolbarSize));
mToolbar.setMinimumHeight(toolbarSize);
doOnLayout(mToolbar, new Runnable() {
@Override
public void run() {
setWebViewTranslation(mToolbarLayout.getHeight());
}
});
mToolbar.requestLayout();
}
});
}
public void closeBrowser() {
mBrowserFrame.setBackgroundColor(mBackgroundColor);
removeViewFromParent(mCurrentView);
performExitCleanUp();
int size = mTabsManager.size();
mTabsManager.shutdown();
mCurrentView = null;
for (int n = 0; n < size; n++) {
mTabsView.tabRemoved(0);
}
finish();
}
@Override
public synchronized void onBackPressed() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (mDrawerLayout.isDrawerOpen(getTabDrawer())) {
mDrawerLayout.closeDrawer(getTabDrawer());
} else if (mDrawerLayout.isDrawerOpen(getBookmarkDrawer())) {
mBookmarksView.navigateBack();
} else {
if (currentTab != null) {
Log.d(TAG, "onBackPressed");
if (mSearch.hasFocus()) {
currentTab.requestFocus();
} else if (currentTab.canGoBack()) {
if (!currentTab.isShown()) {
onHideCustomView();
} else {
currentTab.goBack();
}
} else {
if (mCustomView != null || mCustomViewCallback != null) {
onHideCustomView();
} else {
mPresenter.deleteTab(mTabsManager.positionOf(currentTab));
}
}
} else {
Log.e(TAG, "This shouldn't happen ever");
super.onBackPressed();
}
}
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
mTabsManager.pauseAll();
try {
getApplication().unregisterReceiver(mNetworkReceiver);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Receiver was not registered", e);
}
if (isIncognito() && isFinishing()) {
overridePendingTransition(R.anim.fade_in_scale, R.anim.slide_down_out);
}
}
void saveOpenTabs() {
if (mPreferences.getRestoreLostTabsEnabled()) {
mTabsManager.saveState();
}
}
@Override
protected void onStop() {
super.onStop();
mProxyUtils.onStop();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy");
Handlers.MAIN.removeCallbacksAndMessages(null);
mPresenter.shutdown();
super.onDestroy();
}
@Override
protected void onStart() {
super.onStart();
mProxyUtils.onStart(this);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mTabsManager.shutdown();
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
if (mSwapBookmarksAndTabs != mPreferences.getBookmarksAndTabsSwapped()) {
restart();
}
if (mSuggestionsAdapter != null) {
mSuggestionsAdapter.refreshPreferences();
mSuggestionsAdapter.refreshBookmarks();
}
mTabsManager.resumeAll(this);
initializePreferences();
supportInvalidateOptionsMenu();
IntentFilter filter = new IntentFilter();
filter.addAction(NETWORK_BROADCAST_ACTION);
getApplication().registerReceiver(mNetworkReceiver, filter);
if (mFullScreen) {
overlayToolbarOnWebView();
} else {
putToolbarInRoot();
}
}
/**
* searches the web for the query fixing any and all problems with the input
* checks if it is a search, url, etc.
*/
private void searchTheWeb(@NonNull String query) {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (query.isEmpty()) {
return;
}
String searchUrl = mSearchText + UrlUtils.QUERY_PLACE_HOLDER;
query = query.trim();
if (currentTab != null) {
currentTab.stopLoading();
mPresenter.loadUrlInCurrentView(UrlUtils.smartUrlFilter(query, true, searchUrl));
}
}
/**
* Animates the color of the toolbar from one color to another. Optionally animates
* the color of the tab background, for use when the tabs are displayed on the top
* of the screen.
*
* @param favicon the Bitmap to extract the color from
* @param tabBackground the optional LinearLayout to color
*/
@Override
public void changeToolbarBackground(@NonNull Bitmap favicon, @Nullable final Drawable tabBackground) {
final int defaultColor = ContextCompat.getColor(this, R.color.primary_color);
if (mCurrentUiColor == Color.BLACK) {
mCurrentUiColor = defaultColor;
}
Palette.from(favicon).generate(new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
// OR with opaque black to remove transparency glitches
int color = 0xff000000 | palette.getVibrantColor(defaultColor);
final int finalColor; // Lighten up the dark color if it is
// too dark
if (!mShowTabsInDrawer || Utils.isColorTooDark(color)) {
finalColor = Utils.mixTwoColors(defaultColor, color, 0.25f);
} else {
finalColor = color;
}
final Window window = getWindow();
if (!mShowTabsInDrawer) {
window.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
}
final int startSearchColor = getSearchBarColor(mCurrentUiColor, defaultColor);
final int finalSearchColor = getSearchBarColor(finalColor, defaultColor);
Animation animation = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final int color = DrawableUtils.mixColor(interpolatedTime, mCurrentUiColor, finalColor);
if (mShowTabsInDrawer) {
mBackground.setColor(color);
Handlers.MAIN.post(new Runnable() {
@Override
public void run() {
window.setBackgroundDrawable(mBackground);
}
});
} else if (tabBackground != null) {
tabBackground.setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
mCurrentUiColor = color;
mToolbarLayout.setBackgroundColor(color);
mSearchBackground.getBackground().setColorFilter(DrawableUtils.mixColor(interpolatedTime,
startSearchColor, finalSearchColor), PorterDuff.Mode.SRC_IN);
}
};
animation.setDuration(300);
mToolbarLayout.startAnimation(animation);
}
});
}
private int getSearchBarColor(int requestedColor, int defaultColor) {
if (requestedColor == defaultColor) {
return mDarkTheme ? DrawableUtils.mixColor(0.25f, defaultColor, Color.WHITE) : Color.WHITE;
} else {
return DrawableUtils.mixColor(0.25f, requestedColor, Color.WHITE);
}
}
@Override
public boolean getUseDarkTheme() {
return mDarkTheme;
}
@ColorInt
@Override
public int getUiColor() {
return mCurrentUiColor;
}
@Override
public void updateUrl(@Nullable String url, boolean shortUrl) {
if (url == null || mSearch == null || mSearch.hasFocus()) {
return;
}
final LightningView currentTab = mTabsManager.getCurrentTab();
mBookmarksView.handleUpdatedUrl(url);
if (shortUrl && !UrlUtils.isSpecialUrl(url)) {
switch (mPreferences.getUrlBoxContentChoice()) {
case 0: // Default, show only the domain
url = url.replaceFirst(Constants.HTTP, "");
url = Utils.getDomainName(url);
mSearch.setText(url);
break;
case 1: // URL, show the entire URL
mSearch.setText(url);
break;
case 2: // Title, show the page's title
if (currentTab != null && !currentTab.getTitle().isEmpty()) {
mSearch.setText(currentTab.getTitle());
} else {
mSearch.setText(mUntitledTitle);
}
break;
}
} else {
if (UrlUtils.isSpecialUrl(url)) {
url = "";
}
mSearch.setText(url);
}
}
@Override
public void updateTabNumber(int number) {
if (mArrowImage != null && mShowTabsInDrawer) {
mArrowImage.setImageBitmap(DrawableUtils.getRoundedNumberImage(number, Utils.dpToPx(24),
Utils.dpToPx(24), ThemeUtils.getIconThemeColor(this, mDarkTheme), Utils.dpToPx(2.5f)));
}
}
@Override
public void updateProgress(int n) {
setIsLoading(n < 100);
mProgressBar.setProgress(n);
}
void addItemToHistory(@Nullable final String title, @NonNull final String url) {
if (UrlUtils.isSpecialUrl(url)) {
return;
}
HistoryModel.visitHistoryItem(url, title)
.subscribeOn(Schedulers.io())
.subscribe(new CompletableOnSubscribe() {
@Override
public void onError(@NonNull Throwable throwable) {
Log.e(TAG, "Exception while updating history", throwable);
}
});
}
/**
* method to generate search suggestions for the AutoCompleteTextView from
* previously searched URLs
*/
private void initializeSearchSuggestions(final AutoCompleteTextView getUrl) {
mSuggestionsAdapter = new SuggestionsAdapter(this, mDarkTheme, isIncognito());
getUrl.setThreshold(1);
getUrl.setDropDownWidth(-1);
getUrl.setDropDownAnchor(R.id.toolbar_layout);
getUrl.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
String url = null;
CharSequence urlString = ((TextView) view.findViewById(R.id.url)).getText();
if (urlString != null) {
url = urlString.toString();
}
if (url == null || url.startsWith(getString(R.string.suggestion))) {
CharSequence searchString = ((TextView) view.findViewById(R.id.title)).getText();
if (searchString != null) {
url = searchString.toString();
}
}
if (url == null) {
return;
}
getUrl.setText(url);
searchTheWeb(url);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getUrl.getWindowToken(), 0);
mPresenter.onAutoCompleteItemPressed();
}
});
getUrl.setSelectAllOnFocus(true);
getUrl.setAdapter(mSuggestionsAdapter);
}
/**
* function that opens the HTML history page in the browser
*/
private void openHistory() {
new HistoryPage().getHistoryPage()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.main())
.subscribe(new SingleOnSubscribe<String>() {
@Override
public void onItem(@Nullable String item) {
Preconditions.checkNonNull(item);
LightningView view = mTabsManager.getCurrentTab();
if (view != null) {
view.loadUrl(item);
}
}
});
}
private View getBookmarkDrawer() {
return mSwapBookmarksAndTabs ? mDrawerLeft : mDrawerRight;
}
private View getTabDrawer() {
return mSwapBookmarksAndTabs ? mDrawerRight : mDrawerLeft;
}
/**
* helper function that opens the bookmark drawer
*/
private void openBookmarks() {
if (mDrawerLayout.isDrawerOpen(getTabDrawer())) {
mDrawerLayout.closeDrawers();
}
mDrawerLayout.openDrawer(getBookmarkDrawer());
}
/**
* This method closes any open drawer and executes
* the runnable after the drawers are completely closed.
*
* @param runnable an optional runnable to run after
* the drawers are closed.
*/
void closeDrawers(@Nullable final Runnable runnable) {
if (!mDrawerLayout.isDrawerOpen(mDrawerLeft) && !mDrawerLayout.isDrawerOpen(mDrawerRight)) {
if (runnable != null) {
runnable.run();
return;
}
}
mDrawerLayout.closeDrawers();
mDrawerLayout.addDrawerListener(new DrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {}
@Override
public void onDrawerOpened(View drawerView) {}
@Override
public void onDrawerClosed(View drawerView) {
if (runnable != null) {
runnable.run();
}
mDrawerLayout.removeDrawerListener(this);
}
@Override
public void onDrawerStateChanged(int newState) {}
});
}
@Override
public void setForwardButtonEnabled(boolean enabled) {
if (mForwardMenuItem != null && mForwardMenuItem.getIcon() != null) {
int colorFilter;
if (enabled) {
colorFilter = mIconColor;
} else {
colorFilter = mDisabledIconColor;
}
mForwardMenuItem.getIcon().setColorFilter(colorFilter, PorterDuff.Mode.SRC_IN);
mForwardMenuItem.setIcon(mForwardMenuItem.getIcon());
}
}
@Override
public void setBackButtonEnabled(boolean enabled) {
if (mBackMenuItem != null && mBackMenuItem.getIcon() != null) {
int colorFilter;
if (enabled) {
colorFilter = mIconColor;
} else {
colorFilter = mDisabledIconColor;
}
mBackMenuItem.getIcon().setColorFilter(colorFilter, PorterDuff.Mode.SRC_IN);
mBackMenuItem.setIcon(mBackMenuItem.getIcon());
}
}
private MenuItem mBackMenuItem;
private MenuItem mForwardMenuItem;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
mBackMenuItem = menu.findItem(R.id.action_back);
mForwardMenuItem = menu.findItem(R.id.action_forward);
if (mBackMenuItem != null && mBackMenuItem.getIcon() != null)
mBackMenuItem.getIcon().setColorFilter(mIconColor, PorterDuff.Mode.SRC_IN);
if (mForwardMenuItem != null && mForwardMenuItem.getIcon() != null)
mForwardMenuItem.getIcon().setColorFilter(mIconColor, PorterDuff.Mode.SRC_IN);
return super.onCreateOptionsMenu(menu);
}
/**
* opens a file chooser
* param ValueCallback is the message from the WebView indicating a file chooser
* should be opened
*/
@Override
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i, getString(R.string.title_file_chooser)), 1);
}
/**
* used to allow uploading into the browser
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (API < Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == 1) {
if (null == mUploadMessage) {
return;
}
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
if (requestCode != 1 || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, intent);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (intent == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = intent.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
}
@Override
public void showFileChooser(ValueCallback<Uri[]> filePathCallback) {
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(this.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = Utils.createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, 1);
}
@Override
public synchronized void onShowCustomView(View view, CustomViewCallback callback) {
int requestedOrientation = mOriginalOrientation = getRequestedOrientation();
onShowCustomView(view, callback, requestedOrientation);
}
@Override
public synchronized void onShowCustomView(final View view, CustomViewCallback callback, int requestedOrientation) {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (view == null || mCustomView != null) {
if (callback != null) {
try {
callback.onCustomViewHidden();
} catch (Exception e) {
Log.e(TAG, "Error hiding custom view", e);
}
}
return;
}
try {
view.setKeepScreenOn(true);
} catch (SecurityException e) {
Log.e(TAG, "WebView is not allowed to keep the screen on");
}
mOriginalOrientation = getRequestedOrientation();
mCustomViewCallback = callback;
mCustomView = view;
setRequestedOrientation(requestedOrientation);
final FrameLayout decorView = (FrameLayout) getWindow().getDecorView();
mFullscreenContainer = new FrameLayout(this);
mFullscreenContainer.setBackgroundColor(ContextCompat.getColor(this, android.R.color.black));
if (view instanceof FrameLayout) {
if (((FrameLayout) view).getFocusedChild() instanceof VideoView) {
mVideoView = (VideoView) ((FrameLayout) view).getFocusedChild();
mVideoView.setOnErrorListener(new VideoCompletionListener());
mVideoView.setOnCompletionListener(new VideoCompletionListener());
}
} else if (view instanceof VideoView) {
mVideoView = (VideoView) view;
mVideoView.setOnErrorListener(new VideoCompletionListener());
mVideoView.setOnCompletionListener(new VideoCompletionListener());
}
decorView.addView(mFullscreenContainer, COVER_SCREEN_PARAMS);
mFullscreenContainer.addView(mCustomView, COVER_SCREEN_PARAMS);
decorView.requestLayout();
setFullscreen(true, true);
if (currentTab != null) {
currentTab.setVisibility(View.INVISIBLE);
}
}
@Override
public void closeBookmarksDrawer() {
mDrawerLayout.closeDrawer(getBookmarkDrawer());
}
@Override
public void onHideCustomView() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (mCustomView == null || mCustomViewCallback == null || currentTab == null) {
if (mCustomViewCallback != null) {
try {
mCustomViewCallback.onCustomViewHidden();
} catch (Exception e) {
Log.e(TAG, "Error hiding custom view", e);
}
mCustomViewCallback = null;
}
return;
}
Log.d(TAG, "onHideCustomView");
currentTab.setVisibility(View.VISIBLE);
try {
mCustomView.setKeepScreenOn(false);
} catch (SecurityException e) {
Log.e(TAG, "WebView is not allowed to keep the screen on");
}
setFullscreen(mPreferences.getHideStatusBarEnabled(), false);
if (mFullscreenContainer != null) {
ViewGroup parent = (ViewGroup) mFullscreenContainer.getParent();
if (parent != null) {
parent.removeView(mFullscreenContainer);
}
mFullscreenContainer.removeAllViews();
}
mFullscreenContainer = null;
mCustomView = null;
if (mVideoView != null) {
Log.d(TAG, "VideoView is being stopped");
mVideoView.stopPlayback();
mVideoView.setOnErrorListener(null);
mVideoView.setOnCompletionListener(null);
mVideoView = null;
}
if (mCustomViewCallback != null) {
try {
mCustomViewCallback.onCustomViewHidden();
} catch (Exception e) {
Log.e(TAG, "Error hiding custom view", e);
}
}
mCustomViewCallback = null;
setRequestedOrientation(mOriginalOrientation);
}
private class VideoCompletionListener implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
@Override
public void onCompletion(MediaPlayer mp) {
onHideCustomView();
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d(TAG, "onWindowFocusChanged");
if (hasFocus) {
setFullscreen(mIsFullScreen, mIsImmersive);
}
}
@Override
public void onBackButtonPressed() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (currentTab != null) {
if (currentTab.canGoBack()) {
currentTab.goBack();
} else {
mPresenter.deleteTab(mTabsManager.positionOf(currentTab));
}
}
}
@Override
public void onForwardButtonPressed() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (currentTab != null) {
if (currentTab.canGoForward()) {
currentTab.goForward();
}
}
}
@Override
public void onHomeButtonPressed() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (currentTab != null) {
currentTab.loadHomepage();
closeDrawers(null);
}
}
/**
* This method sets whether or not the activity will display
* in full-screen mode (i.e. the ActionBar will be hidden) and
* whether or not immersive mode should be set. This is used to
* set both parameters correctly as during a full-screen video,
* both need to be set, but other-wise we leave it up to user
* preference.
*
* @param enabled true to enable full-screen, false otherwise
* @param immersive true to enable immersive mode, false otherwise
*/
private void setFullscreen(boolean enabled, boolean immersive) {
mIsFullScreen = enabled;
mIsImmersive = immersive;
Window window = getWindow();
View decor = window.getDecorView();
if (enabled) {
if (immersive) {
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
} else {
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
/**
* This method handles the JavaScript callback to create a new tab.
* Basically this handles the event that JavaScript needs to create
* a popup.
*
* @param resultMsg the transport message used to send the URL to
* the newly created WebView.
*/
@Override
public synchronized void onCreateWindow(Message resultMsg) {
if (resultMsg == null) {
return;
}
if (newTab("", true)) {
LightningView newTab = mTabsManager.getTabAtPosition(mTabsManager.size() - 1);
if (newTab != null) {
final WebView webView = newTab.getWebView();
if (webView != null) {
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(webView);
resultMsg.sendToTarget();
}
}
}
}
/**
* Closes the specified {@link LightningView}. This implements
* the JavaScript callback that asks the tab to close itself and
* is especially helpful when a page creates a redirect and does
* not need the tab to stay open any longer.
*
* @param view the LightningView to close, delete it.
*/
@Override
public void onCloseWindow(LightningView view) {
mPresenter.deleteTab(mTabsManager.positionOf(view));
}
/**
* Hide the ActionBar using an animation if we are in full-screen
* mode. This method also re-parents the ActionBar if its parent is
* incorrect so that the animation can happen correctly.
*/
@Override
public void hideActionBar() {
if (mFullScreen) {
if (mToolbarLayout == null || mBrowserFrame == null)
return;
final int height = mToolbarLayout.getHeight();
if (mToolbarLayout.getTranslationY() > -0.01f) {
Animation show = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float trans = interpolatedTime * height;
mToolbarLayout.setTranslationY(-trans);
setWebViewTranslation(height - trans);
}
};
show.setDuration(250);
show.setInterpolator(new BezierDecelerateInterpolator());
mBrowserFrame.startAnimation(show);
}
}
}
/**
* Display the ActionBar using an animation if we are in full-screen
* mode. This method also re-parents the ActionBar if its parent is
* incorrect so that the animation can happen correctly.
*/
@Override
public void showActionBar() {
if (mFullScreen) {
Log.d(TAG, "showActionBar");
if (mToolbarLayout == null)
return;
int height = mToolbarLayout.getHeight();
if (height == 0) {
mToolbarLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
height = mToolbarLayout.getMeasuredHeight();
}
final int totalHeight = height;
if (mToolbarLayout.getTranslationY() < -(height - 0.01f)) {
Animation show = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float trans = interpolatedTime * totalHeight;
mToolbarLayout.setTranslationY(trans - totalHeight);
setWebViewTranslation(trans);
}
};
show.setDuration(250);
show.setInterpolator(new BezierDecelerateInterpolator());
mBrowserFrame.startAnimation(show);
}
}
}
@Override
public void handleBookmarksChange() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (currentTab != null && currentTab.getUrl().startsWith(Constants.FILE)
&& currentTab.getUrl().endsWith(BookmarkPage.FILENAME)) {
currentTab.loadBookmarkpage();
}
if (currentTab != null) {
mBookmarksView.handleUpdatedUrl(currentTab.getUrl());
}
}
@Override
public void handleBookmarkDeleted(@NonNull HistoryItem item) {
mBookmarksView.handleBookmarkDeleted(item);
handleBookmarksChange();
}
@Override
public void handleNewTab(@NonNull LightningDialogBuilder.NewTab newTabType, @NonNull String url) {
mDrawerLayout.closeDrawers();
switch (newTabType) {
case FOREGROUND:
newTab(url, true);
break;
case BACKGROUND:
newTab(url, false);
break;
case INCOGNITO:
Intent intent = new Intent(BrowserActivity.this, IncognitoActivity.class);
intent.setData(Uri.parse(url));
startActivity(intent);
overridePendingTransition(R.anim.slide_up_in, R.anim.fade_out_scale);
break;
}
}
/**
* Performs an action when the provided view is laid out.
*
* @param view the view to listen to for layouts.
* @param runnable the runnable to run when the view is
* laid out.
*/
private static void doOnLayout(@NonNull final View view, @NonNull final Runnable runnable) {
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
//noinspection deprecation
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
runnable.run();
}
});
}
/**
* This method lets the search bar know that the page is currently loading
* and that it should display the stop icon to indicate to the user that
* pressing it stops the page from loading
*/
private void setIsLoading(boolean isLoading) {
if (!mSearch.hasFocus()) {
mIcon = isLoading ? mDeleteIcon : mRefreshIcon;
mSearch.setCompoundDrawables(null, null, mIcon, null);
}
}
/**
* handle presses on the refresh icon in the search bar, if the page is
* loading, stop the page, if it is done loading refresh the page.
* See setIsFinishedLoading and setIsLoading for displaying the correct icon
*/
private void refreshOrStop() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (currentTab != null) {
if (currentTab.getProgress() < 100) {
currentTab.stopLoading();
} else {
currentTab.reload();
}
}
}
/**
* Handle the click event for the views that are using
* this class as a click listener. This method should
* distinguish between the various views using their IDs.
*
* @param v the view that the user has clicked
*/
@Override
public void onClick(View v) {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (currentTab == null) {
return;
}
switch (v.getId()) {
case R.id.arrow_button:
if (mSearch != null && mSearch.hasFocus()) {
currentTab.requestFocus();
} else if (mShowTabsInDrawer) {
mDrawerLayout.openDrawer(getTabDrawer());
} else {
currentTab.loadHomepage();
}
break;
case R.id.button_next:
currentTab.findNext();
break;
case R.id.button_back:
currentTab.findPrevious();
break;
case R.id.button_quit:
currentTab.clearFindMatches();
mSearchBar.setVisibility(View.GONE);
break;
case R.id.action_reading:
Intent read = new Intent(this, ReadingActivity.class);
read.putExtra(Constants.LOAD_READING_URL, currentTab.getUrl());
startActivity(read);
break;
case R.id.action_toggle_desktop:
currentTab.toggleDesktopUA(this);
currentTab.reload();
closeDrawers(null);
break;
}
}
/**
* This NetworkReceiver notifies each of the WebViews in the browser whether
* the network is currently connected or not. This is important because some
* JavaScript properties rely on the WebView knowing the current network state.
* It is used to help the browser be compliant with the HTML5 spec, sec. 5.7.7
*/
private final NetworkReceiver mNetworkReceiver = new NetworkReceiver() {
@Override
public void onConnectivityChange(boolean isConnected) {
Log.d(TAG, "Network Connected: " + isConnected);
mTabsManager.notifyConnectionStatus(isConnected);
}
};
/**
* Handle the callback that permissions requested have been granted or not.
* This method should act upon the results of the permissions request.
*
* @param requestCode the request code sent when initially making the request
* @param permissions the array of the permissions that was requested
* @param grantResults the results of the permissions requests that provides
* information on whether the request was granted or not
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
| app/src/main/java/acr/browser/lightning/activity/BrowserActivity.java | /*
* Copyright 2015 Anthony Restaino
*/
package acr.browser.lightning.activity;
import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.ColorInt;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebIconDatabase;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.VideoView;
import com.anthonycr.bonsai.Completable;
import com.anthonycr.bonsai.CompletableOnSubscribe;
import com.anthonycr.bonsai.Schedulers;
import com.anthonycr.bonsai.SingleOnSubscribe;
import com.anthonycr.grant.PermissionsManager;
import com.anthonycr.progress.AnimatedProgressBar;
import java.io.File;
import java.io.IOException;
import javax.inject.Inject;
import acr.browser.lightning.R;
import acr.browser.lightning.app.BrowserApp;
import acr.browser.lightning.browser.BookmarksView;
import acr.browser.lightning.browser.BrowserPresenter;
import acr.browser.lightning.browser.BrowserView;
import acr.browser.lightning.browser.TabsView;
import acr.browser.lightning.constant.BookmarkPage;
import acr.browser.lightning.constant.Constants;
import acr.browser.lightning.constant.HistoryPage;
import acr.browser.lightning.controller.UIController;
import acr.browser.lightning.database.HistoryItem;
import acr.browser.lightning.database.bookmark.BookmarkModel;
import acr.browser.lightning.database.history.HistoryModel;
import acr.browser.lightning.dialog.BrowserDialog;
import acr.browser.lightning.dialog.LightningDialogBuilder;
import acr.browser.lightning.fragment.BookmarksFragment;
import acr.browser.lightning.fragment.TabsFragment;
import acr.browser.lightning.interpolator.BezierDecelerateInterpolator;
import acr.browser.lightning.receiver.NetworkReceiver;
import acr.browser.lightning.search.SuggestionsAdapter;
import acr.browser.lightning.utils.DrawableUtils;
import acr.browser.lightning.utils.Preconditions;
import acr.browser.lightning.utils.ProxyUtils;
import acr.browser.lightning.utils.ThemeUtils;
import acr.browser.lightning.utils.UrlUtils;
import acr.browser.lightning.utils.Utils;
import acr.browser.lightning.utils.WebUtils;
import acr.browser.lightning.view.Handlers;
import acr.browser.lightning.view.LightningView;
import acr.browser.lightning.view.SearchView;
import butterknife.BindView;
import butterknife.ButterKnife;
public abstract class BrowserActivity extends ThemableBrowserActivity implements BrowserView, UIController, OnClickListener {
private static final String TAG = "BrowserActivity";
private static final String INTENT_PANIC_TRIGGER = "info.guardianproject.panic.action.TRIGGER";
private static final String TAG_BOOKMARK_FRAGMENT = "TAG_BOOKMARK_FRAGMENT";
private static final String TAG_TABS_FRAGMENT = "TAG_TABS_FRAGMENT";
// Static Layout
@BindView(R.id.drawer_layout) DrawerLayout mDrawerLayout;
@BindView(R.id.content_frame) FrameLayout mBrowserFrame;
@BindView(R.id.left_drawer) ViewGroup mDrawerLeft;
@BindView(R.id.right_drawer) ViewGroup mDrawerRight;
@BindView(R.id.ui_layout) ViewGroup mUiLayout;
@BindView(R.id.toolbar_layout) ViewGroup mToolbarLayout;
@BindView(R.id.progress_view) AnimatedProgressBar mProgressBar;
@BindView(R.id.search_bar) RelativeLayout mSearchBar;
// Toolbar Views
@BindView(R.id.toolbar) Toolbar mToolbar;
private View mSearchBackground;
private SearchView mSearch;
private ImageView mArrowImage;
// Current tab view being displayed
@Nullable private View mCurrentView;
// Full Screen Video Views
private FrameLayout mFullscreenContainer;
private VideoView mVideoView;
private View mCustomView;
// Adapter
private SuggestionsAdapter mSuggestionsAdapter;
// Callback
private CustomViewCallback mCustomViewCallback;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> mFilePathCallback;
// Primitives
private boolean mFullScreen;
private boolean mDarkTheme;
private boolean mIsFullScreen = false;
private boolean mIsImmersive = false;
private boolean mShowTabsInDrawer;
private boolean mSwapBookmarksAndTabs;
private int mOriginalOrientation;
private int mBackgroundColor;
private int mIconColor;
private int mDisabledIconColor;
private int mCurrentUiColor = Color.BLACK;
private long mKeyDownStartTime;
private String mSearchText;
private String mUntitledTitle;
private String mCameraPhotoPath;
// The singleton BookmarkManager
@Inject BookmarkModel mBookmarkManager;
@Inject LightningDialogBuilder mBookmarksDialogBuilder;
private TabsManager mTabsManager;
// Image
private Bitmap mWebpageBitmap;
private final ColorDrawable mBackground = new ColorDrawable();
private Drawable mDeleteIcon, mRefreshIcon, mClearIcon, mIcon;
private BrowserPresenter mPresenter;
private TabsView mTabsView;
private BookmarksView mBookmarksView;
// Proxy
@Inject ProxyUtils mProxyUtils;
// Constant
private static final int API = android.os.Build.VERSION.SDK_INT;
private static final String NETWORK_BROADCAST_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
private static final LayoutParams MATCH_PARENT = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
private static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
protected abstract boolean isIncognito();
public abstract void closeActivity();
public abstract void updateHistory(@Nullable final String title, @NonNull final String url);
@NonNull
abstract Completable updateCookiePreference();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BrowserApp.getAppComponent().inject(this);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mTabsManager = new TabsManager();
mPresenter = new BrowserPresenter(this, isIncognito());
initialize(savedInstanceState);
}
private synchronized void initialize(Bundle savedInstanceState) {
initializeToolbarHeight(getResources().getConfiguration());
setSupportActionBar(mToolbar);
ActionBar actionBar = getSupportActionBar();
//TODO make sure dark theme flag gets set correctly
mDarkTheme = mPreferences.getUseTheme() != 0 || isIncognito();
mIconColor = mDarkTheme ? ThemeUtils.getIconDarkThemeColor(this) : ThemeUtils.getIconLightThemeColor(this);
mDisabledIconColor = mDarkTheme ? ContextCompat.getColor(this, R.color.icon_dark_theme_disabled) :
ContextCompat.getColor(this, R.color.icon_light_theme_disabled);
mShowTabsInDrawer = mPreferences.getShowTabsInDrawer(!isTablet());
mSwapBookmarksAndTabs = mPreferences.getBookmarksAndTabsSwapped();
// initialize background ColorDrawable
int primaryColor = ThemeUtils.getPrimaryColor(this);
mBackground.setColor(primaryColor);
// Drawer stutters otherwise
mDrawerLeft.setLayerType(View.LAYER_TYPE_NONE, null);
mDrawerRight.setLayerType(View.LAYER_TYPE_NONE, null);
mDrawerLayout.addDrawerListener(new DrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {}
@Override
public void onDrawerOpened(View drawerView) {}
@Override
public void onDrawerClosed(View drawerView) {}
@Override
public void onDrawerStateChanged(int newState) {
if (newState == DrawerLayout.STATE_DRAGGING) {
mDrawerLeft.setLayerType(View.LAYER_TYPE_HARDWARE, null);
mDrawerRight.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (newState == DrawerLayout.STATE_IDLE) {
mDrawerLeft.setLayerType(View.LAYER_TYPE_NONE, null);
mDrawerRight.setLayerType(View.LAYER_TYPE_NONE, null);
}
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !mShowTabsInDrawer) {
getWindow().setStatusBarColor(Color.BLACK);
}
setNavigationDrawerWidth();
mDrawerLayout.addDrawerListener(new DrawerLocker());
mWebpageBitmap = ThemeUtils.getThemedBitmap(this, R.drawable.ic_webpage, mDarkTheme);
final FragmentManager fragmentManager = getSupportFragmentManager();
TabsFragment tabsFragment = (TabsFragment) fragmentManager.findFragmentByTag(TAG_TABS_FRAGMENT);
BookmarksFragment bookmarksFragment = (BookmarksFragment) fragmentManager.findFragmentByTag(TAG_BOOKMARK_FRAGMENT);
if (tabsFragment != null) {
fragmentManager.beginTransaction().remove(tabsFragment).commit();
}
tabsFragment = TabsFragment.createTabsFragment(isIncognito(), mShowTabsInDrawer);
mTabsView = tabsFragment;
if (bookmarksFragment != null) {
fragmentManager.beginTransaction().remove(bookmarksFragment).commit();
}
bookmarksFragment = BookmarksFragment.createFragment(isIncognito());
mBookmarksView = bookmarksFragment;
fragmentManager.executePendingTransactions();
fragmentManager
.beginTransaction()
.replace(getTabsFragmentViewId(), tabsFragment, TAG_TABS_FRAGMENT)
.replace(getBookmarksFragmentViewId(), bookmarksFragment, TAG_BOOKMARK_FRAGMENT)
.commit();
if (mShowTabsInDrawer) {
mToolbarLayout.removeView(findViewById(R.id.tabs_toolbar_container));
}
Preconditions.checkNonNull(actionBar);
// set display options of the ActionBar
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(R.layout.toolbar_content);
View customView = actionBar.getCustomView();
LayoutParams lp = customView.getLayoutParams();
lp.width = LayoutParams.MATCH_PARENT;
lp.height = LayoutParams.MATCH_PARENT;
customView.setLayoutParams(lp);
mArrowImage = (ImageView) customView.findViewById(R.id.arrow);
FrameLayout arrowButton = (FrameLayout) customView.findViewById(R.id.arrow_button);
if (mShowTabsInDrawer) {
if (mArrowImage.getWidth() <= 0) {
mArrowImage.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
}
updateTabNumber(0);
// Post drawer locking in case the activity is being recreated
Handlers.MAIN.post(new Runnable() {
@Override
public void run() {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, getTabDrawer());
}
});
} else {
// Post drawer locking in case the activity is being recreated
Handlers.MAIN.post(new Runnable() {
@Override
public void run() {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, getTabDrawer());
}
});
mArrowImage.setImageResource(R.drawable.ic_action_home);
mArrowImage.setColorFilter(mIconColor, PorterDuff.Mode.SRC_IN);
}
// Post drawer locking in case the activity is being recreated
Handlers.MAIN.post(new Runnable() {
@Override
public void run() {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, getBookmarkDrawer());
}
});
arrowButton.setOnClickListener(this);
// create the search EditText in the ToolBar
mSearch = (SearchView) customView.findViewById(R.id.search);
mSearchBackground = customView.findViewById(R.id.search_container);
// initialize search background color
mSearchBackground.getBackground().setColorFilter(getSearchBarColor(primaryColor, primaryColor), PorterDuff.Mode.SRC_IN);
mSearch.setHintTextColor(ThemeUtils.getThemedTextHintColor(mDarkTheme));
mSearch.setTextColor(mDarkTheme ? Color.WHITE : Color.BLACK);
mUntitledTitle = getString(R.string.untitled);
mBackgroundColor = ThemeUtils.getPrimaryColor(this);
mDeleteIcon = ThemeUtils.getThemedDrawable(this, R.drawable.ic_action_delete, mDarkTheme);
mRefreshIcon = ThemeUtils.getThemedDrawable(this, R.drawable.ic_action_refresh, mDarkTheme);
mClearIcon = ThemeUtils.getThemedDrawable(this, R.drawable.ic_action_delete, mDarkTheme);
int iconBounds = Utils.dpToPx(24);
mDeleteIcon.setBounds(0, 0, iconBounds, iconBounds);
mRefreshIcon.setBounds(0, 0, iconBounds, iconBounds);
mClearIcon.setBounds(0, 0, iconBounds, iconBounds);
mIcon = mRefreshIcon;
SearchListenerClass search = new SearchListenerClass();
mSearch.setCompoundDrawablePadding(Utils.dpToPx(3));
mSearch.setCompoundDrawables(null, null, mRefreshIcon, null);
mSearch.setOnKeyListener(search);
mSearch.setOnFocusChangeListener(search);
mSearch.setOnEditorActionListener(search);
mSearch.setOnTouchListener(search);
mSearch.setOnPreFocusListener(search);
initializeSearchSuggestions(mSearch);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_right_shadow, GravityCompat.END);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_left_shadow, GravityCompat.START);
if (API <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
//noinspection deprecation
WebIconDatabase.getInstance().open(getDir("icons", MODE_PRIVATE).getPath());
}
@SuppressWarnings("VariableNotUsedInsideIf")
Intent intent = savedInstanceState == null ? getIntent() : null;
boolean launchedFromHistory = intent != null && (intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0;
if (isPanicTrigger(intent)) {
setIntent(null);
panicClean();
} else {
if (launchedFromHistory) {
intent = null;
}
mPresenter.setupTabs(intent);
setIntent(null);
mProxyUtils.checkForProxy(this);
}
}
@IdRes
private int getBookmarksFragmentViewId() {
return mSwapBookmarksAndTabs ? R.id.left_drawer : R.id.right_drawer;
}
private int getTabsFragmentViewId() {
if (mShowTabsInDrawer) {
return mSwapBookmarksAndTabs ? R.id.right_drawer : R.id.left_drawer;
} else {
return R.id.tabs_toolbar_container;
}
}
/**
* Determines if an intent is originating
* from a panic trigger.
*
* @param intent the intent to check.
* @return true if the panic trigger sent
* the intent, false otherwise.
*/
static boolean isPanicTrigger(@Nullable Intent intent) {
return intent != null && INTENT_PANIC_TRIGGER.equals(intent.getAction());
}
void panicClean() {
Log.d(TAG, "Closing browser");
mTabsManager.newTab(this, "", false);
mTabsManager.switchToTab(0);
mTabsManager.clearSavedState();
HistoryPage.deleteHistoryPage(getApplication()).subscribe();
closeBrowser();
// System exit needed in the case of receiving
// the panic intent since finish() isn't completely
// closing the browser
System.exit(1);
}
private class SearchListenerClass implements OnKeyListener, OnEditorActionListener,
OnFocusChangeListener, OnTouchListener, SearchView.PreFocusListener {
@Override
public boolean onKey(View searchView, int keyCode, KeyEvent keyEvent) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mSearch.getWindowToken(), 0);
searchTheWeb(mSearch.getText().toString());
final LightningView currentView = mTabsManager.getCurrentTab();
if (currentView != null) {
currentView.requestFocus();
}
return true;
default:
break;
}
return false;
}
@Override
public boolean onEditorAction(TextView arg0, int actionId, KeyEvent arg2) {
// hide the keyboard and search the web when the enter key
// button is pressed
if (actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_DONE
|| actionId == EditorInfo.IME_ACTION_NEXT
|| actionId == EditorInfo.IME_ACTION_SEND
|| actionId == EditorInfo.IME_ACTION_SEARCH
|| (arg2.getAction() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mSearch.getWindowToken(), 0);
searchTheWeb(mSearch.getText().toString());
final LightningView currentView = mTabsManager.getCurrentTab();
if (currentView != null) {
currentView.requestFocus();
}
return true;
}
return false;
}
@Override
public void onFocusChange(final View v, final boolean hasFocus) {
final LightningView currentView = mTabsManager.getCurrentTab();
if (!hasFocus && currentView != null) {
setIsLoading(currentView.getProgress() < 100);
updateUrl(currentView.getUrl(), true);
} else if (hasFocus && currentView != null) {
// Hack to make sure the text gets selected
((SearchView) v).selectAll();
mIcon = mClearIcon;
mSearch.setCompoundDrawables(null, null, mClearIcon, null);
}
if (!hasFocus) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mSearch.getWindowToken(), 0);
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mSearch.getCompoundDrawables()[2] != null) {
boolean tappedX = event.getX() > (mSearch.getWidth()
- mSearch.getPaddingRight() - mIcon.getIntrinsicWidth());
if (tappedX) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mSearch.hasFocus()) {
mSearch.setText("");
} else {
refreshOrStop();
}
}
return true;
}
}
return false;
}
@Override
public void onPreFocus() {
final LightningView currentView = mTabsManager.getCurrentTab();
if (currentView == null) {
return;
}
String url = currentView.getUrl();
if (!UrlUtils.isSpecialUrl(url)) {
if (!mSearch.hasFocus()) {
mSearch.setText(url);
}
}
}
}
private class DrawerLocker implements DrawerListener {
@Override
public void onDrawerClosed(View v) {
View tabsDrawer = getTabDrawer();
View bookmarksDrawer = getBookmarkDrawer();
if (v == tabsDrawer) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, bookmarksDrawer);
} else if (mShowTabsInDrawer) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, tabsDrawer);
}
}
@Override
public void onDrawerOpened(View v) {
View tabsDrawer = getTabDrawer();
View bookmarksDrawer = getBookmarkDrawer();
if (v == tabsDrawer) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, bookmarksDrawer);
} else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, tabsDrawer);
}
}
@Override
public void onDrawerSlide(View v, float arg) {}
@Override
public void onDrawerStateChanged(int arg) {}
}
private void setNavigationDrawerWidth() {
int width = getResources().getDisplayMetrics().widthPixels - Utils.dpToPx(56);
int maxWidth;
if (isTablet()) {
maxWidth = Utils.dpToPx(320);
} else {
maxWidth = Utils.dpToPx(300);
}
if (width > maxWidth) {
DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerLeft
.getLayoutParams();
params.width = maxWidth;
mDrawerLeft.setLayoutParams(params);
mDrawerLeft.requestLayout();
DrawerLayout.LayoutParams paramsRight = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerRight
.getLayoutParams();
paramsRight.width = maxWidth;
mDrawerRight.setLayoutParams(paramsRight);
mDrawerRight.requestLayout();
} else {
DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerLeft
.getLayoutParams();
params.width = width;
mDrawerLeft.setLayoutParams(params);
mDrawerLeft.requestLayout();
DrawerLayout.LayoutParams paramsRight = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerRight
.getLayoutParams();
paramsRight.width = width;
mDrawerRight.setLayoutParams(paramsRight);
mDrawerRight.requestLayout();
}
}
private void initializePreferences() {
final LightningView currentView = mTabsManager.getCurrentTab();
mFullScreen = mPreferences.getFullScreenEnabled();
boolean colorMode = mPreferences.getColorModeEnabled();
colorMode &= !mDarkTheme;
if (!isIncognito() && !colorMode && !mDarkTheme && mWebpageBitmap != null) {
changeToolbarBackground(mWebpageBitmap, null);
} else if (!isIncognito() && currentView != null && !mDarkTheme) {
changeToolbarBackground(currentView.getFavicon(), null);
} else if (!isIncognito() && !mDarkTheme && mWebpageBitmap != null) {
changeToolbarBackground(mWebpageBitmap, null);
}
FragmentManager manager = getSupportFragmentManager();
Fragment tabsFragment = manager.findFragmentByTag(TAG_TABS_FRAGMENT);
if (tabsFragment instanceof TabsFragment) {
((TabsFragment) tabsFragment).reinitializePreferences();
}
Fragment bookmarksFragment = manager.findFragmentByTag(TAG_BOOKMARK_FRAGMENT);
if (bookmarksFragment instanceof BookmarksFragment) {
((BookmarksFragment) bookmarksFragment).reinitializePreferences();
}
// TODO layout transition causing memory leak
// mBrowserFrame.setLayoutTransition(new LayoutTransition());
setFullscreen(mPreferences.getHideStatusBarEnabled(), false);
switch (mPreferences.getSearchChoice()) {
case 0:
mSearchText = mPreferences.getSearchUrl();
if (!mSearchText.startsWith(Constants.HTTP)
&& !mSearchText.startsWith(Constants.HTTPS)) {
mSearchText = Constants.GOOGLE_SEARCH;
}
break;
case 1:
mSearchText = Constants.GOOGLE_SEARCH;
break;
case 2:
mSearchText = Constants.ASK_SEARCH;
break;
case 3:
mSearchText = Constants.BING_SEARCH;
break;
case 4:
mSearchText = Constants.YAHOO_SEARCH;
break;
case 5:
mSearchText = Constants.STARTPAGE_SEARCH;
break;
case 6:
mSearchText = Constants.STARTPAGE_MOBILE_SEARCH;
break;
case 7:
mSearchText = Constants.DUCK_SEARCH;
break;
case 8:
mSearchText = Constants.DUCK_LITE_SEARCH;
break;
case 9:
mSearchText = Constants.BAIDU_SEARCH;
break;
case 10:
mSearchText = Constants.YANDEX_SEARCH;
break;
}
updateCookiePreference().subscribeOn(Schedulers.worker()).subscribe();
mProxyUtils.updateProxySettings(this);
}
@Override
public void onWindowVisibleToUserAfterResume() {
super.onWindowVisibleToUserAfterResume();
mToolbarLayout.setTranslationY(0);
setWebViewTranslation(mToolbarLayout.getHeight());
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (mSearch.hasFocus()) {
searchTheWeb(mSearch.getText().toString());
}
} else if ((keyCode == KeyEvent.KEYCODE_MENU)
&& (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN)
&& (Build.MANUFACTURER.compareTo("LGE") == 0)) {
// Workaround for stupid LG devices that crash
return true;
} else if (keyCode == KeyEvent.KEYCODE_BACK) {
mKeyDownStartTime = System.currentTimeMillis();
Handlers.MAIN.postDelayed(mLongPressBackRunnable, ViewConfiguration.getLongPressTimeout());
}
return super.onKeyDown(keyCode, event);
}
private final Runnable mLongPressBackRunnable = new Runnable() {
@Override
public void run() {
final LightningView currentTab = mTabsManager.getCurrentTab();
showCloseDialog(mTabsManager.positionOf(currentTab));
}
};
@Override
public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_MENU)
&& (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN)
&& (Build.MANUFACTURER.compareTo("LGE") == 0)) {
// Workaround for stupid LG devices that crash
openOptionsMenu();
return true;
} else if (keyCode == KeyEvent.KEYCODE_BACK) {
Handlers.MAIN.removeCallbacks(mLongPressBackRunnable);
if ((System.currentTimeMillis() - mKeyDownStartTime) > ViewConfiguration.getLongPressTimeout()) {
return true;
}
}
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final LightningView currentView = mTabsManager.getCurrentTab();
final String currentUrl = currentView != null ? currentView.getUrl() : null;
// Handle action buttons
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(getBookmarkDrawer())) {
mDrawerLayout.closeDrawer(getBookmarkDrawer());
}
return true;
case R.id.action_back:
if (currentView != null && currentView.canGoBack()) {
currentView.goBack();
}
return true;
case R.id.action_forward:
if (currentView != null && currentView.canGoForward()) {
currentView.goForward();
}
return true;
case R.id.action_add_to_homescreen:
if (currentView != null) {
HistoryItem shortcut = new HistoryItem(currentView.getUrl(), currentView.getTitle());
shortcut.setBitmap(currentView.getFavicon());
Utils.createShortcut(this, shortcut);
}
return true;
case R.id.action_new_tab:
newTab(null, true);
return true;
case R.id.action_incognito:
startActivity(new Intent(this, IncognitoActivity.class));
overridePendingTransition(R.anim.slide_up_in, R.anim.fade_out_scale);
return true;
case R.id.action_share:
if (currentUrl != null && !UrlUtils.isSpecialUrl(currentUrl)) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, currentView.getTitle());
shareIntent.putExtra(Intent.EXTRA_TEXT, currentUrl);
startActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.dialog_title_share)));
}
return true;
case R.id.action_bookmarks:
openBookmarks();
return true;
case R.id.action_copy:
if (currentUrl != null && !UrlUtils.isSpecialUrl(currentUrl)) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", currentUrl);
clipboard.setPrimaryClip(clip);
Utils.showSnackbar(this, R.string.message_link_copied);
}
return true;
case R.id.action_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.action_history:
openHistory();
return true;
case R.id.action_add_bookmark:
if (currentUrl != null && !UrlUtils.isSpecialUrl(currentUrl)) {
addBookmark(currentView.getTitle(), currentUrl);
}
return true;
case R.id.action_find:
findInPage();
return true;
case R.id.action_reading_mode:
if (currentUrl != null) {
Intent read = new Intent(this, ReadingActivity.class);
read.putExtra(Constants.LOAD_READING_URL, currentUrl);
startActivity(read);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// By using a manager, adds a bookmark and notifies third parties about that
private void addBookmark(final String title, final String url) {
final HistoryItem item = new HistoryItem(url, title);
mBookmarkManager.addBookmarkIfNotExists(item)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.main())
.subscribe(new SingleOnSubscribe<Boolean>() {
@Override
public void onItem(@Nullable Boolean item) {
if (Boolean.TRUE.equals(item)) {
mSuggestionsAdapter.refreshBookmarks();
mBookmarksView.handleUpdatedUrl(url);
}
}
});
}
private void deleteBookmark(final String title, final String url) {
final HistoryItem item = new HistoryItem(url, title);
mBookmarkManager.deleteBookmark(item)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.main())
.subscribe(new SingleOnSubscribe<Boolean>() {
@Override
public void onItem(@Nullable Boolean item) {
if (Boolean.TRUE.equals(item)) {
mSuggestionsAdapter.refreshBookmarks();
mBookmarksView.handleUpdatedUrl(url);
}
}
});
}
private void putToolbarInRoot() {
if (mToolbarLayout.getParent() != mUiLayout) {
if (mToolbarLayout.getParent() != null) {
((ViewGroup) mToolbarLayout.getParent()).removeView(mToolbarLayout);
}
mUiLayout.addView(mToolbarLayout, 0);
mUiLayout.requestLayout();
}
setWebViewTranslation(0);
}
private void overlayToolbarOnWebView() {
if (mToolbarLayout.getParent() != mBrowserFrame) {
if (mToolbarLayout.getParent() != null) {
((ViewGroup) mToolbarLayout.getParent()).removeView(mToolbarLayout);
}
mBrowserFrame.addView(mToolbarLayout);
mBrowserFrame.requestLayout();
}
setWebViewTranslation(mToolbarLayout.getHeight());
}
private void setWebViewTranslation(float translation) {
if (mFullScreen && mCurrentView != null) {
mCurrentView.setTranslationY(translation);
} else if (mCurrentView != null) {
mCurrentView.setTranslationY(0);
}
}
/**
* method that shows a dialog asking what string the user wishes to search
* for. It highlights the text entered.
*/
private void findInPage() {
BrowserDialog.showEditText(this,
R.string.action_find,
R.string.search_hint,
R.string.search_hint, new BrowserDialog.EditorListener() {
@Override
public void onClick(String text) {
if (!TextUtils.isEmpty(text)) {
mPresenter.findInPage(text);
showFindInPageControls(text);
}
}
});
}
private void showFindInPageControls(@NonNull String text) {
mSearchBar.setVisibility(View.VISIBLE);
TextView tw = (TextView) findViewById(R.id.search_query);
tw.setText('\'' + text + '\'');
ImageButton up = (ImageButton) findViewById(R.id.button_next);
up.setOnClickListener(this);
ImageButton down = (ImageButton) findViewById(R.id.button_back);
down.setOnClickListener(this);
ImageButton quit = (ImageButton) findViewById(R.id.button_quit);
quit.setOnClickListener(this);
}
@Override
public TabsManager getTabModel() {
return mTabsManager;
}
@Override
public void showCloseDialog(final int position) {
if (position < 0) {
return;
}
BrowserDialog.show(this, R.string.dialog_title_close_browser,
new BrowserDialog.Item(R.string.close_tab) {
@Override
public void onClick() {
mPresenter.deleteTab(position);
}
},
new BrowserDialog.Item(R.string.close_other_tabs) {
@Override
public void onClick() {
mPresenter.closeAllOtherTabs();
}
},
new BrowserDialog.Item(R.string.close_all_tabs) {
@Override
public void onClick() {
closeBrowser();
}
});
}
@Override
public void notifyTabViewRemoved(int position) {
Log.d(TAG, "Notify Tab Removed: " + position);
mTabsView.tabRemoved(position);
}
@Override
public void notifyTabViewAdded() {
Log.d(TAG, "Notify Tab Added");
mTabsView.tabAdded();
}
@Override
public void notifyTabViewChanged(int position) {
Log.d(TAG, "Notify Tab Changed: " + position);
mTabsView.tabChanged(position);
}
@Override
public void notifyTabViewInitialized() {
Log.d(TAG, "Notify Tabs Initialized");
mTabsView.tabsInitialized();
}
@Override
public void tabChanged(LightningView tab) {
mPresenter.tabChangeOccurred(tab);
}
@Override
public void removeTabView() {
Log.d(TAG, "Remove the tab view");
// Set the background color so the color mode color doesn't show through
mBrowserFrame.setBackgroundColor(mBackgroundColor);
removeViewFromParent(mCurrentView);
mCurrentView = null;
// Use a delayed handler to make the transition smooth
// otherwise it will get caught up with the showTab code
// and cause a janky motion
Handlers.MAIN.postDelayed(new Runnable() {
@Override
public void run() {
mDrawerLayout.closeDrawers();
}
}, 200);
}
@Override
public void setTabView(@NonNull final View view) {
if (mCurrentView == view) {
return;
}
Log.d(TAG, "Setting the tab view");
// Set the background color so the color mode color doesn't show through
mBrowserFrame.setBackgroundColor(mBackgroundColor);
removeViewFromParent(view);
removeViewFromParent(mCurrentView);
mBrowserFrame.addView(view, 0, MATCH_PARENT);
if (mFullScreen) {
view.setTranslationY(mToolbarLayout.getHeight() + mToolbarLayout.getTranslationY());
} else {
view.setTranslationY(0);
}
view.requestFocus();
mCurrentView = view;
showActionBar();
// Use a delayed handler to make the transition smooth
// otherwise it will get caught up with the showTab code
// and cause a janky motion
Handlers.MAIN.postDelayed(new Runnable() {
@Override
public void run() {
mDrawerLayout.closeDrawers();
}
}, 200);
// Handlers.MAIN.postDelayed(new Runnable() {
// @Override
// public void run() {
// Remove browser frame background to reduce overdraw
//TODO evaluate performance
// mBrowserFrame.setBackgroundColor(Color.TRANSPARENT);
// }
// }, 300);
}
@Override
public void showBlockedLocalFileDialog(DialogInterface.OnClickListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
Dialog dialog = builder.setCancelable(true)
.setTitle(R.string.title_warning)
.setMessage(R.string.message_blocked_local)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.action_open, listener)
.show();
BrowserDialog.setDialogSize(this, dialog);
}
@Override
public void showSnackbar(@StringRes int resource) {
Utils.showSnackbar(this, resource);
}
@Override
public void tabCloseClicked(int position) {
mPresenter.deleteTab(position);
}
@Override
public void tabClicked(int position) {
showTab(position);
}
@Override
public void newTabButtonClicked() {
mPresenter.newTab(null, true);
}
@Override
public void newTabButtonLongClicked() {
String url = mPreferences.getSavedUrl();
if (url != null) {
newTab(url, true);
Utils.showSnackbar(this, R.string.deleted_tab);
}
mPreferences.setSavedUrl(null);
}
@Override
public void bookmarkButtonClicked() {
final LightningView currentTab = mTabsManager.getCurrentTab();
final String url = currentTab != null ? currentTab.getUrl() : null;
final String title = currentTab != null ? currentTab.getTitle() : null;
if (url == null) {
return;
}
if (!UrlUtils.isSpecialUrl(url)) {
mBookmarkManager.isBookmark(url)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.main())
.subscribe(new SingleOnSubscribe<Boolean>() {
@Override
public void onItem(@Nullable Boolean item) {
if (Boolean.TRUE.equals(item)) {
addBookmark(title, url);
} else {
deleteBookmark(title, url);
}
}
});
}
}
@Override
public void bookmarkItemClicked(@NonNull HistoryItem item) {
mPresenter.loadUrlInCurrentView(item.getUrl());
// keep any jank from happening when the drawer is closed after the
// URL starts to load
Handlers.MAIN.postDelayed(new Runnable() {
@Override
public void run() {
closeDrawers(null);
}
}, 150);
}
@Override
public void handleHistoryChange() {
openHistory();
}
/**
* displays the WebView contained in the LightningView Also handles the
* removal of previous views
*
* @param position the poition of the tab to display
*/
// TODO move to presenter
private synchronized void showTab(final int position) {
mPresenter.tabChanged(position);
}
private static void removeViewFromParent(@Nullable View view) {
if (view == null) {
return;
}
ViewParent parent = view.getParent();
if (parent instanceof ViewGroup) {
((ViewGroup) parent).removeView(view);
}
}
void handleNewIntent(Intent intent) {
mPresenter.onNewIntent(intent);
}
@Override
public void closeEmptyTab() {
// Currently do nothing
// Possibly closing the current tab might close the browser
// and mess stuff up
}
@Override
public void onTrimMemory(int level) {
if (level > TRIM_MEMORY_MODERATE && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
Log.d(TAG, "Low Memory, Free Memory");
mPresenter.onAppLowMemory();
}
}
// TODO move to presenter
private synchronized boolean newTab(String url, boolean show) {
return mPresenter.newTab(url, show);
}
void performExitCleanUp() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (mPreferences.getClearCacheExit() && currentTab != null && !isIncognito()) {
WebUtils.clearCache(currentTab.getWebView());
Log.d(TAG, "Cache Cleared");
}
if (mPreferences.getClearHistoryExitEnabled() && !isIncognito()) {
WebUtils.clearHistory(this);
Log.d(TAG, "History Cleared");
}
if (mPreferences.getClearCookiesExitEnabled() && !isIncognito()) {
WebUtils.clearCookies(this);
Log.d(TAG, "Cookies Cleared");
}
if (mPreferences.getClearWebStorageExitEnabled() && !isIncognito()) {
WebUtils.clearWebStorage();
Log.d(TAG, "WebStorage Cleared");
} else if (isIncognito()) {
WebUtils.clearWebStorage(); // We want to make sure incognito mode is secure
}
mSuggestionsAdapter.clearCache();
}
@Override
public void onConfigurationChanged(final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, "onConfigurationChanged");
if (mFullScreen) {
showActionBar();
mToolbarLayout.setTranslationY(0);
setWebViewTranslation(mToolbarLayout.getHeight());
}
supportInvalidateOptionsMenu();
initializeToolbarHeight(newConfig);
}
private void initializeToolbarHeight(@NonNull final Configuration configuration) {
// TODO externalize the dimensions
doOnLayout(mUiLayout, new Runnable() {
@Override
public void run() {
int toolbarSize;
if (configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
// In portrait toolbar should be 56 dp tall
toolbarSize = Utils.dpToPx(56);
} else {
// In landscape toolbar should be 48 dp tall
toolbarSize = Utils.dpToPx(52);
}
mToolbar.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, toolbarSize));
mToolbar.setMinimumHeight(toolbarSize);
doOnLayout(mToolbar, new Runnable() {
@Override
public void run() {
setWebViewTranslation(mToolbarLayout.getHeight());
}
});
mToolbar.requestLayout();
}
});
}
public void closeBrowser() {
mBrowserFrame.setBackgroundColor(mBackgroundColor);
removeViewFromParent(mCurrentView);
performExitCleanUp();
int size = mTabsManager.size();
mTabsManager.shutdown();
mCurrentView = null;
for (int n = 0; n < size; n++) {
mTabsView.tabRemoved(0);
}
finish();
}
@Override
public synchronized void onBackPressed() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (mDrawerLayout.isDrawerOpen(getTabDrawer())) {
mDrawerLayout.closeDrawer(getTabDrawer());
} else if (mDrawerLayout.isDrawerOpen(getBookmarkDrawer())) {
mBookmarksView.navigateBack();
} else {
if (currentTab != null) {
Log.d(TAG, "onBackPressed");
if (mSearch.hasFocus()) {
currentTab.requestFocus();
} else if (currentTab.canGoBack()) {
if (!currentTab.isShown()) {
onHideCustomView();
} else {
currentTab.goBack();
}
} else {
if (mCustomView != null || mCustomViewCallback != null) {
onHideCustomView();
} else {
mPresenter.deleteTab(mTabsManager.positionOf(currentTab));
}
}
} else {
Log.e(TAG, "This shouldn't happen ever");
super.onBackPressed();
}
}
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
mTabsManager.pauseAll();
try {
getApplication().unregisterReceiver(mNetworkReceiver);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Receiver was not registered", e);
}
if (isIncognito() && isFinishing()) {
overridePendingTransition(R.anim.fade_in_scale, R.anim.slide_down_out);
}
}
void saveOpenTabs() {
if (mPreferences.getRestoreLostTabsEnabled()) {
mTabsManager.saveState();
}
}
@Override
protected void onStop() {
super.onStop();
mProxyUtils.onStop();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy");
Handlers.MAIN.removeCallbacksAndMessages(null);
mPresenter.shutdown();
super.onDestroy();
}
@Override
protected void onStart() {
super.onStart();
mProxyUtils.onStart(this);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mTabsManager.shutdown();
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
if (mSwapBookmarksAndTabs != mPreferences.getBookmarksAndTabsSwapped()) {
restart();
}
if (mSuggestionsAdapter != null) {
mSuggestionsAdapter.refreshPreferences();
mSuggestionsAdapter.refreshBookmarks();
}
mTabsManager.resumeAll(this);
initializePreferences();
supportInvalidateOptionsMenu();
IntentFilter filter = new IntentFilter();
filter.addAction(NETWORK_BROADCAST_ACTION);
getApplication().registerReceiver(mNetworkReceiver, filter);
if (mFullScreen) {
overlayToolbarOnWebView();
} else {
putToolbarInRoot();
}
}
/**
* searches the web for the query fixing any and all problems with the input
* checks if it is a search, url, etc.
*/
private void searchTheWeb(@NonNull String query) {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (query.isEmpty()) {
return;
}
String searchUrl = mSearchText + UrlUtils.QUERY_PLACE_HOLDER;
query = query.trim();
if (currentTab != null) {
currentTab.stopLoading();
mPresenter.loadUrlInCurrentView(UrlUtils.smartUrlFilter(query, true, searchUrl));
}
}
/**
* Animates the color of the toolbar from one color to another. Optionally animates
* the color of the tab background, for use when the tabs are displayed on the top
* of the screen.
*
* @param favicon the Bitmap to extract the color from
* @param tabBackground the optional LinearLayout to color
*/
@Override
public void changeToolbarBackground(@NonNull Bitmap favicon, @Nullable final Drawable tabBackground) {
final int defaultColor = ContextCompat.getColor(this, R.color.primary_color);
if (mCurrentUiColor == Color.BLACK) {
mCurrentUiColor = defaultColor;
}
Palette.from(favicon).generate(new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
// OR with opaque black to remove transparency glitches
int color = 0xff000000 | palette.getVibrantColor(defaultColor);
final int finalColor; // Lighten up the dark color if it is
// too dark
if (!mShowTabsInDrawer || Utils.isColorTooDark(color)) {
finalColor = Utils.mixTwoColors(defaultColor, color, 0.25f);
} else {
finalColor = color;
}
final Window window = getWindow();
if (!mShowTabsInDrawer) {
window.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
}
final int startSearchColor = getSearchBarColor(mCurrentUiColor, defaultColor);
final int finalSearchColor = getSearchBarColor(finalColor, defaultColor);
Animation animation = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final int color = DrawableUtils.mixColor(interpolatedTime, mCurrentUiColor, finalColor);
if (mShowTabsInDrawer) {
mBackground.setColor(color);
Handlers.MAIN.post(new Runnable() {
@Override
public void run() {
window.setBackgroundDrawable(mBackground);
}
});
} else if (tabBackground != null) {
tabBackground.setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
mCurrentUiColor = color;
mToolbarLayout.setBackgroundColor(color);
mSearchBackground.getBackground().setColorFilter(DrawableUtils.mixColor(interpolatedTime,
startSearchColor, finalSearchColor), PorterDuff.Mode.SRC_IN);
}
};
animation.setDuration(300);
mToolbarLayout.startAnimation(animation);
}
});
}
private int getSearchBarColor(int requestedColor, int defaultColor) {
if (requestedColor == defaultColor) {
return mDarkTheme ? DrawableUtils.mixColor(0.25f, defaultColor, Color.WHITE) : Color.WHITE;
} else {
return DrawableUtils.mixColor(0.25f, requestedColor, Color.WHITE);
}
}
@Override
public boolean getUseDarkTheme() {
return mDarkTheme;
}
@ColorInt
@Override
public int getUiColor() {
return mCurrentUiColor;
}
@Override
public void updateUrl(@Nullable String url, boolean shortUrl) {
if (url == null || mSearch == null || mSearch.hasFocus()) {
return;
}
final LightningView currentTab = mTabsManager.getCurrentTab();
mBookmarksView.handleUpdatedUrl(url);
if (shortUrl && !UrlUtils.isSpecialUrl(url)) {
switch (mPreferences.getUrlBoxContentChoice()) {
case 0: // Default, show only the domain
url = url.replaceFirst(Constants.HTTP, "");
url = Utils.getDomainName(url);
mSearch.setText(url);
break;
case 1: // URL, show the entire URL
mSearch.setText(url);
break;
case 2: // Title, show the page's title
if (currentTab != null && !currentTab.getTitle().isEmpty()) {
mSearch.setText(currentTab.getTitle());
} else {
mSearch.setText(mUntitledTitle);
}
break;
}
} else {
if (UrlUtils.isSpecialUrl(url)) {
url = "";
}
mSearch.setText(url);
}
}
@Override
public void updateTabNumber(int number) {
if (mArrowImage != null && mShowTabsInDrawer) {
mArrowImage.setImageBitmap(DrawableUtils.getRoundedNumberImage(number, Utils.dpToPx(24),
Utils.dpToPx(24), ThemeUtils.getIconThemeColor(this, mDarkTheme), Utils.dpToPx(2.5f)));
}
}
@Override
public void updateProgress(int n) {
setIsLoading(n < 100);
mProgressBar.setProgress(n);
}
void addItemToHistory(@Nullable final String title, @NonNull final String url) {
if (UrlUtils.isSpecialUrl(url)) {
return;
}
HistoryModel.visitHistoryItem(url, title)
.subscribeOn(Schedulers.io())
.subscribe(new CompletableOnSubscribe() {
@Override
public void onError(@NonNull Throwable throwable) {
Log.e(TAG, "Exception while updating history", throwable);
}
});
}
/**
* method to generate search suggestions for the AutoCompleteTextView from
* previously searched URLs
*/
private void initializeSearchSuggestions(final AutoCompleteTextView getUrl) {
mSuggestionsAdapter = new SuggestionsAdapter(this, mDarkTheme, isIncognito());
getUrl.setThreshold(1);
getUrl.setDropDownWidth(-1);
getUrl.setDropDownAnchor(R.id.toolbar_layout);
getUrl.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
String url = null;
CharSequence urlString = ((TextView) view.findViewById(R.id.url)).getText();
if (urlString != null) {
url = urlString.toString();
}
if (url == null || url.startsWith(getString(R.string.suggestion))) {
CharSequence searchString = ((TextView) view.findViewById(R.id.title)).getText();
if (searchString != null) {
url = searchString.toString();
}
}
if (url == null) {
return;
}
getUrl.setText(url);
searchTheWeb(url);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getUrl.getWindowToken(), 0);
mPresenter.onAutoCompleteItemPressed();
}
});
getUrl.setSelectAllOnFocus(true);
getUrl.setAdapter(mSuggestionsAdapter);
}
/**
* function that opens the HTML history page in the browser
*/
private void openHistory() {
new HistoryPage().getHistoryPage()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.main())
.subscribe(new SingleOnSubscribe<String>() {
@Override
public void onItem(@Nullable String item) {
Preconditions.checkNonNull(item);
LightningView view = mTabsManager.getCurrentTab();
if (view != null) {
view.loadUrl(item);
}
}
});
}
private View getBookmarkDrawer() {
return mSwapBookmarksAndTabs ? mDrawerLeft : mDrawerRight;
}
private View getTabDrawer() {
return mSwapBookmarksAndTabs ? mDrawerRight : mDrawerLeft;
}
/**
* helper function that opens the bookmark drawer
*/
private void openBookmarks() {
if (mDrawerLayout.isDrawerOpen(getTabDrawer())) {
mDrawerLayout.closeDrawers();
}
mDrawerLayout.openDrawer(getBookmarkDrawer());
}
/**
* This method closes any open drawer and executes
* the runnable after the drawers are completely closed.
*
* @param runnable an optional runnable to run after
* the drawers are closed.
*/
void closeDrawers(@Nullable final Runnable runnable) {
if (!mDrawerLayout.isDrawerOpen(mDrawerLeft) && !mDrawerLayout.isDrawerOpen(mDrawerRight)) {
if (runnable != null) {
runnable.run();
return;
}
}
mDrawerLayout.closeDrawers();
mDrawerLayout.addDrawerListener(new DrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {}
@Override
public void onDrawerOpened(View drawerView) {}
@Override
public void onDrawerClosed(View drawerView) {
if (runnable != null) {
runnable.run();
}
mDrawerLayout.removeDrawerListener(this);
}
@Override
public void onDrawerStateChanged(int newState) {}
});
}
@Override
public void setForwardButtonEnabled(boolean enabled) {
if (mForwardMenuItem != null && mForwardMenuItem.getIcon() != null) {
int colorFilter;
if (enabled) {
colorFilter = mIconColor;
} else {
colorFilter = mDisabledIconColor;
}
mForwardMenuItem.getIcon().setColorFilter(colorFilter, PorterDuff.Mode.SRC_IN);
mForwardMenuItem.setIcon(mForwardMenuItem.getIcon());
}
}
@Override
public void setBackButtonEnabled(boolean enabled) {
if (mBackMenuItem != null && mBackMenuItem.getIcon() != null) {
int colorFilter;
if (enabled) {
colorFilter = mIconColor;
} else {
colorFilter = mDisabledIconColor;
}
mBackMenuItem.getIcon().setColorFilter(colorFilter, PorterDuff.Mode.SRC_IN);
mBackMenuItem.setIcon(mBackMenuItem.getIcon());
}
}
private MenuItem mBackMenuItem;
private MenuItem mForwardMenuItem;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
mBackMenuItem = menu.findItem(R.id.action_back);
mForwardMenuItem = menu.findItem(R.id.action_forward);
if (mBackMenuItem != null && mBackMenuItem.getIcon() != null)
mBackMenuItem.getIcon().setColorFilter(mIconColor, PorterDuff.Mode.SRC_IN);
if (mForwardMenuItem != null && mForwardMenuItem.getIcon() != null)
mForwardMenuItem.getIcon().setColorFilter(mIconColor, PorterDuff.Mode.SRC_IN);
return super.onCreateOptionsMenu(menu);
}
/**
* opens a file chooser
* param ValueCallback is the message from the WebView indicating a file chooser
* should be opened
*/
@Override
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i, getString(R.string.title_file_chooser)), 1);
}
/**
* used to allow uploading into the browser
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (API < Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == 1) {
if (null == mUploadMessage) {
return;
}
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
if (requestCode != 1 || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, intent);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (intent == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = intent.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
}
@Override
public void showFileChooser(ValueCallback<Uri[]> filePathCallback) {
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(this.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = Utils.createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, 1);
}
@Override
public synchronized void onShowCustomView(View view, CustomViewCallback callback) {
int requestedOrientation = mOriginalOrientation = getRequestedOrientation();
onShowCustomView(view, callback, requestedOrientation);
}
@Override
public synchronized void onShowCustomView(final View view, CustomViewCallback callback, int requestedOrientation) {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (view == null || mCustomView != null) {
if (callback != null) {
try {
callback.onCustomViewHidden();
} catch (Exception e) {
Log.e(TAG, "Error hiding custom view", e);
}
}
return;
}
try {
view.setKeepScreenOn(true);
} catch (SecurityException e) {
Log.e(TAG, "WebView is not allowed to keep the screen on");
}
mOriginalOrientation = getRequestedOrientation();
mCustomViewCallback = callback;
mCustomView = view;
setRequestedOrientation(requestedOrientation);
final FrameLayout decorView = (FrameLayout) getWindow().getDecorView();
mFullscreenContainer = new FrameLayout(this);
mFullscreenContainer.setBackgroundColor(ContextCompat.getColor(this, android.R.color.black));
if (view instanceof FrameLayout) {
if (((FrameLayout) view).getFocusedChild() instanceof VideoView) {
mVideoView = (VideoView) ((FrameLayout) view).getFocusedChild();
mVideoView.setOnErrorListener(new VideoCompletionListener());
mVideoView.setOnCompletionListener(new VideoCompletionListener());
}
} else if (view instanceof VideoView) {
mVideoView = (VideoView) view;
mVideoView.setOnErrorListener(new VideoCompletionListener());
mVideoView.setOnCompletionListener(new VideoCompletionListener());
}
decorView.addView(mFullscreenContainer, COVER_SCREEN_PARAMS);
mFullscreenContainer.addView(mCustomView, COVER_SCREEN_PARAMS);
decorView.requestLayout();
setFullscreen(true, true);
if (currentTab != null) {
currentTab.setVisibility(View.INVISIBLE);
}
}
@Override
public void closeBookmarksDrawer() {
mDrawerLayout.closeDrawer(getBookmarkDrawer());
}
@Override
public void onHideCustomView() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (mCustomView == null || mCustomViewCallback == null || currentTab == null) {
if (mCustomViewCallback != null) {
try {
mCustomViewCallback.onCustomViewHidden();
} catch (Exception e) {
Log.e(TAG, "Error hiding custom view", e);
}
mCustomViewCallback = null;
}
return;
}
Log.d(TAG, "onHideCustomView");
currentTab.setVisibility(View.VISIBLE);
try {
mCustomView.setKeepScreenOn(false);
} catch (SecurityException e) {
Log.e(TAG, "WebView is not allowed to keep the screen on");
}
setFullscreen(mPreferences.getHideStatusBarEnabled(), false);
if (mFullscreenContainer != null) {
ViewGroup parent = (ViewGroup) mFullscreenContainer.getParent();
if (parent != null) {
parent.removeView(mFullscreenContainer);
}
mFullscreenContainer.removeAllViews();
}
mFullscreenContainer = null;
mCustomView = null;
if (mVideoView != null) {
Log.d(TAG, "VideoView is being stopped");
mVideoView.stopPlayback();
mVideoView.setOnErrorListener(null);
mVideoView.setOnCompletionListener(null);
mVideoView = null;
}
if (mCustomViewCallback != null) {
try {
mCustomViewCallback.onCustomViewHidden();
} catch (Exception e) {
Log.e(TAG, "Error hiding custom view", e);
}
}
mCustomViewCallback = null;
setRequestedOrientation(mOriginalOrientation);
}
private class VideoCompletionListener implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
@Override
public void onCompletion(MediaPlayer mp) {
onHideCustomView();
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d(TAG, "onWindowFocusChanged");
if (hasFocus) {
setFullscreen(mIsFullScreen, mIsImmersive);
}
}
@Override
public void onBackButtonPressed() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (currentTab != null) {
if (currentTab.canGoBack()) {
currentTab.goBack();
} else {
mPresenter.deleteTab(mTabsManager.positionOf(currentTab));
}
}
}
@Override
public void onForwardButtonPressed() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (currentTab != null) {
if (currentTab.canGoForward()) {
currentTab.goForward();
}
}
}
@Override
public void onHomeButtonPressed() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (currentTab != null) {
currentTab.loadHomepage();
closeDrawers(null);
}
}
/**
* This method sets whether or not the activity will display
* in full-screen mode (i.e. the ActionBar will be hidden) and
* whether or not immersive mode should be set. This is used to
* set both parameters correctly as during a full-screen video,
* both need to be set, but other-wise we leave it up to user
* preference.
*
* @param enabled true to enable full-screen, false otherwise
* @param immersive true to enable immersive mode, false otherwise
*/
private void setFullscreen(boolean enabled, boolean immersive) {
mIsFullScreen = enabled;
mIsImmersive = immersive;
Window window = getWindow();
View decor = window.getDecorView();
if (enabled) {
if (immersive) {
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
} else {
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
/**
* This method handles the JavaScript callback to create a new tab.
* Basically this handles the event that JavaScript needs to create
* a popup.
*
* @param resultMsg the transport message used to send the URL to
* the newly created WebView.
*/
@Override
public synchronized void onCreateWindow(Message resultMsg) {
if (resultMsg == null) {
return;
}
if (newTab("", true)) {
LightningView newTab = mTabsManager.getTabAtPosition(mTabsManager.size() - 1);
if (newTab != null) {
final WebView webView = newTab.getWebView();
if (webView != null) {
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(webView);
resultMsg.sendToTarget();
}
}
}
}
/**
* Closes the specified {@link LightningView}. This implements
* the JavaScript callback that asks the tab to close itself and
* is especially helpful when a page creates a redirect and does
* not need the tab to stay open any longer.
*
* @param view the LightningView to close, delete it.
*/
@Override
public void onCloseWindow(LightningView view) {
mPresenter.deleteTab(mTabsManager.positionOf(view));
}
/**
* Hide the ActionBar using an animation if we are in full-screen
* mode. This method also re-parents the ActionBar if its parent is
* incorrect so that the animation can happen correctly.
*/
@Override
public void hideActionBar() {
if (mFullScreen) {
if (mToolbarLayout == null || mBrowserFrame == null)
return;
final int height = mToolbarLayout.getHeight();
if (mToolbarLayout.getTranslationY() > -0.01f) {
Animation show = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float trans = interpolatedTime * height;
mToolbarLayout.setTranslationY(-trans);
setWebViewTranslation(height - trans);
}
};
show.setDuration(250);
show.setInterpolator(new BezierDecelerateInterpolator());
mBrowserFrame.startAnimation(show);
}
}
}
/**
* Display the ActionBar using an animation if we are in full-screen
* mode. This method also re-parents the ActionBar if its parent is
* incorrect so that the animation can happen correctly.
*/
@Override
public void showActionBar() {
if (mFullScreen) {
Log.d(TAG, "showActionBar");
if (mToolbarLayout == null)
return;
int height = mToolbarLayout.getHeight();
if (height == 0) {
mToolbarLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
height = mToolbarLayout.getMeasuredHeight();
}
final int totalHeight = height;
if (mToolbarLayout.getTranslationY() < -(height - 0.01f)) {
Animation show = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float trans = interpolatedTime * totalHeight;
mToolbarLayout.setTranslationY(trans - totalHeight);
setWebViewTranslation(trans);
}
};
show.setDuration(250);
show.setInterpolator(new BezierDecelerateInterpolator());
mBrowserFrame.startAnimation(show);
}
}
}
@Override
public void handleBookmarksChange() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (currentTab != null && currentTab.getUrl().startsWith(Constants.FILE)
&& currentTab.getUrl().endsWith(BookmarkPage.FILENAME)) {
currentTab.loadBookmarkpage();
}
if (currentTab != null) {
mBookmarksView.handleUpdatedUrl(currentTab.getUrl());
}
}
@Override
public void handleBookmarkDeleted(@NonNull HistoryItem item) {
mBookmarksView.handleBookmarkDeleted(item);
handleBookmarksChange();
}
@Override
public void handleNewTab(@NonNull LightningDialogBuilder.NewTab newTabType, @NonNull String url) {
mDrawerLayout.closeDrawers();
switch (newTabType) {
case FOREGROUND:
newTab(url, true);
break;
case BACKGROUND:
newTab(url, false);
break;
case INCOGNITO:
Intent intent = new Intent(BrowserActivity.this, IncognitoActivity.class);
intent.setData(Uri.parse(url));
startActivity(intent);
overridePendingTransition(R.anim.slide_up_in, R.anim.fade_out_scale);
break;
}
}
/**
* Performs an action when the provided view is laid out.
*
* @param view the view to listen to for layouts.
* @param runnable the runnable to run when the view is
* laid out.
*/
private static void doOnLayout(@NonNull final View view, @NonNull final Runnable runnable) {
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
//noinspection deprecation
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
runnable.run();
}
});
}
/**
* This method lets the search bar know that the page is currently loading
* and that it should display the stop icon to indicate to the user that
* pressing it stops the page from loading
*/
private void setIsLoading(boolean isLoading) {
if (!mSearch.hasFocus()) {
mIcon = isLoading ? mDeleteIcon : mRefreshIcon;
mSearch.setCompoundDrawables(null, null, mIcon, null);
}
}
/**
* handle presses on the refresh icon in the search bar, if the page is
* loading, stop the page, if it is done loading refresh the page.
* See setIsFinishedLoading and setIsLoading for displaying the correct icon
*/
private void refreshOrStop() {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (currentTab != null) {
if (currentTab.getProgress() < 100) {
currentTab.stopLoading();
} else {
currentTab.reload();
}
}
}
/**
* Handle the click event for the views that are using
* this class as a click listener. This method should
* distinguish between the various views using their IDs.
*
* @param v the view that the user has clicked
*/
@Override
public void onClick(View v) {
final LightningView currentTab = mTabsManager.getCurrentTab();
if (currentTab == null) {
return;
}
switch (v.getId()) {
case R.id.arrow_button:
if (mSearch != null && mSearch.hasFocus()) {
currentTab.requestFocus();
} else if (mShowTabsInDrawer) {
mDrawerLayout.openDrawer(getTabDrawer());
} else {
currentTab.loadHomepage();
}
break;
case R.id.button_next:
currentTab.findNext();
break;
case R.id.button_back:
currentTab.findPrevious();
break;
case R.id.button_quit:
currentTab.clearFindMatches();
mSearchBar.setVisibility(View.GONE);
break;
case R.id.action_reading:
Intent read = new Intent(this, ReadingActivity.class);
read.putExtra(Constants.LOAD_READING_URL, currentTab.getUrl());
startActivity(read);
break;
case R.id.action_toggle_desktop:
currentTab.toggleDesktopUA(this);
currentTab.reload();
closeDrawers(null);
break;
}
}
/**
* This NetworkReceiver notifies each of the WebViews in the browser whether
* the network is currently connected or not. This is important because some
* JavaScript properties rely on the WebView knowing the current network state.
* It is used to help the browser be compliant with the HTML5 spec, sec. 5.7.7
*/
private final NetworkReceiver mNetworkReceiver = new NetworkReceiver() {
@Override
public void onConnectivityChange(boolean isConnected) {
Log.d(TAG, "Network Connected: " + isConnected);
mTabsManager.notifyConnectionStatus(isConnected);
}
};
/**
* Handle the callback that permissions requested have been granted or not.
* This method should act upon the results of the permissions request.
*
* @param requestCode the request code sent when initially making the request
* @param permissions the array of the permissions that was requested
* @param grantResults the results of the permissions requests that provides
* information on whether the request was granted or not
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
| Fixing bug where add/remove bookmark button didn't work
| app/src/main/java/acr/browser/lightning/activity/BrowserActivity.java | Fixing bug where add/remove bookmark button didn't work |
|
Java | agpl-3.0 | 0a26c1607ee5565d0d4b0d4c523d25919321d07e | 0 | chirino/cloudmix,chirino/cloudmix | /**************************************************************************************
* Copyright (C) 2009 Progress Software, Inc. All rights reserved. *
* http://fusesource.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the AGPL license *
* a copy of which has been included with this distribution in the license.txt file. *
**************************************************************************************/
package org.fusesource.cloudmix.features.osgi;
import static org.ops4j.pax.exam.CoreOptions.*;
import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.*;
import javax.print.attribute.standard.MediaSize.Other;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Inject;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
/**
* @version $Revision: 1.1 $
*/
@RunWith(JUnit4TestRunner.class)
public class FeaturesIntegrationTest extends TestCase {
@Inject
protected BundleContext bundleContext;
@Test
public void testFeatureRunsInOsgi() throws Exception {
System.out.println("Started up!");
boolean allActive = true;
for(Bundle b: bundleContext.getBundles()) {
System.out.println(b.getBundleId() + "\t" + b.getSymbolicName() + "\t" + state2String(b.getState()));
if (b.getState() != Bundle.ACTIVE) {
allActive = false;
}
}
Thread.sleep(1000);
assertTrue(allActive);
//System.out.println("Worked!!!");
}
@Configuration
public static Option[] configure() {
Option[] options = options(
// lets zap the caches first to ensure we're using the latest/greatest
cleanCaches(),
// install log service using pax runners profile abstraction (there are more profiles, like DS)
logProfile().version("1.3.0"),
profile("karaf.gogo", "1.2.0"),
// using the features to install the features
scanFeatures(mavenBundle().groupId("org.fusesource.cloudmix").
artifactId("features").versionAsInProject().type("xml/features"),
"cloudmix.agent"),
cleanCaches(),
systemProperty("karaf.home").value(System.getProperty("user.dir")),
systemProperty("karaf.name").value("root"),
systemProperty("karaf.startLocalConsole").value("false"),
systemProperty("karaf.startRemoteConsole").value("false"),
systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("DEBUG"),
felix() //, equinox(), knopflerfish()
);
return options;
}
private String state2String(final int state) {
switch(state) {
case Bundle.ACTIVE : return "Active";
case Bundle.INSTALLED : return "Installed";
case Bundle.RESOLVED : return "Resolved";
case Bundle.STARTING : return "Starting";
case Bundle.STOPPING : return "Stopping";
case Bundle.UNINSTALLED : return "Uninstalled";
default : return "Unknown";
}
}
}
| systests/feature-test/src/test/java/org/fusesource/cloudmix/features/osgi/FeaturesIntegrationTest.java | /**************************************************************************************
* Copyright (C) 2009 Progress Software, Inc. All rights reserved. *
* http://fusesource.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the AGPL license *
* a copy of which has been included with this distribution in the license.txt file. *
**************************************************************************************/
package org.fusesource.cloudmix.features.osgi;
import static org.ops4j.pax.exam.CoreOptions.*;
import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.*;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Inject;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.osgi.framework.BundleContext;
/**
* @version $Revision: 1.1 $
*/
@RunWith(JUnit4TestRunner.class)
public class FeaturesIntegrationTest extends TestCase {
@Inject
protected BundleContext bundleContext;
@Test
public void testFeatureRunsInOsgi() throws Exception {
System.out.println("Started up!");
Thread.sleep(1000);
System.out.println("Worked!!!");
}
@Configuration
public static Option[] configure() {
Option[] options = options(
// lets zap the caches first to ensure we're using the latest/greatest
cleanCaches(),
// install log service using pax runners profile abstraction (there are more profiles, like DS)
logProfile().version("1.3.0"),
profile("karaf.gogo", "1.2.0"),
// using the features to install the features
scanFeatures(mavenBundle().groupId("org.fusesource.cloudmix").
artifactId("features").versionAsInProject().type("xml/features"),
"cloudmix.agent"),
cleanCaches(),
systemProperty("karaf.home").value(System.getProperty("user.dir")),
systemProperty("karaf.name").value("root"),
systemProperty("karaf.startLocalConsole").value("false"),
systemProperty("karaf.startRemoteConsole").value("false"),
systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("DEBUG"),
felix() //, equinox(), knopflerfish()
);
return options;
}
}
| Changed the test to make it fail when one or more bundles don't come up active
git-svn-id: a568a09a6707b2415012d77e49a6c5c13d2f9ed5@133 c32a53b6-b962-0410-9d7f-cad4864ec771
| systests/feature-test/src/test/java/org/fusesource/cloudmix/features/osgi/FeaturesIntegrationTest.java | Changed the test to make it fail when one or more bundles don't come up active |
|
Java | lgpl-2.1 | e6329138d033176d564d28cbd9dbdf31a5c6cb62 | 0 | cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl | package org.cytoscape.task.internal.loadvizmap;
/*
* #%L
* Cytoscape Core Task Impl (core-task-impl)
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2006 - 2013 The Cytoscape Consortium
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.cytoscape.io.read.VizmapReaderManager;
import org.cytoscape.task.read.LoadVizmapFileTaskFactory;
import org.cytoscape.view.vizmap.VisualMappingManager;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.work.AbstractTaskFactory;
import org.cytoscape.work.SynchronousTaskManager;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TunableSetter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoadVizmapFileTaskFactoryImpl extends AbstractTaskFactory implements LoadVizmapFileTaskFactory {
private static final Logger logger = LoggerFactory.getLogger(LoadVizmapFileTaskFactoryImpl.class);
private final VizmapReaderManager vizmapReaderMgr;
private final VisualMappingManager vmMgr;
private final SynchronousTaskManager<?> syncTaskManager;
private LoadVizmapFileTask task;
private final TunableSetter tunableSetter;
public LoadVizmapFileTaskFactoryImpl(VizmapReaderManager vizmapReaderMgr, VisualMappingManager vmMgr,
SynchronousTaskManager<?> syncTaskManager, TunableSetter tunableSetter) {
this.vizmapReaderMgr = vizmapReaderMgr;
this.vmMgr = vmMgr;
this.syncTaskManager = syncTaskManager;
this.tunableSetter = tunableSetter;
}
@Override
public TaskIterator createTaskIterator() {
task = new LoadVizmapFileTask(vizmapReaderMgr, vmMgr);
return new TaskIterator(2, task);
}
public Set<VisualStyle> loadStyles(File f) {
// Set up map containing values to be assigned to tunables.
// The name "file" is the name of the tunable field in
// LoadVizmapFileTask.
Map<String, Object> m = new HashMap<String, Object>();
m.put("file", f);
syncTaskManager.setExecutionContext(m);
syncTaskManager.execute(createTaskIterator());
return task.getStyles();
}
public Set<VisualStyle> loadStyles(final InputStream is) {
// Save the contents of inputStream in a tmp file
File f = null;
try {
f = this.getFileFromStream(is);
} catch (IOException e) {
throw new IllegalStateException("Could not create temp file", e);
}
if (f == null)
throw new NullPointerException("Could not create temp file.");
return this.loadStyles(f);
}
@Override
public TaskIterator createTaskIterator(File file) {
final Map<String, Object> m = new HashMap<String, Object>();
m.put("file", file);
return tunableSetter.createTaskIterator(this.createTaskIterator(), m);
}
// Read the inputStream and save the content in a tmp file
private File getFileFromStream(final InputStream is) throws IOException {
File returnFile = null;
// Get the contents from inputStream
final List<String> list = new ArrayList<String>();
BufferedReader bf = null;
String line;
try {
bf = new BufferedReader(new InputStreamReader(is));
while (null != (line = bf.readLine())) {
list.add(line);
}
} catch (IOException e) {
logger.error("Could not read the VizMap file.", e);
} finally {
try {
if (bf != null)
bf.close();
} catch (IOException e) {
logger.error("Could not Close the stream.", e);
bf = null;
}
}
if (list.size() == 0)
return null;
// Save the content to a tmp file
Writer output = null;
try {
returnFile = File.createTempFile("visualStyles", "", new File(System.getProperty("java.io.tmpdir")));
returnFile.deleteOnExit();
// use buffering
output = new BufferedWriter(new FileWriter(returnFile));
// FileWriter always assumes default encoding is OK!
for (int i = 0; i < list.size(); i++) {
output.write(list.get(i) + "\n");
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
output = null;
} catch (IOException e) {
logger.error("Could not close stream.", e);
output = null;
}
}
}
if (returnFile == null)
throw new NullPointerException("Could not create temp VizMap file.");
final String originalFileName = returnFile.getAbsolutePath();
if (isXML(list)) {
final File xmlFile = new File(originalFileName + ".xml");
final boolean renamed = returnFile.renameTo(xmlFile);
if (renamed)
return xmlFile;
else
throw new IOException("Could not create temp vizmap file: " + xmlFile);
} else {
// Return ad legacy property format
final File propFile = new File(originalFileName + ".props");
final boolean renamed = returnFile.renameTo(propFile);
if (renamed)
return propFile;
else
throw new IOException("Could not create temp vizmap file: " + propFile);
}
}
/**
* Perform simple test whether this file is XML or not.
*
* @return
*/
private final boolean isXML(final List<String> list) {
if(list == null || list.isEmpty())
return false;
if(list.get(0).contains("<?xml"))
return true;
else
return false;
}
}
| core-task-impl/src/main/java/org/cytoscape/task/internal/loadvizmap/LoadVizmapFileTaskFactoryImpl.java | package org.cytoscape.task.internal.loadvizmap;
/*
* #%L
* Cytoscape Core Task Impl (core-task-impl)
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2006 - 2013 The Cytoscape Consortium
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.cytoscape.io.read.VizmapReaderManager;
import org.cytoscape.task.read.LoadVizmapFileTaskFactory;
import org.cytoscape.view.vizmap.VisualMappingManager;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.work.AbstractTaskFactory;
import org.cytoscape.work.SynchronousTaskManager;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TunableSetter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoadVizmapFileTaskFactoryImpl extends AbstractTaskFactory implements LoadVizmapFileTaskFactory {
private static final Logger logger = LoggerFactory.getLogger(LoadVizmapFileTaskFactoryImpl.class);
private final VizmapReaderManager vizmapReaderMgr;
private final VisualMappingManager vmMgr;
private final SynchronousTaskManager<?> syncTaskManager;
private LoadVizmapFileTask task;
private final TunableSetter tunableSetter;
public LoadVizmapFileTaskFactoryImpl(VizmapReaderManager vizmapReaderMgr, VisualMappingManager vmMgr,
SynchronousTaskManager<?> syncTaskManager, TunableSetter tunableSetter) {
this.vizmapReaderMgr = vizmapReaderMgr;
this.vmMgr = vmMgr;
this.syncTaskManager = syncTaskManager;
this.tunableSetter = tunableSetter;
}
@Override
public TaskIterator createTaskIterator() {
task = new LoadVizmapFileTask(vizmapReaderMgr, vmMgr);
return new TaskIterator(2, task);
}
public Set<VisualStyle> loadStyles(File f) {
// Set up map containing values to be assigned to tunables.
// The name "file" is the name of the tunable field in
// LoadVizmapFileTask.
Map<String, Object> m = new HashMap<String, Object>();
m.put("file", f);
syncTaskManager.setExecutionContext(m);
syncTaskManager.execute(createTaskIterator());
return task.getStyles();
}
public Set<VisualStyle> loadStyles(InputStream is) {
// Save the contents of inputStream in a tmp file
File f = this.getFileFromStream(is);
return this.loadStyles(f);
}
@Override
public TaskIterator createTaskIterator(File file) {
final Map<String, Object> m = new HashMap<String, Object>();
m.put("file", file);
return tunableSetter.createTaskIterator(this.createTaskIterator(), m);
}
// Read the inputStream and save the content in a tmp file
private File getFileFromStream(InputStream is) {
File returnFile = null;
// Get the contents from inputStream
ArrayList<String> list = new ArrayList<String>();
BufferedReader bf = null;
String line;
try {
bf = new BufferedReader(new InputStreamReader(is));
while (null != (line = bf.readLine())) {
list.add(line);
}
} catch (IOException e) {
logger.error("Could not read the VizMap file.", e);
} finally {
try {
if (bf != null)
bf.close();
} catch (IOException e) {
logger.error("Could not Close the stream.", e);
bf = null;
}
}
if (list.size() == 0)
return null;
// Save the content to a tmp file
Writer output = null;
try {
returnFile = File.createTempFile("visualStyles", ".props", new File(System.getProperty("java.io.tmpdir")));
returnFile.deleteOnExit();
// use buffering
output = new BufferedWriter(new FileWriter(returnFile));
// FileWriter always assumes default encoding is OK!
for (int i = 0; i < list.size(); i++) {
output.write(list.get(i) + "\n");
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
output = null;
} catch (IOException e) {
logger.error("Could not close stream.", e);
output = null;
}
}
}
return returnFile;
}
}
| fixes #1785 Correct extension will be given to the temp VizMap file.
Change-Id: I2d9371dabcda26eed77b5fedc701e22c57b85343
| core-task-impl/src/main/java/org/cytoscape/task/internal/loadvizmap/LoadVizmapFileTaskFactoryImpl.java | fixes #1785 Correct extension will be given to the temp VizMap file. |
|
Java | unlicense | c5092a90c1c2edbb93127d7d3c30895b63a22395 | 0 | ferreusveritas/Growing-Trees | package com.ferreusveritas.dynamictrees.event;
import com.ferreusveritas.dynamictrees.trees.Species;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fml.common.eventhandler.Cancelable;
import net.minecraftforge.fml.common.eventhandler.Event;
@Cancelable
public class SeedVoluntaryPlantEvent extends Event {
protected EntityItem seedEntityItem;
protected ItemStack seedStack;
protected Species species;
protected BlockPos pos;//Where the sapling will be created
protected boolean willPlant = false;
public SeedVoluntaryPlantEvent(EntityItem entityItem, Species species, BlockPos pos, boolean willPlant) {
this.seedEntityItem = entityItem;
this.pos = pos;
this.species = species;
this.willPlant = willPlant;
}
public Species getSpecies() {
return species;
}
public void setSpecies(Species species) {
this.species = species;
}
public EntityItem getEntityItem() {
return seedEntityItem;
}
public BlockPos getPos() {
return pos;
}
/**
* Use this to force the seed to plant regardless of it's natural chances
*
* @param force true to force sapling to plant. false will allow nature to take it's coarse.
*/
public void setWillPlant(boolean willPlant) {
this.willPlant = willPlant;
}
public boolean getWillPlant() {
return willPlant;
}
}
| src/main/java/com/ferreusveritas/dynamictrees/event/SeedVoluntaryPlantEvent.java | package com.ferreusveritas.dynamictrees.event;
import com.ferreusveritas.dynamictrees.trees.Species;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fml.common.eventhandler.Cancelable;
import net.minecraftforge.fml.common.eventhandler.Event;
@Cancelable
public class SeedVoluntaryPlantEvent extends Event {
EntityItem seedEntityItem;
ItemStack seedStack;
Species species;
BlockPos pos;//Where the sapling will be created
boolean forcePlant = false;
public SeedVoluntaryPlantEvent(EntityItem entityItem, Species species, BlockPos pos) {
this.seedEntityItem = entityItem;
this.pos = pos;
this.species = species;
}
public Species getSpecies() {
return species;
}
public EntityItem getEntityItem() {
return seedEntityItem;
}
public BlockPos getPos() {
return pos;
}
/**
* Use this to force the seed to plant regardless of it's natural chances
*
* @param force true to force sapling to plant. false will allow nature to take it's coarse.
*/
public void forcePlanting(boolean force) {
this.forcePlant = force;
}
public boolean doForcePlant() {
return forcePlant;
}
}
| Better Seed Voluntary event | src/main/java/com/ferreusveritas/dynamictrees/event/SeedVoluntaryPlantEvent.java | Better Seed Voluntary event |
|
Java | apache-2.0 | cc17b7c025010eb502d743d8a2844a56fde0b874 | 0 | jerrinot/hazelcast-stabilizer,hazelcast/hazelcast-simulator,jerrinot/hazelcast-stabilizer,hazelcast/hazelcast-simulator,fengshao0907/hazelcast-simulator,Danny-Hazelcast/hazelcast-stabilizer,pveentjer/hazelcast-simulator,hasancelik/hazelcast-stabilizer,Danny-Hazelcast/hazelcast-stabilizer,hazelcast/hazelcast-simulator,hasancelik/hazelcast-stabilizer,pveentjer/hazelcast-simulator,Donnerbart/hazelcast-simulator,Donnerbart/hazelcast-simulator,fengshao0907/hazelcast-simulator | package com.hazelcast.simulator.coordinator;
import com.hazelcast.simulator.agent.workerjvm.WorkerJvmSettings;
import com.hazelcast.simulator.coordinator.remoting.AgentsClient;
import com.hazelcast.simulator.probes.probes.Result;
import com.hazelcast.simulator.probes.probes.impl.OperationsPerSecResult;
import com.hazelcast.simulator.test.Failure;
import com.hazelcast.simulator.test.TestCase;
import com.hazelcast.simulator.test.TestPhase;
import com.hazelcast.simulator.test.TestSuite;
import com.hazelcast.simulator.worker.commands.Command;
import com.hazelcast.simulator.worker.commands.GetBenchmarkResultsCommand;
import com.hazelcast.simulator.worker.commands.StopCommand;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import static com.hazelcast.simulator.utils.FileUtils.deleteQuiet;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anySetOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CoordinatorRunTestSuiteTest {
private static String userDir;
private final TestSuite testSuite = new TestSuite();
@Mock
private final WorkerJvmSettings workerJvmSettings = new WorkerJvmSettings();
@Mock
private final AgentsClient agentsClient = mock(AgentsClient.class);
@Mock
private final FailureMonitor failureMonitor = mock(FailureMonitor.class);
@Mock
private final PerformanceMonitor performanceMonitor = mock(PerformanceMonitor.class);
@InjectMocks
private Coordinator coordinator;
@BeforeClass
public static void setUp() throws Exception {
userDir = System.getProperty("user.dir");
System.setProperty("user.dir", "./dist/src/main/dist");
}
@AfterClass
public static void tearDown() {
System.setProperty("user.dir", userDir);
}
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
List<String> privateAddressList = new ArrayList<String>(1);
privateAddressList.add("127.0.0.1");
TestCase testCase1 = new TestCase("CoordinatorTest1");
TestCase testCase2 = new TestCase("CoordinatorTest2");
testSuite.addTest(testCase1);
testSuite.addTest(testCase2);
coordinator.testSuite = testSuite;
coordinator.cooldownSeconds = 0;
coordinator.testCaseRunnerSleepPeriod = 3;
coordinator.lastTestPhaseToSync = TestPhase.SETUP;
when(agentsClient.getPublicAddresses()).thenReturn(privateAddressList);
when(agentsClient.getAgentCount()).thenReturn(1);
when(failureMonitor.getFailureCount()).thenReturn(0);
when(performanceMonitor.getPerformanceNumbers()).thenReturn(" (PerformanceMonitor is mocked)");
}
@After
public void cleanUp() {
deleteQuiet(new File("probes-" + testSuite.id + "_CoordinatorTest1.xml"));
deleteQuiet(new File("probes-" + testSuite.id + "_CoordinatorTest2.xml"));
}
@Test
public void runTestSuiteParallel_waitForTestCase_and_duration() throws Exception {
coordinator.testSuite.waitForTestCase = true;
coordinator.testSuite.durationSeconds = 3;
coordinator.parallel = true;
coordinator.runTestSuite();
verifyAgentsClient(coordinator);
}
@Test
public void runTestSuiteParallel_waitForTestCase_noVerify() throws Exception {
coordinator.testSuite.waitForTestCase = true;
coordinator.testSuite.durationSeconds = 0;
coordinator.parallel = true;
coordinator.verifyEnabled = false;
coordinator.runTestSuite();
verifyAgentsClient(coordinator);
}
@Test
public void runTestSuiteParallel_performanceMonitorEnabled() throws Exception {
coordinator.testSuite.durationSeconds = 4;
coordinator.parallel = true;
coordinator.monitorPerformance = true;
coordinator.runTestSuite();
verifyAgentsClient(coordinator);
}
@Test
public void runTestSuiteSequential_hasCriticalFailures() throws Exception {
when(failureMonitor.hasCriticalFailure(anySetOf(Failure.Type.class))).thenReturn(true);
coordinator.testSuite.durationSeconds = 4;
coordinator.parallel = false;
coordinator.runTestSuite();
verifyAgentsClient(coordinator);
}
@Test
public void runTestSuiteSequential_probeResults() throws Exception {
Answer<List<List<Map<String, Result>>>> probeResultsAnswer = new Answer<List<List<Map<String, Result>>>>() {
@Override
@SuppressWarnings("unchecked")
public List<List<Map<String, Result>>> answer(InvocationOnMock invocation) throws Throwable {
Map<String, Result> resultMap = new HashMap<String, Result>();
resultMap.put("CoordinatorTest1", new OperationsPerSecResult(1000, 23.42f));
resultMap.put("CoordinatorTest2", new OperationsPerSecResult(2000, 42.23f));
List<Map<String, Result>> resultList = new ArrayList<Map<String, Result>>();
resultList.add(resultMap);
List<List<Map<String, Result>>> result = new ArrayList<List<Map<String, Result>>>();
result.add(resultList);
return result;
}
};
when(agentsClient.executeOnAllWorkers(isA(GetBenchmarkResultsCommand.class))).thenAnswer(probeResultsAnswer);
coordinator.testSuite.durationSeconds = 1;
coordinator.parallel = false;
coordinator.runTestSuite();
verifyAgentsClient(coordinator);
}
@Test
public void runTestSuite_getProbeResultsTimeoutException() throws Exception {
when(agentsClient.executeOnAllWorkers(isA(GetBenchmarkResultsCommand.class))).thenThrow(new TimeoutException());
coordinator.testSuite.durationSeconds = 1;
coordinator.parallel = true;
coordinator.runTestSuite();
}
@Test
public void runTestSuite_stopThreadTimeoutException() throws Exception {
when(agentsClient.executeOnAllWorkers(isA(StopCommand.class))).thenThrow(new TimeoutException());
coordinator.testSuite.durationSeconds = 1;
coordinator.parallel = true;
coordinator.runTestSuite();
}
@Test
public void runTestSuite_withException() throws Exception {
when(agentsClient.executeOnAllWorkers(any(Command.class))).thenThrow(new RuntimeException("expected"));
coordinator.runTestSuite();
}
private void verifyAgentsClient(Coordinator coordinator) throws Exception {
boolean verifyExecuteOnAllWorkersWithRange = false;
int numberOfTests = coordinator.testSuite.size();
int phaseNumber = TestPhase.values().length;
int executeOnFirstWorkerTimes = 0;
int executeOnAllWorkersTimes = 3; // InitCommand, StopCommand and GetBenchmarkResultsCommand
for (TestPhase testPhase : TestPhase.values()) {
if (testPhase.desc().startsWith("global")) {
executeOnFirstWorkerTimes++;
} else {
executeOnAllWorkersTimes++;
}
}
int waitForPhaseCompletionTimes = phaseNumber;
if (coordinator.testSuite.durationSeconds == 0) {
// no StopCommand is sent
executeOnAllWorkersTimes--;
} else if (coordinator.testSuite.waitForTestCase) {
// has duration and waitForTestCase
waitForPhaseCompletionTimes++;
verifyExecuteOnAllWorkersWithRange = true;
}
if (!coordinator.verifyEnabled) {
// no GenericCommand for global and local verify phase are sent
executeOnFirstWorkerTimes--;
executeOnAllWorkersTimes--;
waitForPhaseCompletionTimes -= 2;
}
if (verifyExecuteOnAllWorkersWithRange) {
verify(agentsClient, atLeast((executeOnAllWorkersTimes - 1) * numberOfTests)).executeOnAllWorkers(any(Command.class));
verify(agentsClient, atMost(executeOnAllWorkersTimes * numberOfTests)).executeOnAllWorkers(any(Command.class));
} else {
verify(agentsClient, times(executeOnAllWorkersTimes * numberOfTests)).executeOnAllWorkers(any(Command.class));
}
verify(agentsClient, times(executeOnFirstWorkerTimes * numberOfTests)).executeOnFirstWorker(any(Command.class));
if (verifyExecuteOnAllWorkersWithRange) {
verify(agentsClient, atLeast(waitForPhaseCompletionTimes - 1))
.waitForPhaseCompletion(anyString(), eq("CoordinatorTest1"), any(TestPhase.class));
verify(agentsClient, atMost(waitForPhaseCompletionTimes))
.waitForPhaseCompletion(anyString(), eq("CoordinatorTest1"), any(TestPhase.class));
verify(agentsClient, atLeast(waitForPhaseCompletionTimes - 1))
.waitForPhaseCompletion(anyString(), eq("CoordinatorTest2"), any(TestPhase.class));
verify(agentsClient, atMost(waitForPhaseCompletionTimes))
.waitForPhaseCompletion(anyString(), eq("CoordinatorTest2"), any(TestPhase.class));
}
verify(agentsClient, times(1)).terminateWorkers();
}
}
| simulator/src/test/java/com/hazelcast/simulator/coordinator/CoordinatorRunTestSuiteTest.java | package com.hazelcast.simulator.coordinator;
import com.hazelcast.simulator.agent.workerjvm.WorkerJvmSettings;
import com.hazelcast.simulator.coordinator.remoting.AgentsClient;
import com.hazelcast.simulator.probes.probes.Result;
import com.hazelcast.simulator.probes.probes.impl.OperationsPerSecResult;
import com.hazelcast.simulator.test.Failure;
import com.hazelcast.simulator.test.TestCase;
import com.hazelcast.simulator.test.TestPhase;
import com.hazelcast.simulator.test.TestSuite;
import com.hazelcast.simulator.worker.commands.Command;
import com.hazelcast.simulator.worker.commands.GetBenchmarkResultsCommand;
import com.hazelcast.simulator.worker.commands.StopCommand;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import static com.hazelcast.simulator.utils.FileUtils.deleteQuiet;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anySetOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CoordinatorRunTestSuiteTest {
private static String userDir;
private final TestSuite testSuite = new TestSuite();
@Mock
private final WorkerJvmSettings workerJvmSettings = new WorkerJvmSettings();
@Mock
private final AgentsClient agentsClient = mock(AgentsClient.class);
@Mock
private final FailureMonitor failureMonitor = mock(FailureMonitor.class);
@Mock
private final PerformanceMonitor performanceMonitor = mock(PerformanceMonitor.class);
@InjectMocks
private Coordinator coordinator;
@BeforeClass
public static void setUp() throws Exception {
userDir = System.getProperty("user.dir");
System.setProperty("user.dir", "./dist/src/main/dist");
}
@AfterClass
public static void tearDown() {
System.setProperty("user.dir", userDir);
}
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
List<String> privateAddressList = new ArrayList<String>(1);
privateAddressList.add("127.0.0.1");
TestCase testCase1 = new TestCase("CoordinatorTest1");
TestCase testCase2 = new TestCase("CoordinatorTest2");
testSuite.addTest(testCase1);
testSuite.addTest(testCase2);
coordinator.testSuite = testSuite;
coordinator.cooldownSeconds = 0;
coordinator.testCaseRunnerSleepPeriod = 3;
coordinator.lastTestPhaseToSync = TestPhase.SETUP;
when(agentsClient.getPublicAddresses()).thenReturn(privateAddressList);
when(agentsClient.getAgentCount()).thenReturn(1);
when(failureMonitor.getFailureCount()).thenReturn(0);
when(performanceMonitor.getPerformanceNumbers()).thenReturn(" (PerformanceMonitor is mocked)");
}
@After
public void cleanUp() {
deleteQuiet(new File("probes-" + testSuite.id + "_CoordinatorTest1.xml"));
deleteQuiet(new File("probes-" + testSuite.id + "_CoordinatorTest2.xml"));
}
@Test
public void runTestSuiteParallel_waitForTestCase_and_duration() throws Exception {
coordinator.testSuite.waitForTestCase = true;
coordinator.testSuite.durationSeconds = 3;
coordinator.parallel = true;
coordinator.runTestSuite();
verifyAgentsClient(coordinator);
}
@Test
public void runTestSuiteParallel_waitForTestCase_noVerify() throws Exception {
coordinator.testSuite.waitForTestCase = true;
coordinator.testSuite.durationSeconds = 0;
coordinator.parallel = true;
coordinator.verifyEnabled = false;
coordinator.runTestSuite();
verifyAgentsClient(coordinator);
}
@Test
public void runTestSuiteParallel_performanceMonitorEnabled() throws Exception {
coordinator.testSuite.durationSeconds = 4;
coordinator.parallel = true;
coordinator.monitorPerformance = true;
coordinator.runTestSuite();
verifyAgentsClient(coordinator);
}
@Test
public void runTestSuiteSequential_hasCriticalFailures() throws Exception {
when(failureMonitor.hasCriticalFailure(anySetOf(Failure.Type.class))).thenReturn(true);
coordinator.testSuite.durationSeconds = 4;
coordinator.parallel = false;
coordinator.runTestSuite();
verifyAgentsClient(coordinator);
}
@Test
public void runTestSuiteSequential_probeResults() throws Exception {
Answer<List<List<Map<String, Result>>>> probeResultsAnswer = new Answer<List<List<Map<String, Result>>>>() {
@Override
@SuppressWarnings("unchecked")
public List<List<Map<String, Result>>> answer(InvocationOnMock invocation) throws Throwable {
Map<String, Result> resultMap = new HashMap<String, Result>();
resultMap.put("CoordinatorTest1", new OperationsPerSecResult(1000, 23.42f));
resultMap.put("CoordinatorTest2", new OperationsPerSecResult(2000, 42.23f));
List<Map<String, Result>> resultList = new ArrayList<Map<String, Result>>();
resultList.add(resultMap);
List<List<Map<String, Result>>> result = new ArrayList<List<Map<String, Result>>>();
result.add(resultList);
return result;
}
};
when(agentsClient.executeOnAllWorkers(isA(GetBenchmarkResultsCommand.class))).thenAnswer(probeResultsAnswer);
coordinator.testSuite.durationSeconds = 1;
coordinator.parallel = false;
coordinator.runTestSuite();
verifyAgentsClient(coordinator);
}
@Test
public void runTestSuite_getProbeResultsTimeoutException() throws Exception {
when(agentsClient.executeOnAllWorkers(isA(GetBenchmarkResultsCommand.class))).thenThrow(new TimeoutException());
coordinator.testSuite.durationSeconds = 1;
coordinator.parallel = true;
coordinator.runTestSuite();
}
@Test
public void runTestSuite_stopThreadTimeoutException() throws Exception {
when(agentsClient.executeOnAllWorkers(isA(StopCommand.class))).thenThrow(new TimeoutException());
coordinator.testSuite.durationSeconds = 1;
coordinator.parallel = true;
coordinator.runTestSuite();
}
@Test
public void runTestSuite_withException() throws Exception {
when(agentsClient.executeOnAllWorkers(any(Command.class))).thenThrow(new RuntimeException("expected"));
coordinator.runTestSuite();
}
private void verifyAgentsClient(Coordinator coordinator) throws Exception {
boolean verifyExecuteOnAllWorkersWithRange = false;
int numberOfTests = coordinator.testSuite.size();
int phaseNumber = TestPhase.values().length;
int executeOnFirstWorkerTimes = 0;
int executeOnAllWorkersTimes = 3; // InitCommand, StopCommand and GetBenchmarkResultsCommand
for (TestPhase testPhase : TestPhase.values()) {
if (testPhase.desc().startsWith("global")) {
executeOnFirstWorkerTimes++;
} else {
executeOnAllWorkersTimes++;
}
}
int waitForPhaseCompletionTimes = phaseNumber;
if (coordinator.testSuite.durationSeconds == 0) {
// no StopCommand is sent
executeOnAllWorkersTimes--;
} else if (coordinator.testSuite.waitForTestCase) {
// has duration and waitForTestCase
waitForPhaseCompletionTimes++;
verifyExecuteOnAllWorkersWithRange = true;
}
if (!coordinator.verifyEnabled) {
// no GenericCommand for global and local verify phase are sent
executeOnFirstWorkerTimes--;
executeOnAllWorkersTimes--;
waitForPhaseCompletionTimes -= 2;
}
if (verifyExecuteOnAllWorkersWithRange) {
verify(agentsClient, atLeast((executeOnAllWorkersTimes - 1) * numberOfTests)).executeOnAllWorkers(any(Command.class));
verify(agentsClient, atMost(executeOnAllWorkersTimes * numberOfTests)).executeOnAllWorkers(any(Command.class));
} else {
verify(agentsClient, times(executeOnAllWorkersTimes * numberOfTests)).executeOnAllWorkers(any(Command.class));
}
verify(agentsClient, times(executeOnFirstWorkerTimes * numberOfTests)).executeOnFirstWorker(any(Command.class));
verify(agentsClient, times(waitForPhaseCompletionTimes))
.waitForPhaseCompletion(anyString(), eq("CoordinatorTest1"), any(TestPhase.class));
verify(agentsClient, times(waitForPhaseCompletionTimes))
.waitForPhaseCompletion(anyString(), eq("CoordinatorTest2"), any(TestPhase.class));
verify(agentsClient, times(1)).terminateWorkers();
}
}
| Fixed spurious failure in CoordinatorRunTestSuiteTest.
| simulator/src/test/java/com/hazelcast/simulator/coordinator/CoordinatorRunTestSuiteTest.java | Fixed spurious failure in CoordinatorRunTestSuiteTest. |
|
Java | apache-2.0 | a9c1824bd478b43f629e6b61657f3b33e951ca63 | 0 | santhp/trade-away,santhp/trade-away,santhp/trade-away | package com.tw.tradeaway.service;
import com.tw.tradeaway.dto.OrderItemDto;
import java.util.Collection;
public interface SellerService {
Collection<OrderItemDto> getOrders(int sellerId);
}
| src/main/java/com/tw/tradeaway/service/SellerService.java | package com.tw.tradeaway.service;
import com.tw.tradeaway.dto.OrderItemDto;
import java.util.Collection;
public interface SellerService {
public Collection<OrderItemDto> getOrders(int sellerId);
}
| fix demo build failure
| src/main/java/com/tw/tradeaway/service/SellerService.java | fix demo build failure |
|
Java | apache-2.0 | 88f4357431240c9339284c158776677d34061cbf | 0 | ulfjack/bazel,twitter-forks/bazel,kchodorow/bazel,zhexuany/bazel,kchodorow/bazel,aehlig/bazel,mbrukman/bazel,perezd/bazel,dropbox/bazel,snnn/bazel,dslomov/bazel,davidzchen/bazel,spxtr/bazel,spxtr/bazel,iamthearm/bazel,mbrukman/bazel,twitter-forks/bazel,bazelbuild/bazel,zhexuany/bazel,cushon/bazel,aehlig/bazel,werkt/bazel,dropbox/bazel,hermione521/bazel,mikelikespie/bazel,LuminateWireless/bazel,juhalindfors/bazel-patches,meteorcloudy/bazel,Asana/bazel,twitter-forks/bazel,cushon/bazel,dslomov/bazel-windows,iamthearm/bazel,ulfjack/bazel,aehlig/bazel,meteorcloudy/bazel,dslomov/bazel-windows,mrdomino/bazel,juhalindfors/bazel-patches,damienmg/bazel,hermione521/bazel,werkt/bazel,juhalindfors/bazel-patches,twitter-forks/bazel,mbrukman/bazel,mikelikespie/bazel,variac/bazel,mikelikespie/bazel,akira-baruah/bazel,hermione521/bazel,bazelbuild/bazel,dropbox/bazel,ulfjack/bazel,damienmg/bazel,aehlig/bazel,Asana/bazel,variac/bazel,meteorcloudy/bazel,Asana/bazel,cushon/bazel,dslomov/bazel-windows,LuminateWireless/bazel,spxtr/bazel,perezd/bazel,perezd/bazel,cushon/bazel,meteorcloudy/bazel,perezd/bazel,mrdomino/bazel,akira-baruah/bazel,kchodorow/bazel,juhalindfors/bazel-patches,twitter-forks/bazel,bazelbuild/bazel,snnn/bazel,twitter-forks/bazel,iamthearm/bazel,kchodorow/bazel-1,katre/bazel,dslomov/bazel-windows,ButterflyNetwork/bazel,davidzchen/bazel,iamthearm/bazel,iamthearm/bazel,dslomov/bazel-windows,davidzchen/bazel,damienmg/bazel,mbrukman/bazel,juhalindfors/bazel-patches,LuminateWireless/bazel,dropbox/bazel,damienmg/bazel,Asana/bazel,dslomov/bazel,dslomov/bazel-windows,snnn/bazel,variac/bazel,katre/bazel,bazelbuild/bazel,kchodorow/bazel-1,werkt/bazel,variac/bazel,zhexuany/bazel,dslomov/bazel,LuminateWireless/bazel,kchodorow/bazel-1,mrdomino/bazel,LuminateWireless/bazel,davidzchen/bazel,aehlig/bazel,ButterflyNetwork/bazel,davidzchen/bazel,mikelikespie/bazel,dropbox/bazel,perezd/bazel,ulfjack/bazel,mrdomino/bazel,Asana/bazel,mikelikespie/bazel,davidzchen/bazel,damienmg/bazel,hermione521/bazel,bazelbuild/bazel,variac/bazel,zhexuany/bazel,werkt/bazel,aehlig/bazel,cushon/bazel,spxtr/bazel,zhexuany/bazel,akira-baruah/bazel,spxtr/bazel,akira-baruah/bazel,damienmg/bazel,ButterflyNetwork/bazel,meteorcloudy/bazel,kchodorow/bazel,kchodorow/bazel-1,kchodorow/bazel,spxtr/bazel,safarmer/bazel,kchodorow/bazel-1,kchodorow/bazel,perezd/bazel,davidzchen/bazel,ButterflyNetwork/bazel,snnn/bazel,katre/bazel,twitter-forks/bazel,katre/bazel,safarmer/bazel,cushon/bazel,juhalindfors/bazel-patches,kchodorow/bazel-1,mbrukman/bazel,iamthearm/bazel,variac/bazel,Asana/bazel,meteorcloudy/bazel,dropbox/bazel,dslomov/bazel,ulfjack/bazel,LuminateWireless/bazel,bazelbuild/bazel,ButterflyNetwork/bazel,snnn/bazel,damienmg/bazel,kchodorow/bazel,mikelikespie/bazel,dslomov/bazel,perezd/bazel,dslomov/bazel,katre/bazel,safarmer/bazel,ulfjack/bazel,safarmer/bazel,snnn/bazel,spxtr/bazel,Asana/bazel,ButterflyNetwork/bazel,mbrukman/bazel,zhexuany/bazel,katre/bazel,werkt/bazel,juhalindfors/bazel-patches,safarmer/bazel,snnn/bazel,variac/bazel,mrdomino/bazel,akira-baruah/bazel,hermione521/bazel,meteorcloudy/bazel,ulfjack/bazel,dslomov/bazel,werkt/bazel,hermione521/bazel,akira-baruah/bazel,aehlig/bazel,mrdomino/bazel,safarmer/bazel | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.java;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.devtools.build.lib.analysis.config.BuildConfiguration.StrictDepsMode.OFF;
import static com.google.devtools.build.lib.rules.java.JavaCompilationArgs.ClasspathType.BOTH;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration.StrictDepsMode;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.rules.java.JavaConfiguration.JavaClasspathMode;
import com.google.devtools.build.lib.util.Preconditions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A class to create Java compile actions in a way that is consistent with java_library. Rules that
* generate source files and emulate java_library on top of that should use this class
* instead of the lower-level API in JavaCompilationHelper.
*
* <p>Rules that want to use this class are required to have an implicit dependency on the
* Java compiler.
*/
public final class JavaLibraryHelper {
private static final String DEFAULT_SUFFIX_IS_EMPTY_STRING = "";
private final RuleContext ruleContext;
private final String implicitAttributesSuffix;
private Artifact output;
private final List<Artifact> sourceJars = new ArrayList<>();
/**
* Contains all the dependencies; these are treated as both compile-time and runtime dependencies.
*/
private final List<JavaCompilationArgsProvider> deps = new ArrayList<>();
private ImmutableList<String> javacOpts = ImmutableList.of();
private StrictDepsMode strictDepsMode = StrictDepsMode.OFF;
private JavaClasspathMode classpathMode = JavaClasspathMode.OFF;
public JavaLibraryHelper(RuleContext ruleContext) {
this(ruleContext, DEFAULT_SUFFIX_IS_EMPTY_STRING);
}
public JavaLibraryHelper(RuleContext ruleContext, String implicitAttributesSuffix) {
this.ruleContext = ruleContext;
ruleContext.getConfiguration();
this.classpathMode = ruleContext.getFragment(JavaConfiguration.class).getReduceJavaClasspath();
this.implicitAttributesSuffix = implicitAttributesSuffix;
}
/**
* Sets the final output jar; if this is not set, then the {@link #build} method throws an {@link
* IllegalStateException}. Note that this class may generate not just the output itself, but also
* a number of additional intermediate files and outputs.
*/
public JavaLibraryHelper setOutput(Artifact output) {
this.output = output;
return this;
}
/**
* Adds the given source jars. Any .java files in these jars will be compiled.
*/
public JavaLibraryHelper addSourceJars(Iterable<Artifact> sourceJars) {
Iterables.addAll(this.sourceJars, sourceJars);
return this;
}
/**
* Adds the given source jars. Any .java files in these jars will be compiled.
*/
public JavaLibraryHelper addSourceJars(Artifact... sourceJars) {
return this.addSourceJars(Arrays.asList(sourceJars));
}
public JavaLibraryHelper addDep(JavaCompilationArgsProvider provider) {
checkNotNull(provider);
this.deps.add(provider);
return this;
}
public JavaLibraryHelper addAllDeps(
Iterable<JavaCompilationArgsProvider> providers) {
Iterables.addAll(deps, providers);
return this;
}
/**
* Sets the compiler options.
*/
public JavaLibraryHelper setJavacOpts(Iterable<String> javacOpts) {
this.javacOpts = ImmutableList.copyOf(javacOpts);
return this;
}
/**
* When in strict mode, compiling the source-jars passed to this JavaLibraryHelper will break if
* they depend on classes not in any of the {@link
* JavaCompilationArgsProvider#javaCompilationArgs} passed in {@link #addDep}, even if they do
* appear in {@link JavaCompilationArgsProvider#recursiveJavaCompilationArgs}. That is, depending
* on a class requires a direct dependency on it.
*
* <p>Contrast this with the strictness-parameter to {@link #buildCompilationArgsProvider}, which
* controls whether others depending on the result of this compilation, can perform strict-deps
* checks at all.
*/
public JavaLibraryHelper setCompilationStrictDepsMode(StrictDepsMode strictDepsMode) {
this.strictDepsMode = strictDepsMode;
return this;
}
/**
* Creates the compile actions.
*/
public JavaCompilationArgs build(JavaSemantics semantics) {
Preconditions.checkState(output != null, "must have an output file; use setOutput()");
JavaTargetAttributes.Builder attributes = new JavaTargetAttributes.Builder(semantics);
attributes.addSourceJars(sourceJars);
addDepsToAttributes(attributes);
attributes.setStrictJavaDeps(strictDepsMode);
attributes.setRuleKind(ruleContext.getRule().getRuleClass());
attributes.setTargetLabel(ruleContext.getLabel());
if (isStrict() && classpathMode != JavaClasspathMode.OFF) {
JavaCompilationHelper.addDependencyArtifactsToAttributes(
attributes, deps);
}
JavaCompilationArtifacts.Builder artifactsBuilder = new JavaCompilationArtifacts.Builder();
JavaCompilationHelper helper =
new JavaCompilationHelper(
ruleContext, semantics, javacOpts, attributes, implicitAttributesSuffix);
Artifact outputDepsProto = helper.createOutputDepsProtoArtifact(output, artifactsBuilder);
helper.createCompileAction(
output,
null /* manifestProtoOutput */,
null /* gensrcOutputJar */,
outputDepsProto,
null /* outputMetadata */);
helper.createCompileTimeJarAction(output, artifactsBuilder);
artifactsBuilder.addRuntimeJar(output);
return JavaCompilationArgs.builder().merge(artifactsBuilder.build()).build();
}
/**
* Returns a JavaCompilationArgsProvider that fully encapsulates this compilation, based on the
* result of a call to build(). (that is, it contains the compile-time and runtime jars, separated
* by direct vs transitive jars).
*
* @param isReportedAsStrict if true, the result's direct JavaCompilationArgs only contain classes
* resulting from compiling the source-jars. If false, the direct JavaCompilationArgs contain
* both these classes, as well as any classes from transitive dependencies. A value of 'false'
* means this compilation cannot be checked for strict-deps, by any consumer (depending)
* compilation. Contrast this with {@link #setCompilationStrictDepsMode}.
*/
public JavaCompilationArgsProvider buildCompilationArgsProvider(
JavaCompilationArgs directArgs, boolean isReportedAsStrict) {
JavaCompilationArgs transitiveArgs =
JavaCompilationArgs.builder()
.addTransitiveArgs(directArgs, BOTH)
.addTransitiveDependencies(deps, true /* recursive */)
.build();
return new JavaCompilationArgsProvider(
isReportedAsStrict ? directArgs : transitiveArgs, transitiveArgs);
}
private void addDepsToAttributes(JavaTargetAttributes.Builder attributes) {
NestedSet<Artifact> directJars;
if (isStrict()) {
directJars = getNonRecursiveCompileTimeJarsFromDeps();
if (directJars != null) {
attributes.addDirectJars(directJars);
}
}
JavaCompilationArgs args =
JavaCompilationArgs.builder()
.addTransitiveDependencies(deps, true)
.build();
attributes.addCompileTimeClassPathEntries(args.getCompileTimeJars());
attributes.addRuntimeClassPathEntries(args.getRuntimeJars());
attributes.addInstrumentationMetadataEntries(args.getInstrumentationMetadata());
}
private NestedSet<Artifact> getNonRecursiveCompileTimeJarsFromDeps() {
JavaCompilationArgs.Builder builder = JavaCompilationArgs.builder();
builder.addTransitiveDependencies(deps, false);
return builder.build().getCompileTimeJars();
}
private boolean isStrict() {
return strictDepsMode != OFF;
}
}
| src/main/java/com/google/devtools/build/lib/rules/java/JavaLibraryHelper.java | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.java;
import static com.google.devtools.build.lib.analysis.config.BuildConfiguration.StrictDepsMode.OFF;
import static com.google.devtools.build.lib.rules.java.JavaCompilationArgs.ClasspathType.BOTH;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration.StrictDepsMode;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.rules.java.JavaConfiguration.JavaClasspathMode;
import com.google.devtools.build.lib.util.Preconditions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A class to create Java compile actions in a way that is consistent with java_library. Rules that
* generate source files and emulate java_library on top of that should use this class
* instead of the lower-level API in JavaCompilationHelper.
*
* <p>Rules that want to use this class are required to have an implicit dependency on the
* Java compiler.
*/
public final class JavaLibraryHelper {
private static final String DEFAULT_SUFFIX_IS_EMPTY_STRING = "";
private final RuleContext ruleContext;
private final String implicitAttributesSuffix;
private Artifact output;
private final List<Artifact> sourceJars = new ArrayList<>();
/**
* Contains all the dependencies; these are treated as both compile-time and runtime dependencies.
*/
private final List<JavaCompilationArgsProvider> deps = new ArrayList<>();
private ImmutableList<String> javacOpts = ImmutableList.of();
private StrictDepsMode strictDepsMode = StrictDepsMode.OFF;
private JavaClasspathMode classpathMode = JavaClasspathMode.OFF;
public JavaLibraryHelper(RuleContext ruleContext) {
this(ruleContext, DEFAULT_SUFFIX_IS_EMPTY_STRING);
}
public JavaLibraryHelper(RuleContext ruleContext, String implicitAttributesSuffix) {
this.ruleContext = ruleContext;
ruleContext.getConfiguration();
this.classpathMode = ruleContext.getFragment(JavaConfiguration.class).getReduceJavaClasspath();
this.implicitAttributesSuffix = implicitAttributesSuffix;
}
/**
* Sets the final output jar; if this is not set, then the {@link #build} method throws an {@link
* IllegalStateException}. Note that this class may generate not just the output itself, but also
* a number of additional intermediate files and outputs.
*/
public JavaLibraryHelper setOutput(Artifact output) {
this.output = output;
return this;
}
/**
* Adds the given source jars. Any .java files in these jars will be compiled.
*/
public JavaLibraryHelper addSourceJars(Iterable<Artifact> sourceJars) {
Iterables.addAll(this.sourceJars, sourceJars);
return this;
}
/**
* Adds the given source jars. Any .java files in these jars will be compiled.
*/
public JavaLibraryHelper addSourceJars(Artifact... sourceJars) {
return this.addSourceJars(Arrays.asList(sourceJars));
}
public JavaLibraryHelper addDep(JavaCompilationArgsProvider provider) {
this.deps.add(provider);
return this;
}
public JavaLibraryHelper addAllDeps(
Iterable<JavaCompilationArgsProvider> providers) {
Iterables.addAll(deps, providers);
return this;
}
/**
* Sets the compiler options.
*/
public JavaLibraryHelper setJavacOpts(Iterable<String> javacOpts) {
this.javacOpts = ImmutableList.copyOf(javacOpts);
return this;
}
/**
* When in strict mode, compiling the source-jars passed to this JavaLibraryHelper will break if
* they depend on classes not in any of the {@link
* JavaCompilationArgsProvider#javaCompilationArgs} passed in {@link #addDep}, even if they do
* appear in {@link JavaCompilationArgsProvider#recursiveJavaCompilationArgs}. That is, depending
* on a class requires a direct dependency on it.
*
* <p>Contrast this with the strictness-parameter to {@link #buildCompilationArgsProvider}, which
* controls whether others depending on the result of this compilation, can perform strict-deps
* checks at all.
*/
public JavaLibraryHelper setCompilationStrictDepsMode(StrictDepsMode strictDepsMode) {
this.strictDepsMode = strictDepsMode;
return this;
}
/**
* Creates the compile actions.
*/
public JavaCompilationArgs build(JavaSemantics semantics) {
Preconditions.checkState(output != null, "must have an output file; use setOutput()");
JavaTargetAttributes.Builder attributes = new JavaTargetAttributes.Builder(semantics);
attributes.addSourceJars(sourceJars);
addDepsToAttributes(attributes);
attributes.setStrictJavaDeps(strictDepsMode);
attributes.setRuleKind(ruleContext.getRule().getRuleClass());
attributes.setTargetLabel(ruleContext.getLabel());
if (isStrict() && classpathMode != JavaClasspathMode.OFF) {
JavaCompilationHelper.addDependencyArtifactsToAttributes(
attributes, deps);
}
JavaCompilationArtifacts.Builder artifactsBuilder = new JavaCompilationArtifacts.Builder();
JavaCompilationHelper helper =
new JavaCompilationHelper(
ruleContext, semantics, javacOpts, attributes, implicitAttributesSuffix);
Artifact outputDepsProto = helper.createOutputDepsProtoArtifact(output, artifactsBuilder);
helper.createCompileAction(
output,
null /* manifestProtoOutput */,
null /* gensrcOutputJar */,
outputDepsProto,
null /* outputMetadata */);
helper.createCompileTimeJarAction(output, artifactsBuilder);
artifactsBuilder.addRuntimeJar(output);
return JavaCompilationArgs.builder().merge(artifactsBuilder.build()).build();
}
/**
* Returns a JavaCompilationArgsProvider that fully encapsulates this compilation, based on the
* result of a call to build(). (that is, it contains the compile-time and runtime jars, separated
* by direct vs transitive jars).
*
* @param isReportedAsStrict if true, the result's direct JavaCompilationArgs only contain classes
* resulting from compiling the source-jars. If false, the direct JavaCompilationArgs contain
* both these classes, as well as any classes from transitive dependencies. A value of 'false'
* means this compilation cannot be checked for strict-deps, by any consumer (depending)
* compilation. Contrast this with {@link #setCompilationStrictDepsMode}.
*/
public JavaCompilationArgsProvider buildCompilationArgsProvider(
JavaCompilationArgs directArgs, boolean isReportedAsStrict) {
JavaCompilationArgs transitiveArgs =
JavaCompilationArgs.builder()
.addTransitiveArgs(directArgs, BOTH)
.addTransitiveDependencies(deps, true /* recursive */)
.build();
return new JavaCompilationArgsProvider(
isReportedAsStrict ? directArgs : transitiveArgs, transitiveArgs);
}
private void addDepsToAttributes(JavaTargetAttributes.Builder attributes) {
NestedSet<Artifact> directJars;
if (isStrict()) {
directJars = getNonRecursiveCompileTimeJarsFromDeps();
if (directJars != null) {
attributes.addDirectJars(directJars);
}
}
JavaCompilationArgs args =
JavaCompilationArgs.builder()
.addTransitiveDependencies(deps, true)
.build();
attributes.addCompileTimeClassPathEntries(args.getCompileTimeJars());
attributes.addRuntimeClassPathEntries(args.getRuntimeJars());
attributes.addInstrumentationMetadataEntries(args.getInstrumentationMetadata());
}
private NestedSet<Artifact> getNonRecursiveCompileTimeJarsFromDeps() {
JavaCompilationArgs.Builder builder = JavaCompilationArgs.builder();
builder.addTransitiveDependencies(deps, false);
return builder.build().getCompileTimeJars();
}
private boolean isStrict() {
return strictDepsMode != OFF;
}
}
| Check that dependencies are non-null upon insertion.
Otherwise, we'll get an NPE in build(), which doesn't help in finding the place where the null was added.
--
MOS_MIGRATED_REVID=130531765
| src/main/java/com/google/devtools/build/lib/rules/java/JavaLibraryHelper.java | Check that dependencies are non-null upon insertion. Otherwise, we'll get an NPE in build(), which doesn't help in finding the place where the null was added. |
|
Java | apache-2.0 | a9a919a608c0d906954ec86301fc7ab49320c99c | 0 | EvilMcJerkface/kudu,cloudera/kudu,InspurUSA/kudu,EvilMcJerkface/kudu,helifu/kudu,EvilMcJerkface/kudu,InspurUSA/kudu,helifu/kudu,andrwng/kudu,InspurUSA/kudu,EvilMcJerkface/kudu,cloudera/kudu,EvilMcJerkface/kudu,InspurUSA/kudu,cloudera/kudu,andrwng/kudu,cloudera/kudu,andrwng/kudu,cloudera/kudu,andrwng/kudu,helifu/kudu,cloudera/kudu,InspurUSA/kudu,cloudera/kudu,cloudera/kudu,helifu/kudu,helifu/kudu,helifu/kudu,andrwng/kudu,andrwng/kudu,EvilMcJerkface/kudu,InspurUSA/kudu,helifu/kudu,andrwng/kudu,cloudera/kudu,InspurUSA/kudu,EvilMcJerkface/kudu,EvilMcJerkface/kudu,andrwng/kudu,helifu/kudu,InspurUSA/kudu,helifu/kudu,EvilMcJerkface/kudu,andrwng/kudu,InspurUSA/kudu | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.kudu.flume.sink;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.flume.Channel;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.Sink;
import org.apache.flume.Transaction;
import org.apache.flume.channel.MemoryChannel;
import org.apache.flume.conf.Configurables;
import org.apache.flume.event.EventBuilder;
import org.apache.kudu.ColumnSchema;
import org.apache.kudu.Schema;
import org.apache.kudu.Type;
import org.apache.kudu.client.BaseKuduTest;
import org.apache.kudu.client.CreateTableOptions;
import org.apache.kudu.client.KuduTable;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class KeyedKuduEventProducerTest extends BaseKuduTest {
private static final Logger LOG = LoggerFactory.getLogger(KeyedKuduEventProducerTest.class);
private KuduTable createNewTable(String tableName) throws Exception {
LOG.info("Creating new table...");
ArrayList<ColumnSchema> columns = new ArrayList<>(2);
columns.add(new ColumnSchema.ColumnSchemaBuilder("key", Type.STRING).key(true).build());
columns.add(new ColumnSchema.ColumnSchemaBuilder("payload", Type.BINARY).key(false).build());
CreateTableOptions createOptions =
new CreateTableOptions().setRangePartitionColumns(ImmutableList.of("key"))
.setNumReplicas(1);
KuduTable table = createTable(tableName, new Schema(columns), createOptions);
LOG.info("Created new table.");
return table;
}
@Test
public void testEmptyChannelWithInsert() throws Exception {
testEvents(0, "false");
}
@Test
public void testOneEventWithInsert() throws Exception {
testEvents(1, "false");
}
@Test
public void testThreeEventsWithInsert() throws Exception {
testEvents(3, "false");
}
@Test
public void testEmptyChannelWithUpsert() throws Exception {
testEvents(0, "true");
}
@Test
public void testOneEventWithUpsert() throws Exception {
testEvents(1, "true");
}
@Test
public void testThreeEventsWithUpsert() throws Exception {
testEvents(3, "true");
}
@Test
public void testDuplicateRowsWithUpsert() throws Exception {
LOG.info("Testing events with upsert...");
KuduTable table = createNewTable("testDupUpsertEvents");
String tableName = table.getName();
Context ctx = new Context(ImmutableMap.of("producer.upsert", "true"));
KuduSink sink = createSink(tableName, ctx);
Channel channel = new MemoryChannel();
Configurables.configure(channel, new Context());
sink.setChannel(channel);
sink.start();
Transaction tx = channel.getTransaction();
tx.begin();
int numRows = 3;
for (int i = 0; i < numRows; i++) {
Event e = EventBuilder.withBody(String.format("payload body %s", i), Charsets.UTF_8);
e.setHeaders(ImmutableMap.of("key", String.format("key %s", i)));
channel.put(e);
}
tx.commit();
tx.close();
Sink.Status status = sink.process();
assertTrue("incorrect status for non-empty channel", status != Sink.Status.BACKOFF);
List<String> rows = scanTableToStrings(table);
assertEquals(numRows + " row(s) expected", numRows, rows.size());
for (int i = 0; i < numRows; i++) {
assertTrue("incorrect payload", rows.get(i).contains("payload body " + i));
}
Transaction utx = channel.getTransaction();
utx.begin();
Event dup = EventBuilder.withBody("payload body upserted".getBytes());
dup.setHeaders(ImmutableMap.of("key", String.format("key %s", 0)));
channel.put(dup);
utx.commit();
utx.close();
Sink.Status upStatus = sink.process();
assertTrue("incorrect status for non-empty channel", upStatus != Sink.Status.BACKOFF);
List<String> upRows = scanTableToStrings(table);
assertEquals(numRows + " row(s) expected", numRows, upRows.size());
assertTrue("incorrect payload", upRows.get(0).contains("payload body upserted"));
for (int i = 1; i < numRows; i++) {
assertTrue("incorrect payload", upRows.get(i).contains("payload body " + i));
}
LOG.info("Testing events with upsert finished successfully.");
}
private void testEvents(int eventCount, String upsert) throws Exception {
LOG.info("Testing {} events...", eventCount);
KuduTable table = createNewTable("test" + eventCount + "eventsUp" + upsert);
String tableName = table.getName();
Context ctx = new Context(ImmutableMap.of("producer.upsert", upsert));
KuduSink sink = createSink(tableName, ctx);
Channel channel = new MemoryChannel();
Configurables.configure(channel, new Context());
sink.setChannel(channel);
sink.start();
Transaction tx = channel.getTransaction();
tx.begin();
for (int i = 0; i < eventCount; i++) {
Event e = EventBuilder.withBody(String.format("payload body %s", i).getBytes());
e.setHeaders(ImmutableMap.of("key", String.format("key %s", i)));
channel.put(e);
}
tx.commit();
tx.close();
Sink.Status status = sink.process();
if (eventCount == 0) {
assertTrue("incorrect status for empty channel", status == Sink.Status.BACKOFF);
} else {
assertTrue("incorrect status for non-empty channel", status != Sink.Status.BACKOFF);
}
List<String> rows = scanTableToStrings(table);
assertEquals(eventCount + " row(s) expected", eventCount, rows.size());
for (int i = 0; i < eventCount; i++) {
assertTrue("incorrect payload", rows.get(i).contains("payload body " + i));
}
LOG.info("Testing {} events finished successfully.", eventCount);
}
private KuduSink createSink(String tableName, Context ctx) {
LOG.info("Creating Kudu sink for '{}' table...", tableName);
KuduSink sink = new KuduSink(syncClient);
HashMap<String, String> parameters = new HashMap<>();
parameters.put(KuduSinkConfigurationConstants.TABLE_NAME, tableName);
parameters.put(KuduSinkConfigurationConstants.MASTER_ADDRESSES, getMasterAddresses());
parameters.put(KuduSinkConfigurationConstants.PRODUCER, "org.apache.kudu.flume.sink.SimpleKeyedKuduEventProducer");
Context context = new Context(parameters);
context.putAll(ctx.getParameters());
Configurables.configure(sink, context);
LOG.info("Created Kudu sink for '{}' table.", tableName);
return sink;
}
}
| java/kudu-flume-sink/src/test/java/org/apache/kudu/flume/sink/KeyedKuduEventProducerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.kudu.flume.sink;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import org.apache.flume.Channel;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.Sink;
import org.apache.flume.Transaction;
import org.apache.flume.channel.MemoryChannel;
import org.apache.flume.conf.Configurables;
import org.apache.flume.event.EventBuilder;
import org.apache.kudu.ColumnSchema;
import org.apache.kudu.Schema;
import org.apache.kudu.Type;
import org.apache.kudu.client.BaseKuduTest;
import org.apache.kudu.client.CreateTableOptions;
import org.apache.kudu.client.KuduTable;
import org.apache.kudu.client.shaded.com.google.common.collect.ImmutableMap;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class KeyedKuduEventProducerTest extends BaseKuduTest {
private static final Logger LOG = LoggerFactory.getLogger(KeyedKuduEventProducerTest.class);
private KuduTable createNewTable(String tableName) throws Exception {
LOG.info("Creating new table...");
ArrayList<ColumnSchema> columns = new ArrayList<>(2);
columns.add(new ColumnSchema.ColumnSchemaBuilder("key", Type.STRING).key(true).build());
columns.add(new ColumnSchema.ColumnSchemaBuilder("payload", Type.BINARY).key(false).build());
CreateTableOptions createOptions =
new CreateTableOptions().setRangePartitionColumns(ImmutableList.of("key"))
.setNumReplicas(1);
KuduTable table = createTable(tableName, new Schema(columns), createOptions);
LOG.info("Created new table.");
return table;
}
@Test
public void testEmptyChannelWithInsert() throws Exception {
testEvents(0, "false");
}
@Test
public void testOneEventWithInsert() throws Exception {
testEvents(1, "false");
}
@Test
public void testThreeEventsWithInsert() throws Exception {
testEvents(3, "false");
}
@Test
public void testEmptyChannelWithUpsert() throws Exception {
testEvents(0, "true");
}
@Test
public void testOneEventWithUpsert() throws Exception {
testEvents(1, "true");
}
@Test
public void testThreeEventsWithUpsert() throws Exception {
testEvents(3, "true");
}
@Test
public void testDuplicateRowsWithUpsert() throws Exception {
LOG.info("Testing events with upsert...");
KuduTable table = createNewTable("testDupUpsertEvents");
String tableName = table.getName();
Context ctx = new Context(ImmutableMap.of("producer.upsert", "true"));
KuduSink sink = createSink(tableName, ctx);
Channel channel = new MemoryChannel();
Configurables.configure(channel, new Context());
sink.setChannel(channel);
sink.start();
Transaction tx = channel.getTransaction();
tx.begin();
int numRows = 3;
for (int i = 0; i < numRows; i++) {
Event e = EventBuilder.withBody(String.format("payload body %s", i), Charsets.UTF_8);
e.setHeaders(ImmutableMap.of("key", String.format("key %s", i)));
channel.put(e);
}
tx.commit();
tx.close();
Sink.Status status = sink.process();
assertTrue("incorrect status for non-empty channel", status != Sink.Status.BACKOFF);
List<String> rows = scanTableToStrings(table);
assertEquals(numRows + " row(s) expected", numRows, rows.size());
for (int i = 0; i < numRows; i++) {
assertTrue("incorrect payload", rows.get(i).contains("payload body " + i));
}
Transaction utx = channel.getTransaction();
utx.begin();
Event dup = EventBuilder.withBody("payload body upserted".getBytes());
dup.setHeaders(ImmutableMap.of("key", String.format("key %s", 0)));
channel.put(dup);
utx.commit();
utx.close();
Sink.Status upStatus = sink.process();
assertTrue("incorrect status for non-empty channel", upStatus != Sink.Status.BACKOFF);
List<String> upRows = scanTableToStrings(table);
assertEquals(numRows + " row(s) expected", numRows, upRows.size());
assertTrue("incorrect payload", upRows.get(0).contains("payload body upserted"));
for (int i = 1; i < numRows; i++) {
assertTrue("incorrect payload", upRows.get(i).contains("payload body " + i));
}
LOG.info("Testing events with upsert finished successfully.");
}
private void testEvents(int eventCount, String upsert) throws Exception {
LOG.info("Testing {} events...", eventCount);
KuduTable table = createNewTable("test" + eventCount + "eventsUp" + upsert);
String tableName = table.getName();
Context ctx = new Context(ImmutableMap.of("producer.upsert", upsert));
KuduSink sink = createSink(tableName, ctx);
Channel channel = new MemoryChannel();
Configurables.configure(channel, new Context());
sink.setChannel(channel);
sink.start();
Transaction tx = channel.getTransaction();
tx.begin();
for (int i = 0; i < eventCount; i++) {
Event e = EventBuilder.withBody(String.format("payload body %s", i).getBytes());
e.setHeaders(ImmutableMap.of("key", String.format("key %s", i)));
channel.put(e);
}
tx.commit();
tx.close();
Sink.Status status = sink.process();
if (eventCount == 0) {
assertTrue("incorrect status for empty channel", status == Sink.Status.BACKOFF);
} else {
assertTrue("incorrect status for non-empty channel", status != Sink.Status.BACKOFF);
}
List<String> rows = scanTableToStrings(table);
assertEquals(eventCount + " row(s) expected", eventCount, rows.size());
for (int i = 0; i < eventCount; i++) {
assertTrue("incorrect payload", rows.get(i).contains("payload body " + i));
}
LOG.info("Testing {} events finished successfully.", eventCount);
}
private KuduSink createSink(String tableName, Context ctx) {
LOG.info("Creating Kudu sink for '{}' table...", tableName);
KuduSink sink = new KuduSink(syncClient);
HashMap<String, String> parameters = new HashMap<>();
parameters.put(KuduSinkConfigurationConstants.TABLE_NAME, tableName);
parameters.put(KuduSinkConfigurationConstants.MASTER_ADDRESSES, getMasterAddresses());
parameters.put(KuduSinkConfigurationConstants.PRODUCER, "org.apache.kudu.flume.sink.SimpleKeyedKuduEventProducer");
Context context = new Context(parameters);
context.putAll(ctx.getParameters());
Configurables.configure(sink, context);
LOG.info("Created Kudu sink for '{}' table.", tableName);
return sink;
}
}
| [flume] fix import of shaded guava class
Change-Id: Id5e290446e8d67e1899d36e68d45c413fdb08cff
Reviewed-on: http://gerrit.cloudera.org:8080/3845
Reviewed-by: Adar Dembo <[email protected]>
Tested-by: Kudu Jenkins
| java/kudu-flume-sink/src/test/java/org/apache/kudu/flume/sink/KeyedKuduEventProducerTest.java | [flume] fix import of shaded guava class |
|
Java | apache-2.0 | fa099fb862de0affa6d62c636329760056c8eb60 | 0 | cherryhill/collectionspace-services,cherryhill/collectionspace-services | /**
* This document is a part of the source code and related artifacts
* for CollectionSpace, an open source collections management system
* for museums and related institutions:
* http://www.collectionspace.org
* http://wiki.collectionspace.org
* Copyright 2009 University of California at Berkeley
* Licensed under the Educational Community License (ECL), Version 2.0.
* You may not use this file except in compliance with this License.
* You may obtain a copy of the ECL 2.0 License at
* https://source.collectionspace.org/collection-space/LICENSE.txt
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.collectionspace.services.common.document;
import java.lang.reflect.Array;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.Result;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.collectionspace.services.common.ServiceMain;
import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
import org.collectionspace.services.common.context.ServiceContext;
import org.collectionspace.services.common.datetime.DateTimeFormatUtils;
import org.collectionspace.services.config.service.ObjectPartContentType;
import org.collectionspace.services.config.service.ObjectPartType;
import org.collectionspace.services.config.service.XmlContentType;
import org.dom4j.io.DOMReader;
import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
//import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
import org.mortbay.log.Log;
import org.nuxeo.ecm.core.io.ExportConstants;
import org.nuxeo.common.collections.PrimitiveArrays;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.model.Property;
import org.nuxeo.ecm.core.schema.SchemaManager;
import org.nuxeo.ecm.core.schema.TypeConstants;
import org.nuxeo.ecm.core.schema.types.ComplexType;
import org.nuxeo.ecm.core.schema.types.Field;
import org.nuxeo.ecm.core.schema.types.ListType;
import org.nuxeo.ecm.core.schema.types.Schema;
import org.nuxeo.ecm.core.schema.types.SimpleType;
import org.nuxeo.ecm.core.schema.types.Type;
import org.nuxeo.ecm.core.schema.types.TypeException;
import org.nuxeo.ecm.core.schema.types.JavaTypes;
import org.nuxeo.ecm.core.schema.types.primitives.DateType;
import org.nuxeo.ecm.core.schema.types.primitives.DoubleType;
import org.nuxeo.ecm.core.schema.types.primitives.StringType;
import org.nuxeo.ecm.core.schema.types.FieldImpl;
import org.nuxeo.ecm.core.schema.types.QName;
import org.nuxeo.runtime.api.Framework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
//import org.dom4j.Document;
//import org.dom4j.Element;
//import org.dom4j.Node;
//import org.dom4j.NodeList;
//import org.dom4j.Text;
/**
* DocumentUtils is a collection of utilities related to document management
*
* $LastChangedRevision: $ $LastChangedDate: $
*/
public class DocumentUtils {
/** The Constant logger. */
private static final Logger logger = LoggerFactory
.getLogger(DocumentUtils.class);
/** The name dateVal separator. */
private static String NAME_VALUE_SEPARATOR = "|";
// The delimiter in a schema-qualified field name,
// between its schema name and field name components.
/** The SCHEM a_ fiel d_ delimiter. */
private static String SCHEMA_FIELD_DELIMITER = ":";
// The delimiter between a parent authRef field name and
// child authRef field name, if any.
/** The AUTHRE f_ fiel d_ nam e_ delimiter. */
private static String AUTHREF_FIELD_NAME_DELIMITER = "|";
/** The XML elements with this suffix will indicate. */
private static String STRUCTURED_TYPE_SUFFIX = "List";
/**
* The Class NameValue.
*/
private static class NameValue {
/**
* Instantiates a new name dateVal.
*/
NameValue() {
// default scoped constructor to removed "synthetic accessor"
// warning
}
/** The name. */
String name;
/** The dateVal. */
String value;
};
/**
* Log multipart input.
*
* @param multipartInput
* the multipart input
*/
public static void logMultipartInput(MultipartInput multipartInput) {
if (logger.isDebugEnabled() == true) {
List<InputPart> parts = multipartInput.getParts();
for (InputPart part : parts) {
try {
logger.debug(part.getBodyAsString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* Log byte array input stream. After logging this method resets the stream
* and returns it in its original state.
*
* @param inputStream
* the input stream
* @return the byte array input stream
*/
private static ByteArrayInputStream logByteArrayInputStream(
ByteArrayInputStream inputStream) {
ByteArrayInputStream result = inputStream;
if (logger.isTraceEnabled() == true) {
ByteArrayInputStream bais = (ByteArrayInputStream) inputStream;
int length = bais.available();
byte[] buff = new byte[length];
try {
bais.read(buff);
} catch (Exception e) {
logger.debug("Could not read input stream", e);
}
String s = new String(buff);
logger.debug(s);
//
// Essentially, reset the stream and return it in its original state
//
result = new ByteArrayInputStream(buff);
}
return result;
}
/**
* Gets the xML schema.
*
* @param partMeta
* the part meta
* @return the xML schema
* @throws Exception
* the exception
*/
private static File getXMLSchema(ObjectPartType partMeta) throws Exception {
final String FILE_SEPARATOR = System.getProperty("file.separator");
final String XML_SCHEMA_EXTENSION = ".xsd";
final String SCHEMAS_DIR = "schemas";
File schemaFile = null;
//
// Look for an XML Schema (.xsd) file for the incoming part payload
//
String serverRoot = ServiceMain.getInstance().getServerRootDir();
String schemasDir = serverRoot + FILE_SEPARATOR + SCHEMAS_DIR
+ FILE_SEPARATOR;
//
// Send a warning to the log file if the XML Schema file is missing
//
String schemaName = schemasDir + partMeta.getLabel()
+ XML_SCHEMA_EXTENSION;
try {
schemaFile = new File(schemaName);
} catch (Exception e) {
if (logger.isWarnEnabled() == true) {
logger.warn("Missing schema file for incoming payload: "
+ schemaName);
}
}
return schemaFile;
}
/**
* parseProperties given payload to create XML document. this method also
* closes given stream after parsing.
*
* @param payload
* stream
* @param partMeta
* @param validate
* - whether or not to validate the payload with an XML Schema
* @return parsed Document
* @throws Exception
*/
public static Document parseDocument(InputStream payload,
ObjectPartType partMeta, Boolean validate) throws Exception {
final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
Document result = null;
// Log the incoming unprocessed payload
if (logger.isDebugEnabled() == true) {
if (payload instanceof ByteArrayInputStream) {
payload = logByteArrayInputStream((ByteArrayInputStream) payload);
}
}
File schemaFile = null;
if (validate == true) {
schemaFile = getXMLSchema(partMeta);
}
//
// Create and setup a DOMBuilder factory.
//
try {
// Create a builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
//
// Lexical Control Settings that focus on content
//
factory.setCoalescing(true);
factory.setExpandEntityReferences(true);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
//
// Enable XML validation if we found an XML Schema for the payload
//
try {
if (schemaFile != null) {
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
factory.setAttribute(JAXP_SCHEMA_SOURCE, schemaFile);
}
} catch (IllegalArgumentException e) {
String msg = "Error: JAXP DocumentBuilderFactory attribute not recognized: "
+ JAXP_SCHEMA_LANGUAGE
+ ". Check to see if parser conforms to JAXP 1.2 spec.";
if (logger.isWarnEnabled() == true) {
logger.warn(msg);
}
throw e;
}
//
// Create the builder and parse the file
//
DocumentBuilder db = factory.newDocumentBuilder();
db.setErrorHandler(null);
result = db.parse(payload);
// Write it to the log so we can see what we've created.
if (logger.isTraceEnabled() == true) {
logger.trace(xmlToString(result));
}
} finally {
if (payload != null) {
payload.close();
}
}
return result;
}
/**
* parseProperties extract given payload (XML) into Name-Value properties.
* this
*
* @param document
* to parse
* @return map key=property name, dateVal=property dateVal
* @throws Exception
*/
public static Map<String, Object> parseProperties(Node document)
throws Exception {
HashMap<String, Object> objectProps = new HashMap<String, Object>();
// Get a list of all elements in the document
Node root = document;// .getFirstChild();
NodeList rootChildren = root.getChildNodes();
for (int i = 0; i < rootChildren.getLength(); i++) {
Node node = rootChildren.item(i);
String name = node.getNodeName();
if (node.getNodeType() == Node.ELEMENT_NODE) {
NodeList nodeChildren = node.getChildNodes();
int nodeChildrenLen = nodeChildren.getLength();
Node firstChild = nodeChildren.item(0);
Object value = null;
if (firstChild != null) {
// first child node could be a whitespace char CSPACE-1026
// so, check for number of children too
if (firstChild.getNodeType() == Node.TEXT_NODE
&& nodeChildrenLen == 1) {
value = getTextNodeValue(node);
} else {
value = getMultiValues(node);
}
}
//
// Set the dateVal even if it's null.
// A null dateVal implies a clear/delete of the property
//
objectProps.put(name, value);
}
}
return objectProps;
}
/**
* getMultiStringValues retrieve multi-dateVal element values assumption:
* backend does not support more than 1 level deep hierarchy
*
* @param node
* @return
*/
private static String[] getMultiStringValues(Node node) {
ArrayList<String> vals = new ArrayList<String>();
NodeList nodeChildren = node.getChildNodes();
for (int i = 0; i < nodeChildren.getLength(); i++) {
Node child = nodeChildren.item(i);
String name = child.getNodeName();
// assumption: backend does not support more than 2 levels deep
// hierarchy
String value = null;
if (child.getNodeType() == Node.ELEMENT_NODE) {
value = getTextNodeValue(child);
vals.add(qualify(name, value));
}
}
return vals.toArray(new String[0]);
}
/**
* Removes all the immediate child text nodes.
*
* @param parent
* the parent
* @return the element
*/
private static Node removeTextNodes(Node parent) {
Node result = parent;
NodeList nodeList = parent.getChildNodes();
int nodeListSize = nodeList.getLength();
for (int i = 0; i < nodeListSize; i++) {
Node child = nodeList.item(i);
if (child != null && child.getNodeType() == Node.TEXT_NODE) {
parent.removeChild(child);
}
}
return result;
}
/**
* getMultiValues retrieve multi-dateVal element values assumption: backend
* does not support more than 1 level deep hierarchy
*
* @param node
* @return
*/
private static Object getMultiValues(Node node) throws Exception {
Object result = null;
Node nodeWithoutTextNodes = removeTextNodes(node);
NodeList children = nodeWithoutTextNodes.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node grandChild = children.item(j).getFirstChild();
// If any grandchild is non-null, return values for all
// grandchildren.
if (grandChild != null) {
if (grandChild.getNodeType() == Node.TEXT_NODE) {
result = getMultiStringValues(node);
} else {
ArrayList<Map<String, Object>> values = new ArrayList<Map<String, Object>>();
NodeList nodeChildren = node.getChildNodes();
for (int i = 0; i < nodeChildren.getLength(); i++) {
Node nodeChild = nodeChildren.item(i);
Map<String, Object> hashMap = parseProperties(nodeChild);
values.add(hashMap);
}
result = values;
}
break;
}
}
return result;
}
/**
* getTextNodeValue retrieves text node dateVal
*
* @param cnode
* @return
*/
private static String getTextNodeValue(Node cnode) {
String value = "";
Node ccnode = cnode.getFirstChild();
if (ccnode != null && ccnode.getNodeType() == Node.TEXT_NODE) {
value = ccnode.getNodeValue();
}
return value.trim();
}
/**
* isQualified check if the given dateVal is already qualified with given
* property name e.g. (in the example of a former 'otherNumber' field in
* CollectionObject) otherNumber|urn:org.collectionspace.id:24082390 is
* qualified with otherNumber but urn:org.walkerart.id:123 is not qualified
*
* @param name
* of the property, e.g. otherNumber
* @param dateVal
* of the property e.g. otherNumber
* @return
*/
private static boolean isQualified(String name, String value) {
StringTokenizer stz = new StringTokenizer(value, NAME_VALUE_SEPARATOR);
int tokens = stz.countTokens();
if (tokens == 2) {
String n = stz.nextToken();
return name.equals(n);
}
return false;
}
/**
* qualify qualifies given property dateVal with given property name, e.g.
* name=otherNumber and dateVal=urn:org.collectionspace.id:24082390 would be
* qualified as otherNumber|urn:org.collectionspace.id:24082390. however,
* name=otherNumber and
* dateVal=otherNumber|urn:org.collectionspace.id:24082390 would be ignored
* as the given dateVal is already qualified once.
*
* @param name
* @param dateVal
* @return
*/
private static String qualify(String name, String value) {
/*
* String result = null; if (isQualified(name, dateVal)) { result =
* dateVal; } else { result = name + NAME_VALUE_SEPARATOR + dateVal; }
* return result;
*/
return value;
}
/**
* buildDocument builds org.w3c.dom.Document from given properties using
* given metadata for a part
*
* @param partMeta
* @param rootElementName
* @param objectProps
* @return Document
* @throws Exception
*/
public static org.dom4j.Element buildDocument(ObjectPartType partMeta,
String rootElementName, Map<String, Object> objectProps)
throws Exception {
ObjectPartContentType partContentMeta = partMeta.getContent();
XmlContentType xc = partContentMeta.getXmlContent();
if (xc == null) {
return null;
}
// FIXME: We support XML validation on the way in, so we should add it
// here (on the way out) as well.
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document document = builder.newDocument();
document.setXmlStandalone(true); // FIXME: REM - Can we set this to
// false since it is not really
// standalone?
/*
* JAXB unmarshaller recognizes the following kind of namespace
* qualification only. More investigation is needed to use other prefix
*
* <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
* <ns2:collectionobjects-common
* xmlns:ns2="http://collectionspace.org/services/collectionobject">
* <objectNumber>objectNumber-1252960222412</objectNumber>
* <objectName>objectName-1252960222412</objectName>
* </ns2:collectionobjects-common>
*/
String ns = "ns2";
Element root = document.createElementNS(xc.getNamespaceURI(), ns + ":"
+ rootElementName);
root.setAttribute("xmlns:xsi",
"http://www.w3.org/2001/XMLSchema-instance");
// String getSchemaLocation = xc.getSchemaLocation(); //FIXME: REM - w3c
// Document to DOM4j Document mangles this attribute
// root.setAttribute("xsi:schemaLocation", xc.getSchemaLocation());
String getNamespaceURI = xc.getNamespaceURI();
root.setAttribute("xmlns:" + ns, xc.getNamespaceURI());
document.appendChild(root);
Schema schema = getSchemaFromName(partMeta.getLabel());
buildDocument(document, root, objectProps, schema);
String w3cDocumentStr = xmlToString(document);
DOMReader reader = new DOMReader();
org.dom4j.Document dom4jDoc = reader.read(document);
org.dom4j.Element result = dom4jDoc.getRootElement();
result.detach(); // return just the root element detached from the DOM
// document
return result;// FIXME: REM - Add if (logger.isTraceEnabled() == true)
// logger.trace(document.asXML());
}
/**
* Builds the document.
*
* @param document
* the document
* @param e
* the e
* @param objectProps
* the object props
* @throws Exception
* the exception
*/
public static void buildDocument(Document document, Element parent,
Map<String, Object> objectProps, Schema schema) throws Exception {
for (String prop : objectProps.keySet()) {
Object value = objectProps.get(prop);
if (value != null) {
Field field = schema.getField(prop);
// If there is no field, then we added this property to the
// properties,
// and it must be a String (e.g., CSID)
// TODO - infer the type from the type of Object, if we need
// more than String
if (field == null) {
field = new FieldImpl(new QName(prop), schema,
StringType.INSTANCE);
}
buildProperty(document, parent, field, value);
}
}
}
/*
* String-encode Nuxeo date types (DateType) as ISO8601 timestamps. If the
* value passed in is not a Nuxeo date type, use Nuxeo's "encode" method for
* the type to string-encode the value.
*/
private static String encodeValue(Type type, Object value) {
String result = null;
if (type != null && value != null) {
if (type instanceof DateType) {
Date dateResult = null;
if (value instanceof Calendar) {
dateResult = ((Calendar) value).getTime();
} else if (value instanceof Date) {
dateResult = (Date) value;
} else {
logger.error(String.format(
"Cannot encode type %s with value %s", type, value));
}
if (dateResult != null) {
result = GregorianCalendarDateTimeUtils
.formatAsISO8601Timestamp(dateResult);
}
} else {
result = type.encode(value); // If it's not of type DateType,
// use the default mechanism to
// encode the value
}
}
return result;
}
/**
* Builds the property.
*
* @param document
* the document
* @param parent
* the parent
* @param field
* the field
* @param dateVal
* the dateVal
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private static void buildProperty(Document document, Element parent,
Field field, Object value) throws IOException {
Type type = field.getType();
// no need to qualify each element name as namespace is already added
String propName = field.getName().getLocalName();
Element element = document.createElement(propName);
parent.appendChild(element);
// extract the element content
if (type.isSimpleType()) {
// Avoid returning scientific notation representations of
// very large or very small decimal values. See CSPACE-4691.
if (isNuxeoDecimalType(type) && valueMatchesNuxeoType(type, value)) {
element.setTextContent(nuxeoDecimalValueToDecimalString(value));
/*
* We need a way to produce just a Date when the specified data
* type is an xs:date vs. xs:datetime. Nuxeo maps both to a
* Calendar. Sigh. if(logger.isTraceEnabled() &&
* isDateType(type)) { String dateValType = "unknown"; if (value
* instanceof java.util.Date) { dateValType = "java.util.Date";
* } else if (value instanceof java.util.Calendar) { dateValType
* = "java.util.Calendar"; }
* logger.trace("building XML for date type: "+type.getName()
* +" value type: "+dateValType +" encoded: "+encodedVal); }
*/
} else {
String encodedVal = encodeValue(type, value); // get a String
// representation
// of the value
element.setTextContent(encodedVal);
}
} else if (type.isComplexType()) {
ComplexType ctype = (ComplexType) type;
if (ctype.getName().equals(TypeConstants.CONTENT)) {
throw new RuntimeException(
"Unexpected schema type: BLOB for field: " + propName);
} else {
buildComplex(document, element, ctype, (Map) value);
}
} else if (type.isListType()) {
if (value instanceof List) {
buildList(document, element, (ListType) type, (List) value);
} else if (value.getClass().getComponentType() != null) {
buildList(document, element, (ListType) type,
PrimitiveArrays.toList(value));
} else {
throw new IllegalArgumentException(
"A value of list type is neither list neither array: "
+ value);
}
}
}
/**
* Builds the complex.
*
* @param document
* the document
* @param element
* the element
* @param ctype
* the ctype
* @param map
* the map
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private static void buildComplex(Document document, Element element,
ComplexType ctype, Map map) throws IOException {
Iterator<Map.Entry> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
String propName = entry.getKey().toString();
buildProperty(document, element, ctype.getField(propName),
entry.getValue());
}
}
/**
* Builds the list.
*
* @param document
* the document
* @param element
* the element
* @param ltype
* the ltype
* @param list
* the list
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private static void buildList(Document document, Element element,
ListType ltype, List list) throws IOException {
Field field = ltype.getField();
for (Object obj : list) {
buildProperty(document, element, field, obj);
}
}
/**
* Returns a schema, given the name of a schema.
*
* @param schemaName
* a schema name.
* @return a schema.
*/
public static Schema getSchemaFromName(String schemaName) {
SchemaManager schemaManager = Framework
.getLocalService(SchemaManager.class);
return schemaManager.getSchema(schemaName);
}
/**
* Returns the schema part of a presumably schema-qualified field name.
*
* If the schema part is null or empty, returns an empty string.
*
* @param schemaQualifiedFieldName
* a schema-qualified field name.
* @return the schema part of the field name.
*/
// FIXME: Might instead use Nuxeo's built-in QName class.
public static String getSchemaNamePart(String schemaQualifiedFieldName) {
if (schemaQualifiedFieldName == null
|| schemaQualifiedFieldName.trim().isEmpty()) {
return "";
}
if (schemaQualifiedFieldName.indexOf(SCHEMA_FIELD_DELIMITER) > 0) {
String[] schemaQualifiedFieldNameParts = schemaQualifiedFieldName
.split(SCHEMA_FIELD_DELIMITER);
String schemaName = schemaQualifiedFieldNameParts[0];
return schemaName;
} else {
return "";
}
}
/**
* Returns a list of delimited strings, by splitting the supplied string on
* a supplied delimiter.
*
* @param str
* A string to split on a delimiter.
* @param delmiter
* A delimiter on which the string will be split into parts.
*
* @return A list of delimited strings. Returns an empty list if either the
* string or delimiter are null or empty, or if the delimiter cannot
* be found in the string.
*/
public static List<String> getDelimitedParts(String str, String delimiter) {
List<String> parts = new ArrayList<String>();
if (str == null || str.trim().isEmpty()) {
return parts;
}
if (delimiter == null || delimiter.trim().isEmpty()) {
return parts;
}
StringTokenizer stz = new StringTokenizer(str, delimiter);
while (stz.hasMoreTokens()) {
parts.add(stz.nextToken());
}
return parts;
}
/**
* Gets the ancestor auth ref field name.
*
* @param str
* the str
* @return the ancestor auth ref field name
*/
public static String getAncestorAuthRefFieldName(String str) {
List<String> parts = getDelimitedParts(str,
AUTHREF_FIELD_NAME_DELIMITER);
if (parts.size() > 0) {
return parts.get(0).trim();
} else {
return str;
}
}
/**
* Gets the descendant auth ref field name.
*
* @param str
* the str
* @return the descendant auth ref field name
*/
public static String getDescendantAuthRefFieldName(String str) {
List<String> parts = getDelimitedParts(str,
AUTHREF_FIELD_NAME_DELIMITER);
if (parts.size() > 1) {
return parts.get(1).trim();
} else {
return str;
}
}
/**
* Returns the relevant authRef field name from a fieldName, which may
* potentially be in the form of a single field name, or a delimited pair of
* field names, that in turn consists of an ancestor field name and a
* descendant field name.
*
* If a delimited pair of names is provided, will return the descendant
* field name from that pair, if present. Otherwise, will return the
* ancestor name from that pair.
*
* Will return the relevant authRef field name as schema-qualified (i.e.
* schema prefixed), if the schema name was present, either in the supplied
* simple field name or in the ancestor name in the delimited pair of names.
*
* @param fieldNameOrNames
* A field name or delimited pair of field names.
*
* @return The relevant authRef field name, as described.
*/
public static String getDescendantOrAncestor(String fieldNameOrNames) {
String fName = "";
if (fieldNameOrNames == null || fieldNameOrNames.trim().isEmpty()) {
return fName;
}
String descendantAuthRefFieldName = getDescendantAuthRefFieldName(fieldNameOrNames);
if (descendantAuthRefFieldName != null
&& !descendantAuthRefFieldName.trim().isEmpty()) {
fName = descendantAuthRefFieldName;
} else {
fName = getAncestorAuthRefFieldName(fieldNameOrNames);
}
if (getSchemaNamePart(fName).isEmpty()) {
String schemaName = getSchemaNamePart(getAncestorAuthRefFieldName(fieldNameOrNames));
if (!schemaName.trim().isEmpty()) {
fName = appendSchemaName(schemaName, fName);
}
}
return fName;
}
/**
* Returns a schema-qualified field name, given a schema name and field
* name.
*
* If the schema name is null or empty, returns the supplied field name.
*
* @param schemaName
* a schema name.
* @param fieldName
* a field name.
* @return a schema-qualified field name.
*/
public static String appendSchemaName(String schemaName, String fieldName) {
if (schemaName == null || schemaName.trim().isEmpty()) {
return fieldName;
}
return schemaName + SCHEMA_FIELD_DELIMITER + fieldName;
}
/**
* Checks if is simple type.
*
* @param prop
* the prop
* @return true, if is simple type
*/
public static boolean isSimpleType(Property prop) {
boolean isSimple = false;
if (prop == null) {
return isSimple;
}
if (prop.getType().isSimpleType()) {
isSimple = true;
}
return isSimple;
}
/**
* Checks if is list type.
*
* @param prop
* the prop
* @return true, if is list type
*/
public static boolean isListType(Property prop) {
// TODO simplify this to return (prop!=null &&
// prop.getType().isListType());
boolean isList = false;
if (prop == null) {
return isList;
}
if (prop.getType().isListType()) {
isList = true;
}
return isList;
}
/**
* Checks if is complex type.
*
* @param prop
* the prop
* @return true, if is complex type
*/
public static boolean isComplexType(Property prop) {
// TODO simplify this to return (prop!=null &&
// prop.getType().isComplexType());
boolean isComplex = false;
if (prop == null) {
return isComplex;
}
if (prop.getType().isComplexType()) {
isComplex = true;
}
return isComplex;
}
/*
* Identifies whether a property type is a Nuxeo decimal type.
*
* Note: currently, elements declared as xs:decimal in XSD schemas are
* handled as the Nuxeo primitive DoubleType. If this type correspondence
* changes, the test below should be changed accordingly.
*
* @param type a type.
*
* @return true, if is a Nuxeo decimal type; false, if it is not a Nuxeo
* decimal type.
*/
private static boolean isNuxeoDecimalType(Type type) {
return ((SimpleType) type).getPrimitiveType() instanceof DoubleType;
}
/**
* Obtains a String representation of a Nuxeo property value, where the
* latter is an opaque Object that may or may not be directly convertible to
* a string.
*
* @param obj
* an Object containing a property value
* @param docModel
* the document model associated with this property.
* @param propertyPath
* a path to the property, such as a property name, XPath, etc.
* @return a String representation of the Nuxeo property value.
*/
static public String propertyValueAsString(Object obj,
DocumentModel docModel, String propertyPath) {
if (obj == null) {
return "";
}
if (String.class.isAssignableFrom(obj.getClass())) {
return (String) obj;
} else {
// Handle cases where a property value returned from the repository
// can't be directly cast to a String.
//
// FIXME: This method provides specific, hard-coded formatting
// for String representations of property values. We might want
// to add the ability to specify these formats via configuration.
// - ADR 2013-04-26
if (obj instanceof GregorianCalendar) {
return GregorianCalendarDateTimeUtils
.formatAsISO8601Date((GregorianCalendar) obj);
} else if (obj instanceof Double) {
return nuxeoDecimalValueToDecimalString(obj);
} else if (obj instanceof Long) {
return nuxeoLongValueToString(obj);
} else if (obj instanceof Boolean) {
return String.valueOf(obj);
} else {
logger.warn("Could not convert value of property "
+ propertyPath + " in document "
+ docModel.getPathAsString() + " to a String.");
logger.warn("This may be due to a new, as-yet-unhandled datatype returned from the repository");
return "";
}
}
}
/*
* Returns a string representation of the value of a Nuxeo decimal type.
*
* Note: currently, elements declared as xs:decimal in XSD schemas are
* handled as the Nuxeo primitive DoubleType, and their values are
* convertible into the Java Double type. If this type correspondence
* changes, the conversion below should be changed accordingly, as should
* any 'instanceof' or similar checks elsewhere in this code.
*
* @return a string representation of the value of a Nuxeo decimal type. An
* empty string is returned if the value cannot be cast to the appropriate
* type.
*/
private static String nuxeoDecimalValueToDecimalString(Object value) {
Double doubleVal;
try {
doubleVal = (Double) value;
} catch (ClassCastException cce) {
logger.warn("Could not convert a Nuxeo decimal value to its string equivalent: "
+ cce.getMessage());
return "";
}
// FIXME: Without a Locale supplied as an argument, NumberFormat will
// use the decimal separator and other numeric formatting conventions
// for the current default Locale. In some Locales, this could
// potentially result in returning values that might not be capable
// of being round-tripped; this should be invetigated. Alternately,
// we might standardize on a particular locale whose values are known
// to be capable of also being ingested on return. - ADR 2012-08-07
NumberFormat formatter = NumberFormat.getInstance();
if (formatter instanceof DecimalFormat) {
// This pattern allows up to 15 decimal digits, and will prepend
// a '0' if only fractional digits are included in the value.
((DecimalFormat) formatter).applyPattern("0.###############");
}
return formatter.format(doubleVal.doubleValue());
}
/*
* Returns a string representation of the value of a Nuxeo long type.
*
* Note: currently, elements declared as xs:integer in XSD schemas are
* handled as the Nuxeo primitive LongType, and their values are convertible
* into the Java Long type. If this type correspondence changes, the
* conversion below should be changed accordingly, as should any
* 'instanceof' or similar checks elsewhere in this code.
*
* @return a string representation of the value of a Nuxeo long type. An
* empty string is returned if the value cannot be cast to the appropriate
* type.
*/
private static String nuxeoLongValueToString(Object value) {
Long longVal;
try {
longVal = (Long) value;
} catch (ClassCastException cce) {
logger.warn("Could not convert a Nuxeo integer value to its string equivalent: "
+ cce.getMessage());
return "";
}
return longVal.toString();
}
/*
* Identifies whether a property type is a date type.
*
* @param type a type.
*
* @return true, if is a date type; false, if it is not a date type.
*/
private static boolean isNuxeoDateType(Type type) {
return ((SimpleType) type).getPrimitiveType() instanceof DateType;
}
private static boolean valueMatchesNuxeoType(Type type, Object value) {
try {
return type.validate(value);
} catch (TypeException te) {
return false;
}
}
/**
* Insert multi values.
*
* @param document
* the document
* @param e
* the e
* @param vals
* the vals private static void insertMultiStringValues(Document
* document, Element e, ArrayList<String> vals) { String
* parentName = e.getNodeName();
*
* for (String o : vals) { String val = o; NameValue nv =
* unqualify(val); Element c = document.createElement(nv.name);
* e.appendChild(c); insertTextNode(document, c, nv.dateVal); } }
*/
/**
* Create a set of complex/structured elements from an array of Maps.
*
* @param document
* the document
* @param e
* the e
* @param vals
* the vals
* @throws Exception
* the exception private static void
* insertMultiHashMapValues(Document document, Element e,
* ArrayList<Map<String, Object>> vals) throws Exception {
* String parentName = e.getNodeName(); String childName = null;
* // // By convention, elements with a structured/complex type
* should have a parent element with a name ending with the
* suffix // STRUCTURED_TYPE_SUFFIX. We synthesize the element
* name for the structured type by stripping the suffix from the
* parent name. // For example, <otherNumberList><otherNumber>
* <!-- sequence of simple types -->
* <otherNumber/><otherNumberList/> // if
* (parentName.endsWith(STRUCTURED_TYPE_SUFFIX) == true) { int
* parentNameLen = parentName.length(); childName =
* parentName.substring(0, parentNameLen -
* STRUCTURED_TYPE_SUFFIX.length()); } else { String msg =
* "Unrecognized parent element name. Elements with complex/structured "
* + "types should have a parent element whose name ends with '"
* + STRUCTURED_TYPE_SUFFIX + "'."; if (logger.isErrorEnabled()
* == true) { logger.error(msg); } throw new Exception(msg); }
*
* for (Map<String, Object> map : vals) { Element newNode =
* document.createElement(childName); e.appendChild(newNode);
* buildDocument(document, newNode, map); } }
*/
/**
* Create a set of elements for an array of values. Currently, we're
* assuming the values can be only of type Map or String.
*
* @param document
* the document
* @param e
* the e
* @param vals
* the vals
* @throws Exception
* the exception private static void insertMultiValues(Document
* document, Element e, ArrayList<?> vals) throws Exception { if
* (vals != null && vals.size() > 0) { Object firstElement =
* vals.get(0); if (firstElement instanceof String) {
* insertMultiStringValues(document, e,
* (ArrayList<String>)vals); } else if (firstElement instanceof
* Map<?, ?>) { insertMultiHashMapValues(document, e,
* (ArrayList<Map<String, Object>>)vals); } else { String msg =
* "Unbounded elements need to be arrays of either Strings or Maps. We encountered an array of "
* + firstElement.getClass().getName(); if
* (logger.isErrorEnabled() == true) { logger.error(msg); }
* throw new Exception(msg); } } }
*/
/**
* Insert text node.
*
* @param document
* the document
* @param e
* the e
* @param strValue
* the str dateVal private static void insertTextNode(Document
* document, Element e, String strValue) { Text tNode =
* document.createTextNode(strValue); e.appendChild(tNode); }
*/
/**
* unqualify given dateVal. input of
* otherNumber|urn:org.collectionspace.id:24082390 would be unqualified as
* name=otherNumber and dateVal=urn:org.collectionspace.id:24082390
*
* @param input
* @return name and dateVal
* @exception IllegalStateException
* private static NameValue unqualify(String input) {
* NameValue nv = new NameValue(); StringTokenizer stz = new
* StringTokenizer(input, NAME_VALUE_SEPARATOR); int tokens =
* stz.countTokens(); if (tokens == 2) { nv.name =
* stz.nextToken(); nv.dateVal = stz.nextToken(); // Allow
* null or empty values } else if (tokens == 1) { nv.name =
* stz.nextToken(); nv.dateVal = ""; } else { throw new
* IllegalStateException
* ("Unexpected format for multi valued element: " + input);
* } return nv; }
*/
public static String getFirstString(Object list) {
if (list == null) {
return null;
}
if (list instanceof List) {
return ((List) list).size() == 0 ? null : (String) ((List) list)
.get(0);
}
Class<?> arrType = list.getClass().getComponentType();
if ((arrType != null) && arrType.isPrimitive()) {
if (arrType == Integer.TYPE) {
int[] ar = (int[]) list;
return ar.length == 0 ? null : String.valueOf(ar[0]);
} else if (arrType == Long.TYPE) {
long[] ar = (long[]) list;
return ar.length == 0 ? null : String.valueOf(ar[0]);
} else if (arrType == Double.TYPE) {
double[] ar = (double[]) list;
return ar.length == 0 ? null : String.valueOf(ar[0]);
} else if (arrType == Float.TYPE) {
float[] ar = (float[]) list;
return ar.length == 0 ? null : String.valueOf(ar[0]);
} else if (arrType == Character.TYPE) {
char[] ar = (char[]) list;
return ar.length == 0 ? null : String.valueOf(ar[0]);
} else if (arrType == Byte.TYPE) {
byte[] ar = (byte[]) list;
return ar.length == 0 ? null : String.valueOf(ar[0]);
} else if (arrType == Short.TYPE) {
short[] ar = (short[]) list;
return ar.length == 0 ? null : String.valueOf(ar[0]);
}
throw new IllegalArgumentException(
"Primitive list of unsupported type: " + list);
}
throw new IllegalArgumentException(
"A value of list type is neither list neither array: " + list);
}
/**
* writeDocument streams out given document to given output stream
*
* @param document
* @param os
* @throws Exception
*/
public static void writeDocument(Document document, OutputStream os)
throws Exception {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(os);
transformer.transform(source, result);
}
/**
* Xml to string.
*
* @param node
* the node
* @return the string
*/
public static String xmlToString(Node node) {
String result = null;
try {
Source source = new DOMSource(node);
StringWriter stringWriter = new StringWriter();
Result streamResult = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, streamResult);
result = stringWriter.getBuffer().toString();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
return result;
}
/**
* getXmlDocoument retrieve w3c.Document from given file
*
* @param fileName
* @return Document
* @throws Exception
*/
public static Document getXmlDocument(String fileName) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
File f = new File(fileName);
if (!f.exists()) {
throw new IllegalArgumentException("Test data file " + fileName
+ " not found!");
}
// Create the builder and parse the file
return factory.newDocumentBuilder().parse(f);
}
//
// Added from Nuxeo sources for creating new DocumentModel from an XML
// payload
//
/**
* Parses the properties.
*
* @param partMeta
* the part meta
* @param document
* the document
* @return the map
*/
public static Map<String, Object> parseProperties(ObjectPartType partMeta,
org.dom4j.Element document, ServiceContext ctx) throws Exception {
Map<String, Object> result = null;
String schemaName = partMeta.getLabel();
Schema schema = getSchemaFromName(schemaName);
// org.dom4j.io.DOMReader xmlReader = new org.dom4j.io.DOMReader();
// org.dom4j.Document dom4jDocument = xmlReader.read(document);
try {
// result = loadSchema(schema, dom4jDocument.getRootElement(), ctx);
result = loadSchema(schema, document, ctx);
} catch (IllegalArgumentException iae) {
throw iae;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static Map<String, Object> parseProperties(String schemaName,
org.dom4j.Element element, ServiceContext ctx) throws Exception {
Map<String, Object> result = null;
Schema schema = getSchemaFromName(schemaName);
result = DocumentUtils.loadSchema(schema, element, ctx);
return result;
}
/**
* Load schema.
*
* @param schema
* the schema
* @param schemaElement
* the schema element
* @return the map
* @throws Exception
* the exception
*/
@SuppressWarnings("unchecked")
static private Map<String, Object> loadSchema(Schema schema,
org.dom4j.Element schemaElement, ServiceContext ctx)
throws Exception {
String schemaName1 = schemaElement
.attributeValue(ExportConstants.NAME_ATTR);// FIXME: Do we need
// this local var?
String schemaName = schema.getName();
Map<String, Object> data = new HashMap<String, Object>();
Iterator<org.dom4j.Element> it = schemaElement.elementIterator();
while (it.hasNext()) {
org.dom4j.Element element = it.next();
String name = element.getName();
Field field = schema.getField(name);
if (field != null) {
Object value = getElementData(element, field.getType(), ctx);
data.put(name, value);
} else {
// FIXME: substitute an appropriate constant for "csid" below.
// One potential class to which to add that constant, if it is
// not already
// declared, might be AbstractCollectionSpaceResourceImpl - ADR
// 2012-09-24
if (!name.equals("csid")) { // 'csid' elements in input payloads
// can be safely ignored.
logger.warn("Invalid input document. No such property was found ["
+ name + "] in schema " + schemaName);
}
}
}
return data;
}
/**
* Gets the element data.
*
* @param element
* the element
* @param type
* the type
* @return the element data
*/
@SuppressWarnings("unchecked")
static private Object getElementData(org.dom4j.Element element, Type type,
ServiceContext ctx) throws Exception {
Object result = null;
String dateStr = "";
if (type.isSimpleType()) {
if (isNuxeoDateType(type)) {
String dateVal = element.getText();
if (dateVal == null || dateVal.trim().isEmpty()) {
result = type.decode("");
} else {
// Dates or date/times in any ISO 8601-based representations
// directly supported by Nuxeo will be successfully decoded.
try {
result = type.decode(dateVal);
} catch (Exception e) { // Nuxeo may not be able to decode dates like "July 11, 2001", so we'll try to convert it to ISO 8601 first
Log.debug(String.format(
"Nuxeo could not decode date string '%s'. CSpace will try to convert it to an ISO 8601 timestamp for Nuxeo first.", dateVal), e);
}
// All other date or date/time values must first converted
// to a supported ISO 8601-based representation.
if (result == null) {
dateStr = DateTimeFormatUtils.toIso8601Timestamp(dateVal, ctx.getTenantId());
if (dateStr != null) {
result = type.decode(dateStr);
} else {
throw new IllegalArgumentException(
"Unrecognized date value '" + dateVal
+ "' in field '"
+ element.getName() + "'");
}
}
}
} else {
String textValue = element.getText();
if (textValue != null && textValue.trim().isEmpty()) {
result = null;
} else {
result = type.decode(textValue);
}
}
} else if (type.isListType()) {
ListType ltype = (ListType) type;
List<Object> list = new ArrayList<Object>();
Iterator<org.dom4j.Element> it = element.elementIterator();
while (it.hasNext()) {
org.dom4j.Element el = it.next();
list.add(getElementData(el, ltype.getFieldType(), ctx));
}
Type ftype = ltype.getFieldType();
if (ftype.isSimpleType()) { // these are stored as arrays
Class klass = JavaTypes.getClass(ftype);
if (klass.isPrimitive()) {
return PrimitiveArrays.toPrimitiveArray(list, klass);
} else {
return list.toArray((Object[]) Array.newInstance(klass,
list.size()));
}
}
result = list;
} else {
ComplexType ctype = (ComplexType) type;
if (ctype.getName().equals(TypeConstants.CONTENT)) {
// String mimeType =
// element.elementText(ExportConstants.BLOB_MIME_TYPE);
// String encoding =
// element.elementText(ExportConstants.BLOB_ENCODING);
// String content =
// element.elementTextTrim(ExportConstants.BLOB_DATA);
// if ((content == null || content.length() == 0)
// && (mimeType == null || mimeType.length() == 0)) {
// return null; // remove blob
// }
// Blob blob = null;
// if (xdoc.hasExternalBlobs()) {
// blob = xdoc.getBlob(content);
// }
// if (blob == null) { // may be the blob is embedded like a
// Base64
// // encoded data
// byte[] bytes = Base64.decode(content);
// blob = new StreamingBlob(new ByteArraySource(bytes));
// }
// blob.setMimeType(mimeType);
// blob.setEncoding(encoding);
// return blob;
} else { // a complex type
Map<String, Object> map = new HashMap<String, Object>();
Iterator<org.dom4j.Element> it = element.elementIterator();
while (it.hasNext()) {
org.dom4j.Element el = it.next();
String name = el.getName();
Object value = getElementData(el,
ctype.getField(el.getName()).getType(), ctx);
map.put(name, value);
}
result = map;
}
}
return result;
}
}
| services/common/src/main/java/org/collectionspace/services/common/document/DocumentUtils.java | /**
* This document is a part of the source code and related artifacts
* for CollectionSpace, an open source collections management system
* for museums and related institutions:
* http://www.collectionspace.org
* http://wiki.collectionspace.org
* Copyright 2009 University of California at Berkeley
* Licensed under the Educational Community License (ECL), Version 2.0.
* You may not use this file except in compliance with this License.
* You may obtain a copy of the ECL 2.0 License at
* https://source.collectionspace.org/collection-space/LICENSE.txt
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.collectionspace.services.common.document;
import java.lang.reflect.Array;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.Result;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.collectionspace.services.common.ServiceMain;
import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
import org.collectionspace.services.common.context.ServiceContext;
import org.collectionspace.services.common.datetime.DateTimeFormatUtils;
import org.collectionspace.services.config.service.ObjectPartContentType;
import org.collectionspace.services.config.service.ObjectPartType;
import org.collectionspace.services.config.service.XmlContentType;
import org.dom4j.io.DOMReader;
import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
//import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
import org.nuxeo.ecm.core.io.ExportConstants;
import org.nuxeo.common.collections.PrimitiveArrays;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.model.Property;
import org.nuxeo.ecm.core.schema.SchemaManager;
import org.nuxeo.ecm.core.schema.TypeConstants;
import org.nuxeo.ecm.core.schema.types.ComplexType;
import org.nuxeo.ecm.core.schema.types.Field;
import org.nuxeo.ecm.core.schema.types.ListType;
import org.nuxeo.ecm.core.schema.types.Schema;
import org.nuxeo.ecm.core.schema.types.SimpleType;
import org.nuxeo.ecm.core.schema.types.Type;
import org.nuxeo.ecm.core.schema.types.TypeException;
import org.nuxeo.ecm.core.schema.types.JavaTypes;
import org.nuxeo.ecm.core.schema.types.primitives.DateType;
import org.nuxeo.ecm.core.schema.types.primitives.DoubleType;
import org.nuxeo.ecm.core.schema.types.primitives.StringType;
import org.nuxeo.ecm.core.schema.types.FieldImpl;
import org.nuxeo.ecm.core.schema.types.QName;
import org.nuxeo.runtime.api.Framework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
//import org.dom4j.Document;
//import org.dom4j.Element;
//import org.dom4j.Node;
//import org.dom4j.NodeList;
//import org.dom4j.Text;
/**
* DocumentUtils is a collection of utilities related to document management
*
* $LastChangedRevision: $
* $LastChangedDate: $
*/
public class DocumentUtils {
/** The Constant logger. */
private static final Logger logger =
LoggerFactory.getLogger(DocumentUtils.class);
/** The name dateVal separator. */
private static String NAME_VALUE_SEPARATOR = "|";
// The delimiter in a schema-qualified field name,
// between its schema name and field name components.
/** The SCHEM a_ fiel d_ delimiter. */
private static String SCHEMA_FIELD_DELIMITER = ":";
// The delimiter between a parent authRef field name and
// child authRef field name, if any.
/** The AUTHRE f_ fiel d_ nam e_ delimiter. */
private static String AUTHREF_FIELD_NAME_DELIMITER = "|";
/** The XML elements with this suffix will indicate. */
private static String STRUCTURED_TYPE_SUFFIX = "List";
/**
* The Class NameValue.
*/
private static class NameValue {
/**
* Instantiates a new name dateVal.
*/
NameValue() {
// default scoped constructor to removed "synthetic accessor" warning
}
/** The name. */
String name;
/** The dateVal. */
String value;
};
/**
* Log multipart input.
*
* @param multipartInput the multipart input
*/
public static void logMultipartInput(MultipartInput multipartInput) {
if (logger.isDebugEnabled() == true) {
List<InputPart> parts = multipartInput.getParts();
for (InputPart part : parts) {
try {
logger.debug(part.getBodyAsString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* Log byte array input stream. After logging this method resets the stream and returns it in its original state.
*
* @param inputStream the input stream
* @return the byte array input stream
*/
private static ByteArrayInputStream logByteArrayInputStream(ByteArrayInputStream inputStream) {
ByteArrayInputStream result = inputStream;
if (logger.isTraceEnabled() == true) {
ByteArrayInputStream bais = (ByteArrayInputStream)inputStream;
int length = bais.available();
byte [] buff = new byte[length];
try {
bais.read(buff);
} catch (Exception e) {
logger.debug("Could not read input stream", e);
}
String s = new String(buff);
logger.debug(s);
//
// Essentially, reset the stream and return it in its original state
//
result = new ByteArrayInputStream(buff);
}
return result;
}
/**
* Gets the xML schema.
*
* @param partMeta the part meta
* @return the xML schema
* @throws Exception the exception
*/
private static File getXMLSchema(ObjectPartType partMeta)
throws Exception {
final String FILE_SEPARATOR = System.getProperty("file.separator");
final String XML_SCHEMA_EXTENSION = ".xsd";
final String SCHEMAS_DIR = "schemas";
File schemaFile = null;
//
// Look for an XML Schema (.xsd) file for the incoming part payload
//
String serverRoot = ServiceMain.getInstance().getServerRootDir();
String schemasDir = serverRoot + FILE_SEPARATOR +
SCHEMAS_DIR + FILE_SEPARATOR;
//
// Send a warning to the log file if the XML Schema file is missing
//
String schemaName = schemasDir + partMeta.getLabel() + XML_SCHEMA_EXTENSION;
try {
schemaFile = new File(schemaName);
} catch (Exception e) {
if (logger.isWarnEnabled() == true) {
logger.warn("Missing schema file for incoming payload: " + schemaName);
}
}
return schemaFile;
}
/**
* parseProperties given payload to create XML document. this
* method also closes given stream after parsing.
* @param payload stream
* @param partMeta
* @param validate - whether or not to validate the payload with an XML Schema
* @return parsed Document
* @throws Exception
*/
public static Document parseDocument(InputStream payload, ObjectPartType partMeta, Boolean validate)
throws Exception {
final String JAXP_SCHEMA_SOURCE =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
final String JAXP_SCHEMA_LANGUAGE =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
final String W3C_XML_SCHEMA =
"http://www.w3.org/2001/XMLSchema";
Document result = null;
// Log the incoming unprocessed payload
if (logger.isDebugEnabled() == true) {
if (payload instanceof ByteArrayInputStream) {
payload = logByteArrayInputStream((ByteArrayInputStream)payload);
}
}
File schemaFile = null;
if (validate == true) {
schemaFile = getXMLSchema(partMeta);
}
//
// Create and setup a DOMBuilder factory.
//
try {
// Create a builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//
// Lexical Control Settings that focus on content
//
factory.setCoalescing(true);
factory.setExpandEntityReferences(true);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
//
// Enable XML validation if we found an XML Schema for the payload
//
try {
if (schemaFile != null) {
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
factory.setAttribute(JAXP_SCHEMA_SOURCE, schemaFile);
}
} catch (IllegalArgumentException e) {
String msg = "Error: JAXP DocumentBuilderFactory attribute not recognized: " +
JAXP_SCHEMA_LANGUAGE + ". Check to see if parser conforms to JAXP 1.2 spec.";
if (logger.isWarnEnabled() == true) {
logger.warn(msg);
}
throw e;
}
//
// Create the builder and parse the file
//
DocumentBuilder db = factory.newDocumentBuilder();
db.setErrorHandler(null);
result = db.parse(payload);
// Write it to the log so we can see what we've created.
if (logger.isTraceEnabled() == true) {
logger.trace(xmlToString(result));
}
} finally {
if (payload != null) {
payload.close();
}
}
return result;
}
/**
* parseProperties extract given payload (XML) into Name-Value properties. this
* @param document to parse
* @return map key=property name, dateVal=property dateVal
* @throws Exception
*/
public static Map<String, Object> parseProperties(Node document)
throws Exception {
HashMap<String, Object> objectProps = new HashMap<String, Object>();
// Get a list of all elements in the document
Node root = document;//.getFirstChild();
NodeList rootChildren = root.getChildNodes();
for (int i = 0; i < rootChildren.getLength(); i++) {
Node node = rootChildren.item(i);
String name = node.getNodeName();
if (node.getNodeType() == Node.ELEMENT_NODE) {
NodeList nodeChildren = node.getChildNodes();
int nodeChildrenLen = nodeChildren.getLength();
Node firstChild = nodeChildren.item(0);
Object value = null;
if (firstChild != null) {
//first child node could be a whitespace char CSPACE-1026
//so, check for number of children too
if (firstChild.getNodeType() == Node.TEXT_NODE
&& nodeChildrenLen == 1) {
value = getTextNodeValue(node);
} else {
value = getMultiValues(node);
}
}
//
// Set the dateVal even if it's null.
// A null dateVal implies a clear/delete of the property
//
objectProps.put(name, value);
}
}
return objectProps;
}
/**
* getMultiStringValues retrieve multi-dateVal element values
* assumption: backend does not support more than 1 level deep hierarchy
* @param node
* @return
*/
private static String[] getMultiStringValues(Node node) {
ArrayList<String> vals = new ArrayList<String>();
NodeList nodeChildren = node.getChildNodes();
for (int i = 0; i < nodeChildren.getLength(); i++) {
Node child = nodeChildren.item(i);
String name = child.getNodeName();
//assumption: backend does not support more than 2 levels deep
//hierarchy
String value = null;
if (child.getNodeType() == Node.ELEMENT_NODE) {
value = getTextNodeValue(child);
vals.add(qualify(name, value));
}
}
return vals.toArray(new String[0]);
}
/**
* Removes all the immediate child text nodes.
*
* @param parent the parent
* @return the element
*/
private static Node removeTextNodes(Node parent) {
Node result = parent;
NodeList nodeList = parent.getChildNodes();
int nodeListSize = nodeList.getLength();
for (int i = 0; i < nodeListSize; i++) {
Node child = nodeList.item(i);
if (child != null && child.getNodeType() == Node.TEXT_NODE) {
parent.removeChild(child);
}
}
return result;
}
/**
* getMultiValues retrieve multi-dateVal element values
* assumption: backend does not support more than 1 level deep hierarchy
* @param node
* @return
*/
private static Object getMultiValues(Node node) throws Exception {
Object result = null;
Node nodeWithoutTextNodes = removeTextNodes(node);
NodeList children = nodeWithoutTextNodes.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node grandChild = children.item(j).getFirstChild();
// If any grandchild is non-null, return values for all grandchildren.
if (grandChild != null) {
if (grandChild.getNodeType() == Node.TEXT_NODE) {
result = getMultiStringValues(node);
} else {
ArrayList<Map<String, Object>> values = new ArrayList<Map<String, Object>>();
NodeList nodeChildren = node.getChildNodes();
for (int i = 0; i < nodeChildren.getLength(); i++) {
Node nodeChild = nodeChildren.item(i);
Map<String, Object> hashMap = parseProperties(nodeChild);
values.add(hashMap);
}
result = values;
}
break;
}
}
return result;
}
/**
* getTextNodeValue retrieves text node dateVal
* @param cnode
* @return
*/
private static String getTextNodeValue(Node cnode) {
String value = "";
Node ccnode = cnode.getFirstChild();
if (ccnode != null && ccnode.getNodeType() == Node.TEXT_NODE) {
value = ccnode.getNodeValue();
}
return value.trim();
}
/**
* isQualified check if the given dateVal is already qualified with given
* property name e.g. (in the example of a former 'otherNumber' field in
* CollectionObject) otherNumber|urn:org.collectionspace.id:24082390 is
* qualified with otherNumber but urn:org.walkerart.id:123 is not qualified
* @param name of the property, e.g. otherNumber
* @param dateVal of the property e.g. otherNumber
* @return
*/
private static boolean isQualified(String name, String value) {
StringTokenizer stz = new StringTokenizer(value, NAME_VALUE_SEPARATOR);
int tokens = stz.countTokens();
if (tokens == 2) {
String n = stz.nextToken();
return name.equals(n);
}
return false;
}
/**
* qualify qualifies given property dateVal with given property name, e.g.
* name=otherNumber and dateVal=urn:org.collectionspace.id:24082390 would be
* qualified as otherNumber|urn:org.collectionspace.id:24082390. however,
* name=otherNumber and dateVal=otherNumber|urn:org.collectionspace.id:24082390
* would be ignored as the given dateVal is already qualified once.
* @param name
* @param dateVal
* @return
*/
private static String qualify(String name, String value) {
/*
String result = null;
if (isQualified(name, dateVal)) {
result = dateVal;
} else {
result = name + NAME_VALUE_SEPARATOR + dateVal;
}
return result;
*/
return value;
}
/**
* buildDocument builds org.w3c.dom.Document from given properties using
* given metadata for a part
* @param partMeta
* @param rootElementName
* @param objectProps
* @return Document
* @throws Exception
*/
public static org.dom4j.Element buildDocument(ObjectPartType partMeta, String rootElementName,
Map<String, Object> objectProps)
throws Exception {
ObjectPartContentType partContentMeta = partMeta.getContent();
XmlContentType xc = partContentMeta.getXmlContent();
if (xc == null) {
return null;
}
//FIXME: We support XML validation on the way in, so we should add it here (on the way out) as well.
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.newDocument();
document.setXmlStandalone(true); //FIXME: REM - Can we set this to false since it is not really standalone?
/*
* JAXB unmarshaller recognizes the following kind of namespace
* qualification only. More investigation is needed to use other prefix
*
* <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
* <ns2:collectionobjects-common xmlns:ns2="http://collectionspace.org/services/collectionobject">
* <objectNumber>objectNumber-1252960222412</objectNumber>
* <objectName>objectName-1252960222412</objectName>
* </ns2:collectionobjects-common>
*/
String ns = "ns2";
Element root = document.createElementNS(xc.getNamespaceURI(), ns + ":" + rootElementName);
root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
// String getSchemaLocation = xc.getSchemaLocation(); //FIXME: REM - w3c Document to DOM4j Document mangles this attribute
// root.setAttribute("xsi:schemaLocation", xc.getSchemaLocation());
String getNamespaceURI = xc.getNamespaceURI();
root.setAttribute("xmlns:" + ns, xc.getNamespaceURI());
document.appendChild(root);
Schema schema = getSchemaFromName(partMeta.getLabel());
buildDocument(document, root, objectProps, schema);
String w3cDocumentStr = xmlToString(document);
DOMReader reader = new DOMReader();
org.dom4j.Document dom4jDoc = reader.read(document);
org.dom4j.Element result = dom4jDoc.getRootElement();
result.detach(); //return just the root element detached from the DOM document
return result;//FIXME: REM - Add if (logger.isTraceEnabled() == true) logger.trace(document.asXML());
}
/**
* Builds the document.
*
* @param document the document
* @param e the e
* @param objectProps the object props
* @throws Exception the exception
*/
public static void buildDocument(Document document, Element parent,
Map<String, Object> objectProps, Schema schema) throws Exception {
for (String prop : objectProps.keySet()) {
Object value = objectProps.get(prop);
if (value != null) {
Field field = schema.getField(prop);
// If there is no field, then we added this property to the properties,
// and it must be a String (e.g., CSID)
// TODO - infer the type from the type of Object, if we need more than String
if(field==null) {
field = new FieldImpl(new QName(prop), schema, StringType.INSTANCE);
}
buildProperty(document, parent, field, value);
}
}
}
/*
* String-encode Nuxeo date types (DateType) as ISO8601 timestamps. If the value passed in is not a Nuxeo date type,
* use Nuxeo's "encode" method for the type to string-encode the value.
*/
private static String encodeValue(Type type, Object value) {
String result = null;
if (type != null && value != null) {
if (type instanceof DateType) {
Date dateResult = null;
if (value instanceof Calendar) {
dateResult = ((Calendar)value).getTime();
} else if (value instanceof Date) {
dateResult = (Date)value;
} else {
logger.error(String.format("Cannot encode type %s with value %s", type, value));
}
if (dateResult != null) {
result = GregorianCalendarDateTimeUtils.formatAsISO8601Timestamp(dateResult);
}
} else {
result = type.encode(value); // If it's not of type DateType, use the default mechanism to encode the value
}
}
return result;
}
/**
* Builds the property.
*
* @param document the document
* @param parent the parent
* @param field the field
* @param dateVal the dateVal
* @throws IOException Signals that an I/O exception has occurred.
*/
private static void buildProperty(Document document, Element parent,
Field field, Object value) throws IOException {
Type type = field.getType();
//no need to qualify each element name as namespace is already added
String propName = field.getName().getLocalName();
Element element = document.createElement(propName);
parent.appendChild(element);
// extract the element content
if (type.isSimpleType()) {
// Avoid returning scientific notation representations of
// very large or very small decimal values. See CSPACE-4691.
if (isNuxeoDecimalType(type) && valueMatchesNuxeoType(type, value)) {
element.setTextContent(nuxeoDecimalValueToDecimalString(value));
/*
* We need a way to produce just a Date when the specified data
* type is an xs:date vs. xs:datetime. Nuxeo maps both to a Calendar. Sigh.
if(logger.isTraceEnabled() && isDateType(type)) {
String dateValType = "unknown";
if (value instanceof java.util.Date) {
dateValType = "java.util.Date";
} else if (value instanceof java.util.Calendar) {
dateValType = "java.util.Calendar";
}
logger.trace("building XML for date type: "+type.getName()
+" value type: "+dateValType
+" encoded: "+encodedVal);
}
*/
} else {
String encodedVal = encodeValue(type, value); // get a String representation of the value
element.setTextContent(encodedVal);
}
} else if (type.isComplexType()) {
ComplexType ctype = (ComplexType) type;
if (ctype.getName().equals(TypeConstants.CONTENT)) {
throw new RuntimeException(
"Unexpected schema type: BLOB for field: "+propName);
} else {
buildComplex(document, element, ctype, (Map) value);
}
} else if (type.isListType()) {
if (value instanceof List) {
buildList(document, element, (ListType) type, (List) value);
} else if (value.getClass().getComponentType() != null) {
buildList(document, element, (ListType) type,
PrimitiveArrays.toList(value));
} else {
throw new IllegalArgumentException(
"A value of list type is neither list neither array: "
+ value);
}
}
}
/**
* Builds the complex.
*
* @param document the document
* @param element the element
* @param ctype the ctype
* @param map the map
* @throws IOException Signals that an I/O exception has occurred.
*/
private static void buildComplex(Document document, Element element,
ComplexType ctype, Map map) throws IOException {
Iterator<Map.Entry> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
String propName = entry.getKey().toString();
buildProperty(document, element,
ctype.getField(propName), entry.getValue());
}
}
/**
* Builds the list.
*
* @param document the document
* @param element the element
* @param ltype the ltype
* @param list the list
* @throws IOException Signals that an I/O exception has occurred.
*/
private static void buildList(Document document, Element element,
ListType ltype, List list) throws IOException {
Field field = ltype.getField();
for (Object obj : list) {
buildProperty(document, element, field, obj);
}
}
/**
* Returns a schema, given the name of a schema.
*
* @param schemaName a schema name.
* @return a schema.
*/
public static Schema getSchemaFromName(String schemaName) {
SchemaManager schemaManager = Framework.getLocalService(SchemaManager.class);
return schemaManager.getSchema(schemaName);
}
/**
* Returns the schema part of a presumably schema-qualified field name.
*
* If the schema part is null or empty, returns an empty string.
*
* @param schemaQualifiedFieldName a schema-qualified field name.
* @return the schema part of the field name.
*/
//FIXME: Might instead use Nuxeo's built-in QName class.
public static String getSchemaNamePart(String schemaQualifiedFieldName) {
if (schemaQualifiedFieldName == null || schemaQualifiedFieldName.trim().isEmpty()) {
return "";
}
if (schemaQualifiedFieldName.indexOf(SCHEMA_FIELD_DELIMITER) > 0) {
String[] schemaQualifiedFieldNameParts =
schemaQualifiedFieldName.split(SCHEMA_FIELD_DELIMITER);
String schemaName = schemaQualifiedFieldNameParts[0];
return schemaName;
} else {
return "";
}
}
/**
* Returns a list of delimited strings, by splitting the supplied string
* on a supplied delimiter.
*
* @param str A string to split on a delimiter.
* @param delmiter A delimiter on which the string will be split into parts.
*
* @return A list of delimited strings. Returns an empty list if either
* the string or delimiter are null or empty, or if the delimiter cannot
* be found in the string.
*/
public static List<String> getDelimitedParts(String str, String delimiter) {
List<String> parts = new ArrayList<String>();
if (str == null || str.trim().isEmpty()) {
return parts;
}
if (delimiter == null || delimiter.trim().isEmpty()) {
return parts;
}
StringTokenizer stz = new StringTokenizer(str, delimiter);
while (stz.hasMoreTokens()) {
parts.add(stz.nextToken());
}
return parts;
}
/**
* Gets the ancestor auth ref field name.
*
* @param str the str
* @return the ancestor auth ref field name
*/
public static String getAncestorAuthRefFieldName(String str) {
List<String> parts = getDelimitedParts(str, AUTHREF_FIELD_NAME_DELIMITER);
if (parts.size() > 0) {
return parts.get(0).trim();
} else {
return str;
}
}
/**
* Gets the descendant auth ref field name.
*
* @param str the str
* @return the descendant auth ref field name
*/
public static String getDescendantAuthRefFieldName(String str) {
List<String> parts = getDelimitedParts(str, AUTHREF_FIELD_NAME_DELIMITER);
if (parts.size() > 1) {
return parts.get(1).trim();
} else {
return str;
}
}
/**
* Returns the relevant authRef field name from a fieldName, which may
* potentially be in the form of a single field name, or a delimited pair
* of field names, that in turn consists of an ancestor field name and a
* descendant field name.
*
* If a delimited pair of names is provided, will return the descendant
* field name from that pair, if present. Otherwise, will return the
* ancestor name from that pair.
*
* Will return the relevant authRef field name as schema-qualified
* (i.e. schema prefixed), if the schema name was present, either in
* the supplied simple field name or in the ancestor name in the
* delimited pair of names.
*
* @param fieldNameOrNames A field name or delimited pair of field names.
*
* @return The relevant authRef field name, as described.
*/
public static String getDescendantOrAncestor(String fieldNameOrNames) {
String fName = "";
if (fieldNameOrNames == null || fieldNameOrNames.trim().isEmpty()) {
return fName;
}
String descendantAuthRefFieldName = getDescendantAuthRefFieldName(fieldNameOrNames);
if (descendantAuthRefFieldName != null && !descendantAuthRefFieldName.trim().isEmpty()) {
fName = descendantAuthRefFieldName;
} else {
fName = getAncestorAuthRefFieldName(fieldNameOrNames);
}
if (getSchemaNamePart(fName).isEmpty()) {
String schemaName = getSchemaNamePart(getAncestorAuthRefFieldName(fieldNameOrNames));
if (! schemaName.trim().isEmpty()) {
fName = appendSchemaName(schemaName, fName);
}
}
return fName;
}
/**
* Returns a schema-qualified field name, given a schema name and field name.
*
* If the schema name is null or empty, returns the supplied field name.
*
* @param schemaName a schema name.
* @param fieldName a field name.
* @return a schema-qualified field name.
*/
public static String appendSchemaName(String schemaName, String fieldName) {
if (schemaName == null || schemaName.trim().isEmpty()) {
return fieldName;
}
return schemaName + SCHEMA_FIELD_DELIMITER + fieldName;
}
/**
* Checks if is simple type.
*
* @param prop the prop
* @return true, if is simple type
*/
public static boolean isSimpleType(Property prop) {
boolean isSimple = false;
if (prop == null) {
return isSimple;
}
if (prop.getType().isSimpleType()) {
isSimple = true;
}
return isSimple;
}
/**
* Checks if is list type.
*
* @param prop the prop
* @return true, if is list type
*/
public static boolean isListType(Property prop) {
// TODO simplify this to return (prop!=null && prop.getType().isListType());
boolean isList = false;
if (prop == null) {
return isList;
}
if (prop.getType().isListType()) {
isList = true;
}
return isList;
}
/**
* Checks if is complex type.
*
* @param prop the prop
* @return true, if is complex type
*/
public static boolean isComplexType(Property prop) {
// TODO simplify this to return (prop!=null && prop.getType().isComplexType());
boolean isComplex = false;
if (prop == null) {
return isComplex;
}
if (prop.getType().isComplexType()) {
isComplex = true;
}
return isComplex;
}
/*
* Identifies whether a property type is a Nuxeo decimal type.
*
* Note: currently, elements declared as xs:decimal in XSD schemas
* are handled as the Nuxeo primitive DoubleType. If this type
* correspondence changes, the test below should be changed accordingly.
*
* @param type a type.
* @return true, if is a Nuxeo decimal type;
* false, if it is not a Nuxeo decimal type.
*/
private static boolean isNuxeoDecimalType(Type type) {
return ((SimpleType)type).getPrimitiveType() instanceof DoubleType;
}
/**
* Obtains a String representation of a Nuxeo property value, where
* the latter is an opaque Object that may or may not be directly
* convertible to a string.
*
* @param obj an Object containing a property value
* @param docModel the document model associated with this property.
* @param propertyPath a path to the property, such as a property name, XPath, etc.
* @return a String representation of the Nuxeo property value.
*/
static public String propertyValueAsString(Object obj, DocumentModel docModel, String propertyPath) {
if (obj == null) {
return "";
}
if (String.class.isAssignableFrom(obj.getClass())) {
return (String)obj;
} else {
// Handle cases where a property value returned from the repository
// can't be directly cast to a String.
//
// FIXME: This method provides specific, hard-coded formatting
// for String representations of property values. We might want
// to add the ability to specify these formats via configuration.
// - ADR 2013-04-26
if (obj instanceof GregorianCalendar) {
return GregorianCalendarDateTimeUtils.formatAsISO8601Date((GregorianCalendar)obj);
} else if (obj instanceof Double) {
return nuxeoDecimalValueToDecimalString(obj);
} else if (obj instanceof Long) {
return nuxeoLongValueToString(obj);
} else if (obj instanceof Boolean) {
return String.valueOf(obj);
} else {
logger.warn("Could not convert value of property " + propertyPath
+ " in document " + docModel.getPathAsString() + " to a String.");
logger.warn("This may be due to a new, as-yet-unhandled datatype returned from the repository");
return "";
}
}
}
/*
* Returns a string representation of the value of a Nuxeo decimal type.
*
* Note: currently, elements declared as xs:decimal in XSD schemas
* are handled as the Nuxeo primitive DoubleType, and their values are
* convertible into the Java Double type. If this type correspondence
* changes, the conversion below should be changed accordingly, as
* should any 'instanceof' or similar checks elsewhere in this code.
*
* @return a string representation of the value of a Nuxeo decimal type.
* An empty string is returned if the value cannot be cast to the
* appropriate type.
*/
private static String nuxeoDecimalValueToDecimalString(Object value) {
Double doubleVal;
try {
doubleVal = (Double) value;
} catch (ClassCastException cce) {
logger.warn("Could not convert a Nuxeo decimal value to its string equivalent: "
+ cce.getMessage());
return "";
}
// FIXME: Without a Locale supplied as an argument, NumberFormat will
// use the decimal separator and other numeric formatting conventions
// for the current default Locale. In some Locales, this could
// potentially result in returning values that might not be capable
// of being round-tripped; this should be invetigated. Alternately,
// we might standardize on a particular locale whose values are known
// to be capable of also being ingested on return. - ADR 2012-08-07
NumberFormat formatter = NumberFormat.getInstance();
if (formatter instanceof DecimalFormat) {
// This pattern allows up to 15 decimal digits, and will prepend
// a '0' if only fractional digits are included in the value.
((DecimalFormat) formatter).applyPattern("0.###############");
}
return formatter.format(doubleVal.doubleValue());
}
/*
* Returns a string representation of the value of a Nuxeo long type.
*
* Note: currently, elements declared as xs:integer in XSD schemas
* are handled as the Nuxeo primitive LongType, and their values are
* convertible into the Java Long type. If this type correspondence
* changes, the conversion below should be changed accordingly, as
* should any 'instanceof' or similar checks elsewhere in this code.
*
* @return a string representation of the value of a Nuxeo long type.
* An empty string is returned if the value cannot be cast to the
* appropriate type.
*/
private static String nuxeoLongValueToString(Object value) {
Long longVal;
try {
longVal = (Long) value;
} catch (ClassCastException cce) {
logger.warn("Could not convert a Nuxeo integer value to its string equivalent: "
+ cce.getMessage());
return "";
}
return longVal.toString();
}
/*
* Identifies whether a property type is a date type.
*
* @param type a type.
* @return true, if is a date type;
* false, if it is not a date type.
*/
private static boolean isNuxeoDateType(Type type) {
return ((SimpleType)type).getPrimitiveType() instanceof DateType;
}
private static boolean valueMatchesNuxeoType(Type type, Object value) {
try {
return type.validate(value);
} catch (TypeException te) {
return false;
}
}
/**
* Insert multi values.
*
* @param document the document
* @param e the e
* @param vals the vals
private static void insertMultiStringValues(Document document, Element e, ArrayList<String> vals) {
String parentName = e.getNodeName();
for (String o : vals) {
String val = o;
NameValue nv = unqualify(val);
Element c = document.createElement(nv.name);
e.appendChild(c);
insertTextNode(document, c, nv.dateVal);
}
}
*/
/**
* Create a set of complex/structured elements from an array of Maps.
*
* @param document the document
* @param e the e
* @param vals the vals
* @throws Exception the exception
private static void insertMultiHashMapValues(Document document, Element e, ArrayList<Map<String, Object>> vals)
throws Exception {
String parentName = e.getNodeName();
String childName = null;
//
// By convention, elements with a structured/complex type should have a parent element with a name ending with the suffix
// STRUCTURED_TYPE_SUFFIX. We synthesize the element name for the structured type by stripping the suffix from the parent name.
// For example, <otherNumberList><otherNumber> <!-- sequence of simple types --> <otherNumber/><otherNumberList/>
//
if (parentName.endsWith(STRUCTURED_TYPE_SUFFIX) == true) {
int parentNameLen = parentName.length();
childName = parentName.substring(0, parentNameLen - STRUCTURED_TYPE_SUFFIX.length());
} else {
String msg = "Unrecognized parent element name. Elements with complex/structured " +
"types should have a parent element whose name ends with '" +
STRUCTURED_TYPE_SUFFIX + "'.";
if (logger.isErrorEnabled() == true) {
logger.error(msg);
}
throw new Exception(msg);
}
for (Map<String, Object> map : vals) {
Element newNode = document.createElement(childName);
e.appendChild(newNode);
buildDocument(document, newNode, map);
}
}
*/
/**
* Create a set of elements for an array of values. Currently, we're assuming the
* values can be only of type Map or String.
*
* @param document the document
* @param e the e
* @param vals the vals
* @throws Exception the exception
private static void insertMultiValues(Document document, Element e, ArrayList<?> vals)
throws Exception {
if (vals != null && vals.size() > 0) {
Object firstElement = vals.get(0);
if (firstElement instanceof String) {
insertMultiStringValues(document, e, (ArrayList<String>)vals);
} else if (firstElement instanceof Map<?, ?>) {
insertMultiHashMapValues(document, e, (ArrayList<Map<String, Object>>)vals);
} else {
String msg = "Unbounded elements need to be arrays of either Strings or Maps. We encountered an array of " +
firstElement.getClass().getName();
if (logger.isErrorEnabled() == true) {
logger.error(msg);
}
throw new Exception(msg);
}
}
}
*/
/**
* Insert text node.
*
* @param document the document
* @param e the e
* @param strValue the str dateVal
private static void insertTextNode(Document document, Element e, String strValue) {
Text tNode = document.createTextNode(strValue);
e.appendChild(tNode);
}
*/
/**
* unqualify given dateVal.
* input of otherNumber|urn:org.collectionspace.id:24082390 would be unqualified
* as name=otherNumber and dateVal=urn:org.collectionspace.id:24082390
* @param input
* @return name and dateVal
* @exception IllegalStateException
private static NameValue unqualify(String input) {
NameValue nv = new NameValue();
StringTokenizer stz = new StringTokenizer(input, NAME_VALUE_SEPARATOR);
int tokens = stz.countTokens();
if (tokens == 2) {
nv.name = stz.nextToken();
nv.dateVal = stz.nextToken();
// Allow null or empty values
} else if (tokens == 1) {
nv.name = stz.nextToken();
nv.dateVal = "";
} else {
throw new IllegalStateException("Unexpected format for multi valued element: " + input);
}
return nv;
}
*/
public static String getFirstString(Object list) {
if (list==null) {
return null;
}
if (list instanceof List) {
return ((List)list).size()==0?null:(String)((List)list).get(0);
}
Class<?> arrType = list.getClass().getComponentType();
if ((arrType != null) && arrType.isPrimitive()) {
if (arrType == Integer.TYPE) {
int[] ar = (int[]) list;
return ar.length==0?null:String.valueOf(ar[0]);
} else if (arrType == Long.TYPE) {
long[] ar = (long[]) list;
return ar.length==0?null:String.valueOf(ar[0]);
} else if (arrType == Double.TYPE) {
double[] ar = (double[]) list;
return ar.length==0?null:String.valueOf(ar[0]);
} else if (arrType == Float.TYPE) {
float[] ar = (float[]) list;
return ar.length==0?null:String.valueOf(ar[0]);
} else if (arrType == Character.TYPE) {
char[] ar = (char[]) list;
return ar.length==0?null:String.valueOf(ar[0]);
} else if (arrType == Byte.TYPE) {
byte[] ar = (byte[]) list;
return ar.length==0?null:String.valueOf(ar[0]);
} else if (arrType == Short.TYPE) {
short[] ar = (short[]) list;
return ar.length==0?null:String.valueOf(ar[0]);
}
throw new IllegalArgumentException(
"Primitive list of unsupported type: "
+ list);
}
throw new IllegalArgumentException(
"A value of list type is neither list neither array: "
+ list);
}
/**
* writeDocument streams out given document to given output stream
* @param document
* @param os
* @throws Exception
*/
public static void writeDocument(Document document, OutputStream os) throws Exception {
TransformerFactory tFactory =
TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(os);
transformer.transform(source, result);
}
/**
* Xml to string.
*
* @param node the node
* @return the string
*/
public static String xmlToString(Node node) {
String result = null;
try {
Source source = new DOMSource(node);
StringWriter stringWriter = new StringWriter();
Result streamResult = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, streamResult);
result = stringWriter.getBuffer().toString();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
return result;
}
/**
* getXmlDocoument retrieve w3c.Document from given file
* @param fileName
* @return Document
* @throws Exception
*/
public static Document getXmlDocument(String fileName) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
File f = new File(fileName);
if (!f.exists()) {
throw new IllegalArgumentException("Test data file " + fileName + " not found!");
}
// Create the builder and parse the file
return factory.newDocumentBuilder().parse(f);
}
//
// Added from Nuxeo sources for creating new DocumentModel from an XML payload
//
/**
* Parses the properties.
*
* @param partMeta the part meta
* @param document the document
* @return the map
*/
public static Map<String, Object> parseProperties(ObjectPartType partMeta,
org.dom4j.Element document, ServiceContext ctx) throws Exception {
Map<String, Object> result = null;
String schemaName = partMeta.getLabel();
Schema schema = getSchemaFromName(schemaName);
// org.dom4j.io.DOMReader xmlReader = new org.dom4j.io.DOMReader();
// org.dom4j.Document dom4jDocument = xmlReader.read(document);
try {
// result = loadSchema(schema, dom4jDocument.getRootElement(), ctx);
result = loadSchema(schema, document, ctx);
} catch (IllegalArgumentException iae) {
throw iae;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static Map<String, Object> parseProperties(String schemaName, org.dom4j.Element element, ServiceContext ctx) throws Exception {
Map<String, Object> result = null;
Schema schema = getSchemaFromName(schemaName);
result = DocumentUtils.loadSchema(schema, element, ctx);
return result;
}
/**
* Load schema.
*
* @param schema the schema
* @param schemaElement the schema element
* @return the map
* @throws Exception the exception
*/
@SuppressWarnings("unchecked")
static private Map<String, Object> loadSchema(Schema schema, org.dom4j.Element schemaElement, ServiceContext ctx)
throws Exception {
String schemaName1 = schemaElement.attributeValue(ExportConstants.NAME_ATTR);//FIXME: Do we need this local var?
String schemaName = schema.getName();
Map<String, Object> data = new HashMap<String, Object>();
Iterator<org.dom4j.Element> it = schemaElement.elementIterator();
while (it.hasNext()) {
org.dom4j.Element element = it.next();
String name = element.getName();
Field field = schema.getField(name);
if (field != null) {
Object value = getElementData(element, field.getType(), ctx);
data.put(name, value);
} else {
// FIXME: substitute an appropriate constant for "csid" below.
// One potential class to which to add that constant, if it is not already
// declared, might be AbstractCollectionSpaceResourceImpl - ADR 2012-09-24
if (! name.equals("csid")) { // 'csid' elements in input payloads can be safely ignored.
logger.warn("Invalid input document. No such property was found [" +
name + "] in schema " + schemaName);
}
}
}
return data;
}
/**
* Gets the element data.
*
* @param element the element
* @param type the type
* @return the element data
*/
@SuppressWarnings("unchecked")
static private Object getElementData(org.dom4j.Element element, Type type,
ServiceContext ctx) throws Exception {
Object result = null;
String dateStr = "";
if (type.isSimpleType()) {
if (isNuxeoDateType(type)) {
String dateVal = element.getText();
if (dateVal == null || dateVal.trim().isEmpty()) {
result = type.decode("");
} else {
// Dates or date/times in any ISO 8601-based representations
// directly supported by Nuxeo will be successfully decoded.
result = type.decode(dateVal);
// All other date or date/time values must first be converted
// to a supported ISO 8601-based representation.
if (result == null) {
dateStr = DateTimeFormatUtils.toIso8601Timestamp(dateVal,
ctx.getTenantId());
if (dateStr != null) {
result = type.decode(dateStr);
} else {
throw new IllegalArgumentException("Unrecognized date value '"
+ dateVal + "' in field '" + element.getName() + "'");
}
}
}
} else {
String textValue = element.getText();
if (textValue != null && textValue.trim().isEmpty()) {
result = null;
} else {
result = type.decode(textValue);
}
}
} else if (type.isListType()) {
ListType ltype = (ListType) type;
List<Object> list = new ArrayList<Object>();
Iterator<org.dom4j.Element> it = element.elementIterator();
while (it.hasNext()) {
org.dom4j.Element el = it.next();
list.add(getElementData(el, ltype.getFieldType(), ctx));
}
Type ftype = ltype.getFieldType();
if (ftype.isSimpleType()) { // these are stored as arrays
Class klass = JavaTypes.getClass(ftype);
if (klass.isPrimitive()) {
return PrimitiveArrays.toPrimitiveArray(list, klass);
} else {
return list.toArray((Object[])Array.newInstance(klass, list.size()));
}
}
result = list;
} else {
ComplexType ctype = (ComplexType) type;
if (ctype.getName().equals(TypeConstants.CONTENT)) {
// String mimeType = element.elementText(ExportConstants.BLOB_MIME_TYPE);
// String encoding = element.elementText(ExportConstants.BLOB_ENCODING);
// String content = element.elementTextTrim(ExportConstants.BLOB_DATA);
// if ((content == null || content.length() == 0)
// && (mimeType == null || mimeType.length() == 0)) {
// return null; // remove blob
// }
// Blob blob = null;
// if (xdoc.hasExternalBlobs()) {
// blob = xdoc.getBlob(content);
// }
// if (blob == null) { // may be the blob is embedded like a Base64
// // encoded data
// byte[] bytes = Base64.decode(content);
// blob = new StreamingBlob(new ByteArraySource(bytes));
// }
// blob.setMimeType(mimeType);
// blob.setEncoding(encoding);
// return blob;
} else { // a complex type
Map<String, Object> map = new HashMap<String, Object>();
Iterator<org.dom4j.Element> it = element.elementIterator();
while (it.hasNext()) {
org.dom4j.Element el = it.next();
String name = el.getName();
Object value = getElementData(el, ctype.getField(
el.getName()).getType(), ctx);
map.put(name, value);
}
result = map;
}
}
return result;
}
}
| CSPACE-6375: Fixed another date processing/encoding issue.
| services/common/src/main/java/org/collectionspace/services/common/document/DocumentUtils.java | CSPACE-6375: Fixed another date processing/encoding issue. |
|
Java | apache-2.0 | 5942c100e8ef583df35a0873d86fe838d04f9f51 | 0 | MichaelRocks/lightsaber,MichaelRocks/lightsaber | /*
* Copyright 2015 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.annotations;
import org.apache.commons.lang3.Validate;
import org.objectweb.asm.Type;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class AnnotationDataBuilder {
private final Type annotationType;
private final Map<String, Object> values = new HashMap<>();
private boolean isResolved = false;
public AnnotationDataBuilder(final Type annotationType) {
this.annotationType = annotationType;
}
public AnnotationDataBuilder addDefaultValue(final Object defaultValue) {
return addDefaultValue("value", defaultValue);
}
public AnnotationDataBuilder addDefaultValue(final String name, final Object defaultValue) {
Validate.notNull(name);
Validate.notNull(defaultValue);
values.put(name, defaultValue);
return this;
}
public AnnotationDataBuilder setResolved(final boolean resolved) {
isResolved = resolved;
return this;
}
public AnnotationData build() {
return new AnnotationData(annotationType, Collections.unmodifiableMap(values), isResolved);
}
}
| processor/src/main/java/io/michaelrocks/lightsaber/processor/annotations/AnnotationDataBuilder.java | /*
* Copyright 2015 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.annotations;
import org.apache.commons.lang3.Validate;
import org.objectweb.asm.Type;
import java.util.HashMap;
import java.util.Map;
public class AnnotationDataBuilder {
private final Type annotationType;
private final Map<String, Object> values = new HashMap<>();
private boolean isResolved = false;
public AnnotationDataBuilder(final Type annotationType) {
this.annotationType = annotationType;
}
public AnnotationDataBuilder addDefaultValue(final Object defaultValue) {
return addDefaultValue("value", defaultValue);
}
public AnnotationDataBuilder addDefaultValue(final String name, final Object defaultValue) {
Validate.notNull(name);
Validate.notNull(defaultValue);
values.put(name, defaultValue);
return this;
}
public AnnotationDataBuilder setResolved(final boolean resolved) {
isResolved = resolved;
return this;
}
public AnnotationData build() {
return new AnnotationData(annotationType, values, isResolved);
}
}
| Create AnnotationData with unmodifiable map
| processor/src/main/java/io/michaelrocks/lightsaber/processor/annotations/AnnotationDataBuilder.java | Create AnnotationData with unmodifiable map |
|
Java | apache-2.0 | 27be8d6dc3afc99129fb20c27369541a36b1b2cb | 0 | wendal/nutz-book-project,wendal/nutz-book-project,sunhai1988/nutz-book-project,wendal/nutz-book-project,sunhai1988/nutz-book-project,sunhai1988/nutz-book-project,sunhai1988/nutz-book-project,wendal/nutz-book-project | package net.wendal.nutzbook.module.yvr;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import net.wendal.nutzbook.bean.yvr.Topic;
import net.wendal.nutzbook.module.BaseModule;
import net.wendal.nutzbook.util.Markdowns;
import net.wendal.nutzbook.util.Toolkit;
import org.apache.commons.lang.StringEscapeUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Each;
import org.nutz.lang.Files;
import org.nutz.lang.Streams;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;
import com.redfin.sitemapgenerator.WebSitemapGenerator;
import com.redfin.sitemapgenerator.WebSitemapUrl;
import com.redfin.sitemapgenerator.WebSitemapUrl.Options;
import com.rometools.rome.feed.synd.SyndContent;
import com.rometools.rome.feed.synd.SyndContentImpl;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndEntryImpl;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.feed.synd.SyndFeedImpl;
import com.rometools.rome.io.FeedException;
import com.rometools.rome.io.SyndFeedOutput;
/**
* 负责输出rss和sitemap的模块
* @author wendal
*
*/
@IocBean(create="init")
@At("/yvr")
@Fail("http:500")
public class YvrSeoModule extends BaseModule {
@Inject("refer:conf")
PropertiesProxy conf;
/**
* 全文输出
*/
@At
@Ok("raw:xml")
public String rss() throws IOException, FeedException {
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_2.0");
String urlbase = websiteUrlBase;
feed.setLink(urlbase);
feed.setTitle(conf.get("website.title", "Nutz社区"));
feed.setDescription(conf.get("website.description", "一个有爱的社区"));
feed.setAuthor(conf.get("website.author", "wendal"));
feed.setEncoding("UTF-8");
feed.setLanguage("zh-cn");
List<SyndEntry> entries = new ArrayList<SyndEntry>();
SyndEntry entry;
SyndContent description;
List<Topic> list = dao.query(Topic.class, Cnd.orderBy().desc("createTime"), dao.createPager(1, 10));
for (Topic topic: list) {
dao.fetchLinks(topic, "author");
entry = new SyndEntryImpl();
entry.setTitle(StringEscapeUtils.unescapeHtml(topic.getTitle()));
entry.setLink(urlbase + "/yvr/t/" + topic.getId());
entry.setPublishedDate(topic.getCreateTime());
description = new SyndContentImpl();
description.setType("text/html");
description.setValue(Markdowns.toHtml(topic.getContent(), urlbase));
entry.setDescription(description);
entry.setAuthor(topic.getAuthor().getLoginname());
entries.add(entry);
}
feed.setEntries(entries);
if (list.size() > 0) {
feed.setPublishedDate(list.get(0).getCreateTime());
}
SyndFeedOutput output = new SyndFeedOutput();
return output.outputString(feed, true);
}
/**
* 输出Sitemap
*/
@At
@Ok("raw:xml")
public File sitemap() throws MalformedURLException, ParseException{
String tmpdir = conf.get("website.tmp_dir", "/tmp");
Files.createDirIfNoExists(tmpdir);
final WebSitemapGenerator gen = new WebSitemapGenerator(urlbase, new File(tmpdir));
gen.addUrl(urlbase + "/yvr/list");
dao.each(Topic.class, Cnd.orderBy().desc("createTime"), dao.createPager(1, 1000), new Each<Topic>() {
public void invoke(int index, Topic topic, int length) {
try {
Options options = new Options(urlbase + "/yvr/t/" + topic.getId());
// TODO 从redis读取最后更新时间
//options.lastMod(topic.getCreateAt());
WebSitemapUrl url = new WebSitemapUrl(options);
gen.addUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
}
});
List<File> list = gen.write();
if (list.size() > 0)
return list.get(0);
return null;
}
/**
* 根据Markdown生成文档
*/
@At({"/links/?"})
@Ok("beetl:/yvr/website/links.btl")
public Object page(String type) throws IOException {
String path = "/doc/" + type + ".md";
InputStream ins = getClass().getClassLoader().getResourceAsStream(path);
if (ins == null)
return HTTP_404;
String cnt = Streams.readAndClose(new InputStreamReader(ins));
String[] tmp = cnt.split("\n", 2);
String title = tmp[0].trim().split(" ", 2)[1].trim();
return _map("title", title, "cnt", cnt, "current_user", fetch_userprofile(Toolkit.uid()));
}
}
| src/main/java/net/wendal/nutzbook/module/yvr/YvrSeoModule.java | package net.wendal.nutzbook.module.yvr;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import net.wendal.nutzbook.bean.yvr.Topic;
import net.wendal.nutzbook.module.BaseModule;
import net.wendal.nutzbook.util.Markdowns;
import org.apache.commons.lang.StringEscapeUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Each;
import org.nutz.lang.Files;
import org.nutz.lang.Streams;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;
import com.redfin.sitemapgenerator.WebSitemapGenerator;
import com.redfin.sitemapgenerator.WebSitemapUrl;
import com.redfin.sitemapgenerator.WebSitemapUrl.Options;
import com.rometools.rome.feed.synd.SyndContent;
import com.rometools.rome.feed.synd.SyndContentImpl;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndEntryImpl;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.feed.synd.SyndFeedImpl;
import com.rometools.rome.io.FeedException;
import com.rometools.rome.io.SyndFeedOutput;
/**
* 负责输出rss和sitemap的模块
* @author wendal
*
*/
@IocBean(create="init")
@At("/yvr")
@Fail("http:500")
public class YvrSeoModule extends BaseModule {
@Inject("refer:conf")
PropertiesProxy conf;
/**
* 全文输出
*/
@At
@Ok("raw:xml")
public String rss() throws IOException, FeedException {
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_2.0");
String urlbase = websiteUrlBase;
feed.setLink(urlbase);
feed.setTitle(conf.get("website.title", "Nutz社区"));
feed.setDescription(conf.get("website.description", "一个有爱的社区"));
feed.setAuthor(conf.get("website.author", "wendal"));
feed.setEncoding("UTF-8");
feed.setLanguage("zh-cn");
List<SyndEntry> entries = new ArrayList<SyndEntry>();
SyndEntry entry;
SyndContent description;
List<Topic> list = dao.query(Topic.class, Cnd.orderBy().desc("createTime"), dao.createPager(1, 10));
for (Topic topic: list) {
dao.fetchLinks(topic, "author");
entry = new SyndEntryImpl();
entry.setTitle(StringEscapeUtils.unescapeHtml(topic.getTitle()));
entry.setLink(urlbase + "/yvr/t/" + topic.getId());
entry.setPublishedDate(topic.getCreateTime());
description = new SyndContentImpl();
description.setType("text/html");
description.setValue(Markdowns.toHtml(topic.getContent(), urlbase));
entry.setDescription(description);
entry.setAuthor(topic.getAuthor().getLoginname());
entries.add(entry);
}
feed.setEntries(entries);
if (list.size() > 0) {
feed.setPublishedDate(list.get(0).getCreateTime());
}
SyndFeedOutput output = new SyndFeedOutput();
return output.outputString(feed, true);
}
/**
* 输出Sitemap
*/
@At
@Ok("raw:xml")
public File sitemap() throws MalformedURLException, ParseException{
String tmpdir = conf.get("website.tmp_dir", "/tmp");
Files.createDirIfNoExists(tmpdir);
final WebSitemapGenerator gen = new WebSitemapGenerator(urlbase, new File(tmpdir));
gen.addUrl(urlbase + "/yvr/list");
dao.each(Topic.class, Cnd.orderBy().desc("createTime"), dao.createPager(1, 1000), new Each<Topic>() {
public void invoke(int index, Topic topic, int length) {
try {
Options options = new Options(urlbase + "/yvr/t/" + topic.getId());
// TODO 从redis读取最后更新时间
//options.lastMod(topic.getCreateAt());
WebSitemapUrl url = new WebSitemapUrl(options);
gen.addUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
}
});
List<File> list = gen.write();
if (list.size() > 0)
return list.get(0);
return null;
}
/**
* 根据Markdown生成文档
*/
@At({"/links/?"})
@Ok("beetl:/yvr/website/links.btl")
public Object page(String type) throws IOException {
String path = "/doc/" + type + ".md";
InputStream ins = getClass().getClassLoader().getResourceAsStream(path);
if (ins == null)
return HTTP_404;
String cnt = Streams.readAndClose(new InputStreamReader(ins));
String[] tmp = cnt.split("\n", 2);
String title = tmp[0].trim().split(" ", 2)[1].trim();
return _map("title", title, "cnt", cnt);
}
}
| update: 文档页也需要用户信息.
Signed-off-by: wendal chen <[email protected]>
| src/main/java/net/wendal/nutzbook/module/yvr/YvrSeoModule.java | update: 文档页也需要用户信息. |
|
Java | apache-2.0 | 1f171661a33b04571499924d01480760d5650399 | 0 | aredee/accumulo-mesos,aredee/accumulo-mesos,aredee/accumulo-mesos,aredee/accumulo-mesos | package aredee.mesos.frameworks.accumulo.scheduler;
import aredee.mesos.frameworks.accumulo.scheduler.launcher.AccumuloStartExecutorLauncher;
import aredee.mesos.frameworks.accumulo.scheduler.launcher.Launcher;
import aredee.mesos.frameworks.accumulo.scheduler.matcher.Match;
import aredee.mesos.frameworks.accumulo.scheduler.matcher.Matcher;
import aredee.mesos.frameworks.accumulo.scheduler.matcher.MinCpuMinRamFIFOMatcher;
import aredee.mesos.frameworks.accumulo.scheduler.server.AccumuloServer;
import aredee.mesos.frameworks.accumulo.scheduler.server.GarbageCollector;
import aredee.mesos.frameworks.accumulo.scheduler.server.Master;
import aredee.mesos.frameworks.accumulo.scheduler.server.Monitor;
import aredee.mesos.frameworks.accumulo.scheduler.server.ServerUtils;
import aredee.mesos.frameworks.accumulo.scheduler.server.TabletServer;
import aredee.mesos.frameworks.accumulo.scheduler.server.Tracer;
import org.apache.mesos.Protos;
import org.apache.mesos.SchedulerDriver;
import org.apache.mesos.state.State;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aredee.mesos.frameworks.accumulo.configuration.cluster.ClusterConfiguration;
import aredee.mesos.frameworks.accumulo.configuration.process.ProcessConfiguration;
import aredee.mesos.frameworks.accumulo.configuration.ServerType;
import aredee.mesos.frameworks.accumulo.initialize.AccumuloInitializer;
import java.util.*;
import java.util.Map.Entry;
public class Cluster {
private static final Logger LOGGER = LoggerFactory.getLogger(Cluster.class);
private final ClusterConfiguration config;
private String frameworkId;
private State state;
private Master master = null;
private GarbageCollector gc = null;
private Monitor monitor = null;
private Tracer tracer = null;
private Set<AccumuloServer> tservers = new HashSet<AccumuloServer>();
private Set<Protos.TaskStatus> runningServers = new HashSet<Protos.TaskStatus>();
private Set<AccumuloServer> serversToLaunch = new HashSet<AccumuloServer>();
private Map<ServerType, ProcessConfiguration> clusterServers;
private Matcher matcher;
private Launcher launcher;
@SuppressWarnings("unchecked")
public Cluster(AccumuloInitializer initializer){
this.state = initializer.getFrameworkState();
this.config = initializer.getClusterConfiguration();
this.launcher = new AccumuloStartExecutorLauncher(initializer);
this.matcher = new MinCpuMinRamFIFOMatcher(config);
clusterServers = config.getProcessorConfigurations();
LOGGER.info("Servers in the cluster? " + clusterServers);
// Take the cluster configuration from the input cluster configuration.
for(Entry<ServerType, ProcessConfiguration> entry : clusterServers.entrySet()) {
if (entry.getKey() == ServerType.TABLET_SERVER) {
for(int ii = 0; ii < config.getMinTservers(); ii++) {
ServerUtils.addServer(serversToLaunch, entry.getValue());
}
} else {
ServerUtils.addServer(serversToLaunch, entry.getValue());
}
}
}
public void setFrameworkId(String fid){
this.frameworkId = fid;
config.getFrameworkName();
//TODO persist configuration
}
@SuppressWarnings("unchecked")
public void handleOffers(SchedulerDriver driver, List<Protos.Offer> offers){
LOGGER.debug("Mesos Accumulo Cluster handling offers: for servers {}", serversToLaunch);
List<Match> matchedServers = matcher.matchOffers(serversToLaunch, offers);
LOGGER.debug("Found {} matches for servers from {} offers", matchedServers.size(), offers.size());
List<AccumuloServer> launchedServers = new ArrayList<>();
// Launch all the matched servers.
for (Match match: matchedServers){
LOGGER.info("Launching Server: {} on {}", match.getServer().getType().getName(),
match.getOffer().getSlaveId() );
Protos.TaskInfo taskInfo = launcher.launch(driver, match);
LOGGER.info("Created Task {} on {}", taskInfo.getTaskId(), taskInfo.getSlaveId());
launchedServers.add(match.getServer());
serversToLaunch.remove(match.getServer());
}
declineUnmatchedOffers(driver, offers, matchedServers);
// TODO call restore here?
}
// Remove used offers from the available offers and decline the rest.
private void declineUnmatchedOffers(SchedulerDriver driver, List<Protos.Offer> offers, List<Match> matches){
List<Protos.Offer> usedOffers = new ArrayList<>(matches.size());
for(Match match: matches){
if(match.hasOffer()){
usedOffers.add(match.getOffer());
}
}
offers.removeAll(usedOffers);
for( Protos.Offer offer: offers){
driver.declineOffer(offer.getId());
}
}
public void restore(SchedulerDriver driver) {
// reconcileTasks causes the framework to call updateTaskStatus, which
// will update the tasks list.
// TODO handle return of reconcileTasks
Protos.Status reconcileStatus = driver.reconcileTasks(runningServers);
clearServers();
// process the existing tasks
for (Protos.TaskStatus status : runningServers ){
String slaveId = status.getSlaveId().getValue();
String taskId = status.getTaskId().getValue();
if( Master.isMaster(taskId)){
master = (Master)ServerUtils.newServer(clusterServers.get(ServerType.MASTER), taskId, slaveId);
} else if( TabletServer.isTabletServer(taskId)) {
tservers.add((TabletServer)ServerUtils.newServer(clusterServers.get(ServerType.TABLET_SERVER), taskId, slaveId));
} else if( GarbageCollector.isGarbageCollector(taskId)) {
gc = (GarbageCollector)ServerUtils.newServer(clusterServers.get(ServerType.GARBAGE_COLLECTOR), taskId, slaveId);
} else if(Monitor.isMonitor(taskId)){
monitor = (Monitor)ServerUtils.newServer(clusterServers.get(ServerType.MONITOR), taskId, slaveId);
} else if (Tracer.isTacer(taskId)) {
tracer = (Tracer)ServerUtils.newServer(clusterServers.get(ServerType.TRACER), taskId, slaveId);
}
}
//TODO save cluster state
}
/**
* Updates Cluster state based on task status.
*
* @param status
*/
public void updateTaskStatus(Protos.TaskStatus status){
String slaveId = status.getSlaveId().getValue();
String taskId = status.getTaskId().getValue();
LOGGER.info("Task Status Update: Status: {} Slave: {} Task: {}", status.getState(), slaveId, taskId);
switch (status.getState()){
case TASK_RUNNING:
runningServers.add(status);
break;
case TASK_FINISHED:
case TASK_FAILED:
case TASK_KILLED:
case TASK_LOST:
runningServers.remove(status);
// re-queue tasks when servers are lost.
if( Master.isMaster(taskId)){
// Don't save the slave id, it maybe re-assigned to a new slave
serversToLaunch.add(ServerUtils.newServer(clusterServers.get(ServerType.MASTER), taskId, null));
clearMaster();
} else if (TabletServer.isTabletServer(taskId)) {
tservers.remove(new TabletServer(taskId, slaveId));
serversToLaunch.add(ServerUtils.newServer(clusterServers.get(ServerType.TABLET_SERVER), taskId, null));
} else if (Monitor.isMonitor(taskId)) {
serversToLaunch.add(ServerUtils.newServer(clusterServers.get(ServerType.MONITOR), taskId, null));
clearMonitor();
} else if (GarbageCollector.isGarbageCollector(taskId)) {
serversToLaunch.add(ServerUtils.newServer(clusterServers.get(ServerType.GARBAGE_COLLECTOR), taskId, null));
clearGC();
}
break;
case TASK_STARTING:
case TASK_STAGING:
break;
default:
LOGGER.info("Unknown Task Status received: {}", status.getState().toString());
}
}
public boolean isMasterRunning(){
return master == null;
}
public boolean isGCRunning(){
return gc == null;
}
public boolean isMonitorRunning(){
return monitor == null;
}
public int numTserversRunning(){
return tservers.size();
}
private void clearServers(){
clearMaster();
clearMonitor();
clearGC();
clearTservers();
}
private void clearMaster(){ master = null; }
private void clearMonitor(){ monitor = null; }
private void clearGC(){ gc = null; }
private void clearTservers(){ tservers.clear(); }
}
| accumulo-mesos-scheduler/src/main/java/aredee/mesos/frameworks/accumulo/scheduler/Cluster.java | package aredee.mesos.frameworks.accumulo.scheduler;
import aredee.mesos.frameworks.accumulo.scheduler.launcher.AccumuloStartExecutorLauncher;
import aredee.mesos.frameworks.accumulo.scheduler.launcher.Launcher;
import aredee.mesos.frameworks.accumulo.scheduler.matcher.Match;
import aredee.mesos.frameworks.accumulo.scheduler.matcher.Matcher;
import aredee.mesos.frameworks.accumulo.scheduler.matcher.MinCpuMinRamFIFOMatcher;
import aredee.mesos.frameworks.accumulo.scheduler.server.AccumuloServer;
import aredee.mesos.frameworks.accumulo.scheduler.server.GarbageCollector;
import aredee.mesos.frameworks.accumulo.scheduler.server.Master;
import aredee.mesos.frameworks.accumulo.scheduler.server.Monitor;
import aredee.mesos.frameworks.accumulo.scheduler.server.ServerUtils;
import aredee.mesos.frameworks.accumulo.scheduler.server.TabletServer;
import aredee.mesos.frameworks.accumulo.scheduler.server.Tracer;
import org.apache.mesos.Protos;
import org.apache.mesos.SchedulerDriver;
import org.apache.mesos.state.State;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aredee.mesos.frameworks.accumulo.configuration.cluster.ClusterConfiguration;
import aredee.mesos.frameworks.accumulo.configuration.process.ProcessConfiguration;
import aredee.mesos.frameworks.accumulo.configuration.ServerType;
import aredee.mesos.frameworks.accumulo.initialize.AccumuloInitializer;
import java.util.*;
import java.util.Map.Entry;
public class Cluster {
private static final Logger LOGGER = LoggerFactory.getLogger(Cluster.class);
private final ClusterConfiguration config;
private String frameworkId;
private State state;
private AccumuloInitializer initializer;
private Master master = null;
private GarbageCollector gc = null;
private Monitor monitor = null;
private Tracer tracer = null;
private Set<AccumuloServer> tservers = new HashSet<AccumuloServer>();
private Set<Protos.TaskStatus> runningServers = new HashSet<Protos.TaskStatus>();
private Set<AccumuloServer> serversToLaunch = new HashSet<AccumuloServer>();
private Map<ServerType, ProcessConfiguration> clusterServers;
private Matcher matcher;
private Launcher launcher;
@SuppressWarnings("unchecked")
public Cluster(AccumuloInitializer initializer){
this.initializer = initializer;
this.state = initializer.getFrameworkState();
this.config = initializer.getClusterConfiguration();
this.launcher = new AccumuloStartExecutorLauncher(initializer);
this.matcher = new MinCpuMinRamFIFOMatcher(config);
clusterServers = config.getProcessorConfigurations();
LOGGER.info("Servers in the cluster? " + clusterServers);
// Take the cluster configuration from the input cluster configuration.
for(Entry<ServerType, ProcessConfiguration> entry : clusterServers.entrySet()) {
if (entry.getKey() == ServerType.TABLET_SERVER) {
for(int ii = 0; ii < config.getMinTservers(); ii++) {
ServerUtils.addServer(serversToLaunch, entry.getValue());
}
} else {
ServerUtils.addServer(serversToLaunch, entry.getValue());
}
}
}
public void setFrameworkId(String fid){
this.frameworkId = fid;
config.getFrameworkName();
//TODO persist configuration
}
@SuppressWarnings("unchecked")
public void handleOffers(SchedulerDriver driver, List<Protos.Offer> offers){
LOGGER.info("Mesos Accumulo Cluster handling offers: for servers " + serversToLaunch);
List<Match> matchedServers = matcher.matchOffers(serversToLaunch, offers);
LOGGER.info("Found {} matches for servers from {} offers", matchedServers.size(), offers.size());
List<AccumuloServer> launchedServers = new ArrayList<>();
LOGGER.info("serversToLaunch before launching? " + serversToLaunch);
// Launch all the matched servers.
for (Match match: matchedServers){
LOGGER.info("Launching Server: {} on {}", match.getServer().getType().getName(),
match.getOffer().getSlaveId() );
Protos.TaskInfo taskInfo = launcher.launch(driver, match);
LOGGER.info("Created Task {} on {}", taskInfo.getTaskId(), taskInfo.getSlaveId());
launchedServers.add(match.getServer());
serversToLaunch.remove(match.getServer());
}
LOGGER.info("serversToLaunch after launching? " + serversToLaunch);
declineUnmatchedOffers(driver, offers, matchedServers);
// TODO call restore here?
}
// Remove used offers from the available offers and decline the rest.
private void declineUnmatchedOffers(SchedulerDriver driver, List<Protos.Offer> offers, List<Match> matches){
List<Protos.Offer> usedOffers = new ArrayList<>(matches.size());
for(Match match: matches){
if(match.hasOffer()){
usedOffers.add(match.getOffer());
}
}
offers.removeAll(usedOffers);
for( Protos.Offer offer: offers){
driver.declineOffer(offer.getId());
}
}
public void restore(SchedulerDriver driver) {
// reconcileTasks causes the framework to call updateTaskStatus, which
// will update the tasks list.
// TODO handle return of reconcileTasks
Protos.Status reconcileStatus = driver.reconcileTasks(runningServers);
clearServers();
// process the existing tasks
for (Protos.TaskStatus status : runningServers ){
String slaveId = status.getSlaveId().getValue();
String taskId = status.getTaskId().getValue();
if( Master.isMaster(taskId)){
master = (Master)ServerUtils.newServer(clusterServers.get(ServerType.MASTER), taskId, slaveId);
} else if( TabletServer.isTabletServer(taskId)) {
tservers.add((TabletServer)ServerUtils.newServer(clusterServers.get(ServerType.TABLET_SERVER), taskId, slaveId));
} else if( GarbageCollector.isGarbageCollector(taskId)) {
gc = (GarbageCollector)ServerUtils.newServer(clusterServers.get(ServerType.GARBAGE_COLLECTOR), taskId, slaveId);
} else if(Monitor.isMonitor(taskId)){
monitor = (Monitor)ServerUtils.newServer(clusterServers.get(ServerType.MONITOR), taskId, slaveId);
} else if (Tracer.isTacer(taskId)) {
tracer = (Tracer)ServerUtils.newServer(clusterServers.get(ServerType.TRACER), taskId, slaveId);
}
}
//TODO save cluster state
}
/**
* Updates Cluster state based on task status.
*
* @param status
*/
public void updateTaskStatus(Protos.TaskStatus status){
String slaveId = status.getSlaveId().getValue();
String taskId = status.getTaskId().getValue();
LOGGER.info("Task Status Update: Status: {} Slave: {} Task: {}", status.getState(), slaveId, taskId);
switch (status.getState()){
case TASK_RUNNING:
runningServers.add(status);
break;
case TASK_FINISHED:
case TASK_FAILED:
case TASK_KILLED:
case TASK_LOST:
runningServers.remove(status);
// re-queue tasks when servers are lost.
if( Master.isMaster(taskId)){
// Don't save the slave id, it maybe re-assigned to a new slave
serversToLaunch.add(ServerUtils.newServer(clusterServers.get(ServerType.MASTER), taskId, null));
clearMaster();
} else if (TabletServer.isTabletServer(taskId)) {
tservers.remove(new TabletServer(taskId, slaveId));
serversToLaunch.add(ServerUtils.newServer(clusterServers.get(ServerType.TABLET_SERVER), taskId, null));
} else if (Monitor.isMonitor(taskId)) {
serversToLaunch.add(ServerUtils.newServer(clusterServers.get(ServerType.MONITOR), taskId, null));
clearMonitor();
} else if (GarbageCollector.isGarbageCollector(taskId)) {
serversToLaunch.add(ServerUtils.newServer(clusterServers.get(ServerType.GARBAGE_COLLECTOR), taskId, null));
clearGC();
}
break;
case TASK_STARTING:
case TASK_STAGING:
break;
default:
LOGGER.info("Unknown Task Status received: {}", status.getState().toString());
}
}
public boolean isMasterRunning(){
return master == null;
}
public boolean isGCRunning(){
return gc == null;
}
public boolean isMonitorRunning(){
return monitor == null;
}
public int numTserversRunning(){
return tservers.size();
}
private void clearServers(){
clearMaster();
clearMonitor();
clearGC();
clearTservers();
}
private void clearMaster(){ master = null; }
private void clearMonitor(){ monitor = null; }
private void clearGC(){ gc = null; }
private void clearTservers(){ tservers.clear(); }
}
| cleaned up logging
| accumulo-mesos-scheduler/src/main/java/aredee/mesos/frameworks/accumulo/scheduler/Cluster.java | cleaned up logging |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.