answer stringlengths 17 10.2M |
|---|
package scrum.server.css;
import ilarkesto.base.Colors;
import ilarkesto.ui.web.CssRenderer;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ScreenCssBuilder implements CssBuilder {
public static String fontFamily = "Arial Unicode MS, Arial, sans-serif";
public static int fontSize = 12;
public static int lineHeight = 16;
public static int fontSizeSmall = 9;
public static int lineHeightSmall = 9;
public static int fontSizeTitle = 14;
public static int lineHeightTitle = 18;
public static String cBackground = "#F2F5FE";
public static String cHeaderBackground = "#667B99";
public static String cHeaderLink = "#D6E4E1";
public static String cEstimationBar0 = cHeaderBackground;
public static String cEstimationBar1 = "#669976";
public static String cLink = "#2956B2";
public static String cErrorBackground = "#FEE";
public static String cError = "darkred";
public static String cHeaderText = "#FFFFFF";
public static String cNavigatorSeparator = "#D9DEE6";
public static String cNavigatorLink = "#465B79";
public static String cNavigatorSelectedItemBackground = "#CCD5E6";
public static String cNavigatorHoverItemBackground = "#E9EEF6";
public static String cFieldBackground = "#FFFFFF";
public static String cBlockHeaderBackground = cNavigatorHoverItemBackground;
public static String cBlockBackground = "#FAFDFF";
public static String cBlockSelectionBorder = cHeaderBackground;
public static String cBlockHeaderHoverBackground = cBackground;
public static String cBlockHeaderDragHandleBackground = "#FBFBFF";
public static String cBlockHeaderCellSecondary = "gray";
public static String cToolbarBackground = cNavigatorHoverItemBackground;
public static String cPagePanelHeaderBackground = "#FFF7F0";
public static String cPagePanelHeader = "#FF6637";
public static String cPagePanelBorder = cNavigatorSeparator;
public static String cChatBackground = "#FFFFFF";
public static String cChatBorder = cPagePanelBorder;
public static String cTrashBackground = cNavigatorHoverItemBackground;
public static String cTrashBorder = cPagePanelBorder;
public static String cWaitBackground = cFieldBackground;
public static String cWait = cLink;
public static String cButtonText = "#444";
public static String cButtonTextHover = "#500";
public static String cButtonTextDisabled = "lightgray";
public static String cButtonBorder = "#666";
public static String cButtonBorderHover = "#866";
public static String cButtonBorderDisabled = cButtonTextDisabled;
public static String cCommentsBackground = "#F8FFF8";
public static String cCommentsBorder = "#EAFFEA";
public static String cCommentDate = "darkgray";
// public static String cUserguideBackground = "#F8F8FF";
// public static String cUserguide = "#000066";
// public static String cUserguideBorder = "#E0E0FF";
public static String cUserguideBackground = cPagePanelHeaderBackground;
public static String cUserguide = "#330000";
public static String cUserguideBorder = "#E0E0E0";
public static String cUserguideTableHeaderBackground = cUserguideBorder;
public static String cChangesBackground = "#FFFFF8";
public static String cChangesBorder = "#FFFFEA";
public static String cChangeDate = cCommentDate;
public static String cChangesCommentBackground = "#F7F7F0";
public static String cActionsBackground = cPagePanelHeaderBackground;
public static String cActionsBorder = "#FFC697";
public static String cPlanningPokerTableLines = "#EEE";
public static String cBurndownLine = Colors.darken(cHeaderBackground);
public static String cBurndownProjectionLine = Colors.lighten(Colors.lighten(cBurndownLine));
public static String cBurndownOptimalLine = cPagePanelBorder;
@Override
public void buildCss(CssRenderer css) {
html(css);
gwt(css);
ilarkesto(css);
loginPage(css);
systemMessage(css);
blockList(css);
comments(css);
userGuide(css);
actions(css);
changeHistory(css);
workspace(css);
navigator(css);
chat(css);
pagePanel(css);
whiteboard(css);
dashboard(css);
calendar(css);
planningPoker(css);
userStatus(css);
css.style(".EmoticonSelectorWidget-emoticon").border(1, "white").borderRadius(2).padding(2, 1, 0, 1)
.cursorPointer();
css.style(".EmoticonSelectorWidget-emoticon-selected").background(cBlockHeaderBackground)
.border(1, cBlockSelectionBorder).padding(2, 3, 0, 2);
css.style(".TrashWidget").background(cTrashBackground).border(1, cTrashBorder).padding(5);
css.style(".ToolbarWidget").background(cToolbarBackground).padding(3, 0, 3, 3);
css.style(".ToolbarWidget .FloatingFlowPanel-element-left").marginRight(3);
css.style(".ToolbarWidget .FloatingFlowPanel-element-right").marginLeft(3);
css.style(".fieldLabel").color(cHeaderBackground).lineHeight(22).whiteSpaceNowrap();
css.style(".AFieldValueWidget").background("white").border(1, "dotted", "white").minWidth(16).minHeight(16)
.displayBlock().padding(3);
css.style(".FieldsWidget-fieldLabel").color(cHeaderBackground).lineHeight(22).whiteSpaceNowrap();
css.style(".dnd-drop-allowed").background(cHeaderBackground);
css.style(".WidgetsTesterWidget .test-content").background("white").color("black").border(1, "#AAA");
css.style(".highlighted .ABlockWidget-title").border(1, cError);
css.style(".LockInfoWidget-icon").marginRight(10);
css.style(".WaitWidget").background(cWaitBackground).margin(200, 0, 200, 0).borderTop(1, cPagePanelBorder)
.borderBottom(1, cPagePanelBorder).fontSize(fontSize + 2);
css.style(".LoginWidget-errorMessage").background(cErrorBackground).color(cError).border(1, cError)
.fontSize(fontSize + 2).padding(5);
css.style(".PunishmentsWidget-tableHeader").padding(10).fontSize(fontSizeTitle).lineHeight(lineHeightTitle);
css.style(".AViewEditWidget-viewer").minWidth(16).minHeight(16).displayBlock().padding(3);
css.style(".AViewEditWidget-viewer-editable").background(cFieldBackground)
.border(1, "dotted", cNavigatorSelectedItemBackground).cursorPointer();
css.style(".ARichtextViewEditWidget-viewer .codeBlock").displayBlock().padding(5).margin(0, 10, 10, 10)
.border(1, "#EEE").background(Colors.lighten(cFieldBackground)).maxWidth(350).maxHeight(400)
.overflowScroll();
css.style(".ARichtextViewEditWidget-viewer div.toc").border(1, cPagePanelBorder).background("#EEE")
.floatRight().padding(10, 10, 3, 5).margin(10);
css.style(".ARichtextViewEditWidget-editor").border(1, cPagePanelBorder);
css.style(".ARichtextViewEditWidget-editor .html-editor-toolbar").displayNone();
css.style(".AEditableTextareaWidget-editorPanel").width100();
css.style(".Integer-editor").width(10, "%");
css.style(".AViewEditWidget-error").color(cError).background(cErrorBackground).border(1, cError).margin(2)
.padding(2);
css.style(".data-table").borderCollapseCollapse();
css.style(".data-table td").border(1, "#ccc").padding(5);
css.style(".data-table th").border(1, "#ccc").padding(5).fontWeightBold().textAlignCenter().background("#eee");
css.style(".AIntegerViewEditWidget .gwt-Button").padding(0, 3, 0, 3).fontSize(fontSizeSmall);
css.style(".TaskRemainingWorkWidget").marginLeft(3);
css.style(".TaskRemainingWorkWidget .gwt-Button").fontSize(fontSizeSmall);
css.style(".RequirementEstimatedWorkWidget").marginLeft(3);
css.style(".RequirementEstimatedWorkWidget .gwt-Button").fontSize(fontSizeSmall);
css.style(".EstimationBarWidget").marginTop(8).border(1, cNavigatorSelectedItemBackground);
css.style(".EstimationBarWidget-bar0").background(cEstimationBar0).lineHeight(1).fontSize(1);
css.style(".EstimationBarWidget-bar1").background(cEstimationBar1).lineHeight(1).fontSize(1);
css.style(".SprintBorderIndicatorWidget").background(cPagePanelHeaderBackground).color(cPagePanelHeader)
.border(1, cPagePanelBorder).textAlignCenter().borderRadius(10).fontSize(fontSizeSmall)
.margin(3, 100, 3, 100);
css.style("ul.toc");// .displayInline().floatRight();
css.style("a.reference, a.reference:visited").fontFamilyMonospace().color(cLink);
css.style("a.reference-unavailable").color("darkgray");
css.style("input.InputMandatory").border(1, "black");
css.style(".CreateTaskButtonWrapper").marginTop(5);
css.style(".CreateTaskButtonWrapper .ButtonWidget .gwt-Button").fontSize(fontSizeSmall).margin(0).padding(1);
css.style(".CreateStoryButtonWidget").marginTop(1).width(140);
css.style(".CreateStoryButtonWidget-dragHandle").marginTop(0).width(40).colorBlack();
css.style(".ReleaseWidget-script-running").fontFamilyMonospace().overflowHidden().color("red").fontWeightBold()
.textDecorationBlink();
css.style(".ReleaseWidget-script-ok").fontFamilyMonospace().overflowHidden();
css.style(".ReleaseWidget-script-empty").fontFamilyMonospace().overflowHidden();
css.style(".ReleaseWidget-script-failed").fontFamilyMonospace().overflowHidden().color("red");
}
private void loginPage(CssRenderer css) {
css.style(".loginPage");
css.style(".loginPage a").color("moccasin");
css.style(".loginPage code").color("#FFA");
css.style(".loginPage .panel").background(cHeaderBackground).width(380).margin("50px auto").padding(20)
.borderRadius(15);
css.style(".loginPage .panel img").marginBottom(-20);
css.style(".loginPage .message").color("gold").fontWeightBold().marginBottom(10).fontSize(fontSizeTitle);
String labelColor = Colors.lighten(Colors.lighten(Colors.lighten(cHeaderBackground)));
css.style(".loginPage .inputButton, .loginPage a.openid .button").background(Colors.darken(cHeaderBackground))
.border(1, cPagePanelBorder).borderRadius(5).color(labelColor).fontWeightBold().padding(1, 10)
.cursorPointer().textShadow(-1, -1, 0, "#444");
css.style(".loginPage .inputButton").marginRight(10);
css.style(".loginPage a.openid .button").margin(0, 5, 5, 0).floatLeft();
css.style(".loginPage input:hover.inputButton, .loginPage a.openid:hover .button").color(
Colors.lighten(labelColor));
css.style(".loginPage .inputCheckbox").marginLeft(0);
css.style(".loginPage .panel label").color(labelColor).marginRight(5);
css.style(".loginPage .panel .optionalLabel label").color(Colors.lighten(cHeaderBackground));
css.style(".loginPage h2").color("#fff").margin(30, 0, 20, 0).fontSize(fontSizeTitle + 4)
.textShadow(1, 1, 0, "#222");
css.style(".loginPage input").marginBottom(5);
css.style("#username, #email, #password").width(150).marginRight(10);
css.style("#openid").width(309).marginRight(10);
css.style(".loginPage .separator").borderTop(1, Colors.lighten(cHeaderBackground)).margin(20, 0, 20, 0);
css.style(".loginPage .configMessage").colorWhite();
css.style(".loginPage .kunagiLink").textAlignRight().fontSize(fontSizeSmall).color(labelColor);
css.style(".loginPage .kunagiLink a").color(Colors.lighten(labelColor));
}
private void planningPoker(CssRenderer css) {
css.style(".PlanningPokerWidget-table-border").background("#333").border(2, "#2A2A2A").padding(12)
.borderRadius(60).marginBottom(10);
css.style(".PlanningPokerWidget-table").border(2, "#2A2A2A").borderRadius(45)
.background("#5A5 url(pokertable_bg.jpg)").padding(40);
css.style(".PlanningPokerWidget-table-branding").color(cPlanningPokerTableLines).fontFamily("Times New Roman")
.fontWeightBold().fontSize(30).textAlignCenter().marginBottom(30);
css.style(
".PlanningPokerWidget-table .gwt-Hyperlink, .PlanningPokerWidget-table a, .PlanningPokerTableWidget-estimationHelp ul li a.reference")
.color(cPlanningPokerTableLines);
int cardWidth = 40;
int cardHeight = 60;
css.style(".PlanningPokerCardSlotWidget-slot").width(cardWidth - 8).height(cardHeight - 8)
.border(5, "solid", cPlanningPokerTableLines).borderRadius(5);
css.style(".PlanningPokerCardSlotWidget-text").color(cPlanningPokerTableLines).fontSize(fontSizeSmall)
.textAlignCenter();
css.style(".PlanningPokerCardWidget").borderRadius(5).width(cardWidth).height(cardHeight).background("#FFF")
.border(1, "#333");
css.style(".PlanningPokerCardWidget-clickable").cursorPointer();
css.style(".PlanningPokerCardWidget-text").fontSize(23).lineHeight(60).fontFamily("Times New Roman")
.textAlignCenter();
css.style(".PlanningPokerCardWidget-back").height100().background(cHeaderBackground + " url(pokercard_bg.jpg)");
}
private void calendar(CssRenderer css) {
css.style(".DateSelectorWidget").background("white").textAlignCenter().border(1, "white");
css.style(".DateSelectorWidget-weekday").background("white").textAlignCenter().color(cBlockHeaderCellSecondary)
.border(1, "white");
css.style(".DateSelectorWidget-weeknumber").background("white").color(cBlockHeaderCellSecondary).width(20)
.border(1, "white");
css.style(".DateSelectorWidget-spacer").background("white").textAlignCenter().height(20)
.border(1, "solid", "white");
css.style(".DateSelectorWidget-selected").background(cNavigatorHoverItemBackground).textAlignCenter()
.border(1, cNavigatorHoverItemBackground);
css.style(".DateSelectorWidget-visible").background(cBackground).textAlignCenter()
.border(1, "solid", cBackground);
css.style(".DateSelectorWidget-today").border(1, cNavigatorSelectedItemBackground);
css.style(".DateSelectorWidget-events").color("red").fontSize(fontSizeSmall).lineHeight(lineHeightSmall)
.textAlignCenter();
css.style(".DayListWidget-date").color(cBlockHeaderCellSecondary);
css.style(".DayListWidget-date-info").padding(2);
css.style(".DayListWidget-week").color(cBlockHeaderCellSecondary);
css.style(".DayListWidget-month").color(cBlockHeaderCellSecondary);
}
private void dashboard(CssRenderer css) {
css.style(
".TeamTasksWidget, .UpcomingTasksWidget, .AcceptedIssuesWidget, .OpenImpedimentsWidget, .HighestRisksWidget, .LatestEventsWidget td")
.lineHeight(lineHeight + 4);
css.style(".TeamTasksWidget-user").borderTop(1, cBlockHeaderBackground).margin(3, 0);
css.style(".TeamTasksWidget").borderBottom(1, cBlockHeaderBackground);
css.style(".LatestEventsWidget td").borderTop(1, cBlockHeaderBackground).padding(3);
css.style(".LatestEventsWidget table").borderBottom(1, cBlockHeaderBackground);
css.style(".LatestEventsWidget-time").whiteSpaceNowrap().color(cCommentDate);
}
private void whiteboard(CssRenderer css) {
String cOpen = "#f99";
css.style(".WhiteboardWidget-open").borderTop(3, cOpen);
String cOwned = "#ff9";
css.style(".WhiteboardWidget-owned").borderTop(3, cOwned).padding(0, 1, 0, 1);
String cDone = "#9e9";
css.style(".WhiteboardWidget-done").borderTop(3, cDone);
// int pad = 3;
// css.style(".WhiteboardWidget-open").padding(pad, pad, pad, pad).background("#fff5f5");
// css.style(".WhiteboardWidget-owned").padding(pad, pad, pad, pad).background("#fffff5");
// css.style(".WhiteboardWidget-done").padding(pad, pad, pad, pad).background("#f5fff5");
css.style(".WhiteboardWidget-columnLabel").fontSize(fontSizeTitle).lineHeight(lineHeightTitle);
css.style(".WhiteboardWidget-columnLabel-open").borderTop(3, cOpen);
css.style(".WhiteboardWidget-columnLabel-owned").borderTop(3, cOwned);
css.style(".WhiteboardWidget-columnLabel-done").borderTop(3, cDone);
css.style(".WhiteboardWidget-requirement-list").padding(0).paddingTop(10);
}
private void ilarkesto(CssRenderer css) {
css.style(".AWidget-height100").height100();
css.style(".ImageAnchor img").floatLeft().marginRight(3);
css.style(".ImageAnchor .text").displayInline();
css.style(".FloatingFlowPanel-element-left").floatLeft();
css.style(".FloatingFlowPanel-element-right").floatRight();
css.style(".floatClear").clearBoth();
css.style(".BugMarker").border(1, cError).background(cErrorBackground).color(cError).displayBlock().margin(3)
.padding(3).fontWeightBold().fontSize(fontSizeSmall);
css.style(".Tooltip").background(cUserguideBackground).color(cUserguide).padding(10)
.border(1, cUserguideBorder).maxWidth(400);
css.style(".DropdownMenuButtonWidget .gwt-MenuBar-horizontal").paddingLeft(1).border(1, cPagePanelBorder);
css.style(".DropdownMenuButtonWidget .gwt-MenuBar-horizontal td").fontSize(fontSizeSmall)
.lineHeight(lineHeightSmall).padding(0, 3, 0, 3).whiteSpaceNowrap().cursorPointer();
css.style(".DropdownMenuButtonWidget .gwt-MenuItem-selected").backgroundNone();
}
private void gwt(CssRenderer css) {
css.style(".gwt-Hyperlink a").whiteSpaceNowrap();
css.style(".gwt-Button").fontFamily(fontFamily).fontSize(fontSize).fontWeightBold().color(cButtonText)
.padding(2).margin(0).whiteSpaceNowrap().border(1, cButtonBorder);
css.style(".gwt-Button:hover").color(cButtonTextHover).border(1, cButtonBorderHover);
css.style(".gwt-Button[disabled], .gwt-Button[disabled]:hover").color(cButtonTextDisabled)
.border(1, "solid", cButtonBorderDisabled);
css.style(".MenuItem-disabled").color(cButtonTextDisabled);
}
private void html(CssRenderer css) {
css.html().padding(0).margin(0);
css.body().padding(0).margin(0).background(cBackground).fontFamily(fontFamily).fontSize(fontSize)
.lineHeight(lineHeight);
css.table().borderCollapseCollapse();
css.td().verticalAlignTop().fontFamily(fontFamily).fontSize(fontSize).lineHeight(lineHeight);
css.a().cursorPointer().color(cLink).textDecorationUnderline().outlineNone();
css.p().margin(0, 0, 10, 0);
css.h1().fontSize(fontSize + 6).lineHeight(lineHeight + 6).fontWeightBold().margin(5, 0, 5, 0);
css.h2().fontSize(fontSize + 4).lineHeight(lineHeight + 4).fontWeightBold().margin(5, 0, 5, 0);
css.h3().fontSize(fontSize + 2).lineHeight(lineHeight + 2).fontWeightBold().margin(0, 0, 5, 0);
css.h4().fontSize(fontSize + 1).lineHeight(lineHeight + 1).fontWeightBold().margin(0, 0, 5, 0);
css.pre().margin(0, 0, 10, 0).color(cHeaderBackground).fontSize(fontSize).lineHeight(lineHeight);
css.code().color(cHeaderBackground).fontSize(fontSize).lineHeight(lineHeight);
css.ul().margin(0, 0, 10, 0).padding(0, 0, 0, 20);
css.ol().margin(0, 0, 10, 0).padding(0, 0, 0, 20);
css.img().border("0");
css.input().border(1, cPagePanelBorder);
css.textarea().border(1, cPagePanelBorder);
}
private void workspace(CssRenderer css) {
int headerHeight = 25;
css.style(".Workspace");
css.style(".Workspace-header").height(headerHeight).background(cHeaderBackground, "../header-bg.png")
.positionFixed().width100();
css.style(".Workspace-sidebar").overflowHidden().positionFixed(headerHeight + 10, 0).width(200);
css.style(".Workspace-sidebar .PagePanel").padding(0);
css.style(".Workspace-sidebar .PagePanel-header").color(cHeaderText);
css.style(".Workspace-sidebar .PagePanel-content").border("0");
css.style(".ProjectSidebarWidget").marginLeft(10);
css.style(".Workspace-workarea").marginTop(headerHeight + 10).marginRight(10).minHeight(2000);
css.style(".HeaderWidget-logo").marginLeft(5).marginRight(10); // .positionFixed().top(0).left(40).zIndex(100);
css.style(".HeaderWidget-title").color(cHeaderText).fontSize(12).fontWeightBold().paddingLeft(5).paddingTop(3);
css.style(".HeaderWidget-user").color(cHeaderText).fontSize(12).textAlignCenter().marginTop(3).marginRight(5);
css.style(".HeaderWidget .ToolbarWidget").background("none").margin(0).textAlignRight();
css.style(".HeaderWidget .ToolbarWidget .FloatingFlowPanel-element").floatRight();
css.style(".HeaderWidget a").color(cHeaderLink);
css.style(".StatusWidget").width(10).height(6).marginTop(8).borderRadius(1);
css.style(".SearchInputWidget input").fontSize(fontSizeSmall).lineHeight(lineHeightSmall).margin(0, 10, 0, 10)
.padding(1);
}
private void systemMessage(CssRenderer css) {
css.style(".SystemMessageWidget-box").background(cErrorBackground).color(cError).border(1, cError).padding(10)
.marginBottom(10);
css.style(".SystemMessageWidget-box-title").fontWeightBold().marginBottom(5);
css.style(".SystemMessageWidget-box-time").fontStyleItalic().marginTop(5).textAlignRight();
}
private void chat(CssRenderer css) {
css.style(".ChatWidget-outputScroller").background(cChatBackground).border(1, cChatBorder).padding(5);
css.style(".ChatWidget-output .author").color("green").fontStyleItalic();
css.style(".ChatWidget-output .author-system").color("red").fontStyleItalic();
css.style(".ChatWidget-output .author-me").color("gray").fontStyleItalic();
css.style(".ChatWidget-output a").textDecorationUnderline();
css.style(".ChatWidget-message").margin(0, 0, 0, 5);
css.style(".ChatWidget-input").marginTop(5).width(97, "%");
}
private void navigator(CssRenderer css) {
css.style(".NavigatorWidget");
css.style(".NavigatorWidget-head").borderBottom(1, cNavigatorSeparator).overflowHidden();
css.style(".NavigatorWidget-item-link").borderBottom(1, cNavigatorSeparator).overflowHidden();
css.style(".NavigatorWidget-item-link a").color(cNavigatorLink).displayBlock().padding(5, 3, 5, 3)
.textDecorationNone().overflowHidden();
css.style(".NavigatorWidget-item-link a:hover").background(cNavigatorHoverItemBackground);
css.style(".NavigatorWidget-item-link-selected a").background(cNavigatorSelectedItemBackground);
css.style(".NavigatorWidget-item-link-selected a:hover").background(cNavigatorSelectedItemBackground);
css.style(".NavigatorWidget-submenu .NavigatorWidget-item-link a").paddingLeft(30).overflowHidden();
}
private void actions(CssRenderer css) {
css.style(".ActionsPanel").background(cActionsBackground, "../specialarea-bg.png", "repeat-x")
.border(1, cActionsBorder).padding(7).borderRadius(10);
}
private void userGuide(CssRenderer css) {
css.style(".UserGuideWidget").color(cUserguide)
.background(cUserguideBackground, "../specialarea-bg.png", "repeat-x").border(1, cUserguideBorder)
.borderRadius(10);
css.style(".UserGuideWidget-header").padding(7);
css.style(".UserGuideWidget-content").margin(0, 7, 7, 7).paddingTop(7).borderTop(1, cUserguideBorder)
.columnWidth(310).columnGap(25).textAlignJustify();
css.style(".UserGuideWidget-content table").width100().marginBottom(10);
css.style(".UserGuideWidget-content table td").fontSize(fontSizeSmall);
css.style(".UserGuideWidget-content table td.headerCell").background(cUserguideTableHeaderBackground)
.fontWeightBold();
}
private void comments(CssRenderer css) {
css.style(".CommentsWidget").background(cCommentsBackground, "../specialarea-bg.png", "repeat-x")
.border(1, cCommentsBorder).padding(7).borderRadius(10);
css.style(".CommentsWidget-pageNavigator").borderTop(1, cPagePanelBorder).paddingTop(3);
css.style(".CommentsWidget-pageNavigator-currentPage").border(1, cPagePanelBorder).padding(1, 5)
.background(Colors.darken(cCommentsBackground));
css.style(".CommentsWidget-pageNavigator-page a").displayBlock().border(1, cPagePanelBorder).padding(1, 5)
.textDecorationNone().fontWeightBold();
css.style(".CommentsWidget-pageNavigator-page-disabled").displayBlock().border(1, cPagePanelBorder)
.padding(1, 5).textDecorationNone().fontWeightBold().color(cPagePanelBorder);
css.style(".CommentsWidget .AViewEditWidget-viewer").padding(0);
css.style(".CommentsWidget .AViewEditWidget-viewer-editable").padding(3);
css.style(".CommentWidget").margin(15, 0, 10, 0).borderTop(1, cPagePanelBorder);
css.style(".CommentWidget-header").margin(4, 0, 2, 0).width100();
css.style(".CommentWidget-header-author").floatLeft().marginRight(5);
css.style(".CommentWidget-header-date").color(cCommentDate);
css.style(".CommentWidget-editor");
css.style(".Comment-Widget-header-pub").floatRight();
css.style(".Comment-Widget-header-pub .gwt-Button").fontSize(fontSizeSmall);
}
private void changeHistory(CssRenderer css) {
css.style(".ChangeHistoryWidget").background(cChangesBackground, "../specialarea-bg.png", "repeat-x")
.border(1, cChangesBorder).padding(7).borderRadius(10);
css.style(".ChangeWidget").margin(15, 0, 10, 0).borderTop(1, cPagePanelBorder);
css.style(".ChangeWidget-header").margin(4, 0, 2, 0);
css.style(".ChangeWidget-header-author").floatLeft().marginRight(5);
css.style(".ChangeWidget-header-date").floatLeft().marginRight(5).color(cChangeDate);
css.style(".ChangeWidget-comment").marginTop(4);
css.style(".ChangeWidget-comment .AViewEditWidget-viewer").background(cChangesCommentBackground);
css.style(".ChangeWidget-diff span.added").color("green");
css.style(".ChangeWidget-diff span.removed").color("darkred").textDecorationLineThrough();
}
private void blockList(CssRenderer css) {
css.style(".ABlockWidget-extended").border(2, cBlockSelectionBorder).padding(3).backgroundWhite();
css.style(".ABlockWidget-body").padding(10).border(1, cBlockHeaderBackground).background(cBlockBackground);
// css.style(".BlockListWidget").border(1, "yellow").minHeight(50, "px");
css.style(".BlockHeaderWidget").background(cBlockHeaderBackground, "../blockheader-bg.png", "repeat-x");
css.style(".BlockHeaderWidget:hover").background(cBlockHeaderHoverBackground);
css.style(".BlockHeaderWidget-dragHandle, .CreateStoryButtonWidget-dragHandle").margin(2).padding(2)
.fontSize(fontSize - 1).lineHeight(lineHeight - 2).textAlignCenter().cursorMove()
.background(cBlockHeaderDragHandleBackground, "../blockdraghandle-bg.png")
.border(1, cNavigatorSeparator).borderRadius(5);
css.style(".BlockHeaderWidget-anchor").displayBlock().floatLeft().width100().textDecorationNone();
css.style(".BlockHeaderWidget-dragHandle:hover").background("white", "../blockdraghandle-hover-bg.png");
css.style(".BlockHeaderWidget-cell").fontWeightBold().color(cHeaderBackground).padding(4, 5, 0, 5);
css.style("a.BlockHeaderWidget-anchor:hover, a.BlockHeaderWidget-anchor:visited").color(cHeaderBackground);
css.style(
".BlockHeaderWidget-cell-secondary, a.BlockHeaderWidget-cell-secondary:visited, a.BlockHeaderWidget-cell-secondary:hover")
.color(cBlockHeaderCellSecondary).fontWeightNormal();
css.style(
".BlockHeaderWidget-cell-small, a.BlockHeaderWidget-cell-small:visited, a.BlockHeaderWidget-cell-small:hover")
.color(cBlockHeaderCellSecondary).fontSize(fontSizeSmall).fontWeightNormal().paddingTop(6);
css.style(".BlockHeaderWidget .ButtonWidget").padding(2, 5, 0, 5).margin(0);
css.style(".BlockHeaderWidget .ButtonWidget .gwt-Button").fontSize(fontSizeSmall).margin(0).padding(1);
css.style(".BlockHeaderWidget .EmoticonsWidget").padding(3, 5, 0, 5);
css.style(".BlockHeaderWidget .DropdownMenuButtonWidget").padding(2, 3, 0, 5);
css.style(".BlockDndMarkerWidget").background("none");
css.style(".BlockDndMarkerWidget-active").background(cError);
css.style(".UsersOnBlockWidget").padding(3, 5, 0, 5).textAlignRight();
}
private void userStatus(CssRenderer css) {
css.style(".UsersStatusWidget").borderBottom(1, cNavigatorSeparator);
css.style(".UserStatusWidget").padding(3).borderTop(1, cNavigatorSeparator);
css.style(".UserStatusWidget-name").floatLeft().textDecorationLineThrough().fontStyleItalic().cursorPointer();
css.style(".UserStatusWidget-name-online").textDecorationNone().fontStyleNormal();
css.style(".UserStatusWidget-selectedEntities a").fontFamilyMonospace();
css.style(".UserStatusWidget-selectedEntities").floatRight().fontSize(fontSizeSmall + 1);
css.style(".UserStatusWidget .AFieldValueWidget").backgroundNone().borderNone();
}
private void pagePanel(CssRenderer css) {
css.style(".PagePanel");// .padding(10);
css.style(".PagePanel-content").background("white").border(1, cPagePanelBorder);
css.style(".PagePanel-header").padding(6, 10, 6, 10).fontSize(fontSizeTitle).lineHeight(lineHeightTitle)
.background(cPagePanelHeaderBackground, "../page-header-bg.png").color(cPagePanelHeader);
css.style(".PagePanel-header .gwt-Button").fontSize(fontSizeSmall);
css.style(".PagePanel-header input").fontSize(fontSizeSmall);
css.style(".PagePanel-header .gwt-Hyperlink").fontSize(fontSizeSmall);
css.style(".PagePanel-section").margin(0, 10, 0, 10);
css.style(".PagePanel-spacer").height(10);
}
@Override
public String toString() {
StringWriter out = new StringWriter();
CssRenderer renderer = new CssRenderer(new PrintWriter(out));
buildCss(renderer);
renderer.flush();
return out.toString();
}
} |
package sizebay.catalog.client;
import java.util.*;
import lombok.NonNull;
import sizebay.catalog.client.http.*;
import sizebay.catalog.client.model.*;
import sizebay.catalog.client.model.filters.*;
/**
* A Basic wrapper on generated Swagger client.
*
* @author Miere L. Teixeira
*/
public class CatalogAPI {
final static String
DEFAULT_BASE_URL = "https://catalogue.fitpeek.co/api/v1/",
ENDPOINT_DASHBOARD = "/dashboard",
ENDPOINT_BRAND = "/brands",
ENDPOINT_MODELING = "/modelings",
ENDPOINT_PRODUCT = "/products",
ENDPOINT_CATEGORIES = "/categories",
ENDPOINT_TENANTS = "/tenants",
ENDPOINT_USER = "/user",
ENDPOINT_SIZE_STYLE = "/style",
ENDPOINT_DEVOLUTION = "/devolution",
ENDPOINT_IMPORTATION_ERROR = "/importations",
ENDPOINT_STRONG_CATEGORY = "/categories/strong",
ENDPOINT_STRONG_SUBCATEGORY = "/categories/strong/sub",
ENDPOINT_STRONG_MODEL = "models/strong",
ENDPOINT_STRONG_MODELING = "/modelings/strong",
SEARCH_BY_TEXT = "/search/all?text=";
final RESTClient client;
/**
* Constructs the Catalog API.
*
* @param applicationToken
* @param securityToken
*/
public CatalogAPI(@NonNull String applicationToken, @NonNull String securityToken) {
this(DEFAULT_BASE_URL, applicationToken, securityToken);
}
/**
* Constructs the Catalog API.
*
* @param basePath
* @param applicationToken
* @param securityToken
*/
public CatalogAPI(@NonNull String basePath, @NonNull String applicationToken, @NonNull String securityToken) {
final CatalogAuthentication authentication = new CatalogAuthentication( applicationToken, securityToken );
final MimeType mimeType = new JSONMimeType();
client = new RESTClient( basePath, mimeType, authentication );
}
/**
* Starting dashboard management
*/
public List<Dashboard> retrieveDashboard() {
return client.getList(ENDPOINT_DASHBOARD, Dashboard.class);
}
public Dashboard retrieveDashboardByTenant(Long tenantId) {
return client.getSingle(ENDPOINT_DASHBOARD + "/single/" + tenantId, Dashboard.class);
}
/**
* End dashboard management
*/
public ProductBasicInformationToVFR retrieveProductBasicInformationToVFR(String permalink) {
return client.getSingle(ENDPOINT_PRODUCT + "/basic-info-to-vfr?"
+ "permalink=" + permalink, ProductBasicInformationToVFR.class);
}
/**
* Starting user profile management
*/
public void insertUser (UserProfile userProfile) {
client.post(ENDPOINT_USER, userProfile);
}
public UserProfile updateProfileName(ProfileUpdateName profileUpdateName){
return client.put( ENDPOINT_USER + "/update/profile/name", profileUpdateName, UserProfile.class);
}
public UserProfile retrieveUser (String userId) {
return client.getSingle(ENDPOINT_USER + "/single/" + userId, UserProfile.class);
}
public UserProfile retrieveUserByFacebook(String facebookToken) {
return client.getSingle(ENDPOINT_USER + "/social/facebook/" + facebookToken, UserProfile.class);
}
public UserProfile retrieveUserByGoogle(String googleToken) {
return client.getSingle(ENDPOINT_USER + "/social/google/" + googleToken, UserProfile.class);
}
public UserProfile retrieveUserByApple(String appleUserId) {
return client.getSingle(ENDPOINT_USER + "/social/apple/" + appleUserId, UserProfile.class);
}
public Profile retrieveProfile (long profileId) {
return client.getSingle(ENDPOINT_USER + "/profile/" + profileId, Profile.class);
}
public void updateUserFacebookToken(String userId, String facebookToken) {
client.put(ENDPOINT_USER + "/social/facebook/" + userId, facebookToken);
}
public void updateUserGoogleToken(String userId, String googleToken) {
client.put(ENDPOINT_USER + "/social/google/" + userId, googleToken);
}
public void updateUserAppleId(String userId, String appleUserId) {
client.put(ENDPOINT_USER + "/social/apple/" + userId, appleUserId);
}
public void insertProfile (Profile profile) {
client.post(ENDPOINT_USER + "/profile", profile);
}
public void deleteProfile (long profileId) { client.delete(ENDPOINT_USER + "/profile/" + profileId); }
/* User history */
public long insertProductInUserHistory(String userId, UserHistory newProductToUserHistory) {
return client.post(ENDPOINT_USER + "/history/single/"+ userId, newProductToUserHistory);
}
public List<UserHistory> retrieveUserHistory(int page, String userId) {
return client.getList(ENDPOINT_USER + "/history/all/" + userId + "?page=" + page, UserHistory.class);
}
public void deleteUserHistoryProduct(String userId, Long userHistoryId) {
client.delete(ENDPOINT_USER + "/history/single/" + userId + "?userHistoryId=" + userHistoryId);
}
/* User liked products */
public long insertLikeInTheProduct(String userId, LikedProduct likedProduct) {
return client.post(ENDPOINT_USER + "/liked-products/single/"+ userId, likedProduct);
}
public List<LikedProduct> retrieveLikedProductsByUser(int page, String userId) {
return client.getList(ENDPOINT_USER + "/liked-products/all/" + userId + "?page=" + page, LikedProduct.class);
}
public void deleteLikeInTheProduct(String userId, Long likedProductId) {
client.delete(ENDPOINT_USER + "/liked-products/single/" + userId + "?likedProductId=" + likedProductId);
}
/*
* End user profile management
*/
/*
* Starting size style management
*/
public List<SizeStyle> getSizeStyles(SizeStyleFilter filter) {
return client.getList(ENDPOINT_SIZE_STYLE + "?" + filter.createQuery(), SizeStyle.class);
}
public SizeStyle getSingleSizeStyle(long id) {
return client.getSingle(ENDPOINT_SIZE_STYLE + "/single/" + id, SizeStyle.class);
}
public long insertSizeStyle(SizeStyle sizeStyle) {
return client.post(ENDPOINT_SIZE_STYLE + "/single", sizeStyle);
}
public void updateWeightStyle(long id, SizeStyle sizeStyle) {
client.put(ENDPOINT_SIZE_STYLE + "/single/" + id, sizeStyle);
}
public void bulkUpdateWeight(BulkUpdateSizeStyle bulkUpdateSizeStyle) {
client.patch(ENDPOINT_SIZE_STYLE + "/bulk/weight", bulkUpdateSizeStyle);
}
public void bulkUpdateModeling(BulkUpdateSizeStyle bulkUpdateSizeStyle) {
client.patch(ENDPOINT_SIZE_STYLE + "/bulk/modeling", bulkUpdateSizeStyle);
}
public void deleteSizeStyle(long id) {
client.delete(ENDPOINT_SIZE_STYLE + "/single/" + id);
}
public void deleteSizeStyles(List<Integer> ids) {
client.delete(ENDPOINT_SIZE_STYLE + "/bulk/some", ids);
}
/*
* End size style management
*/
/*
* Starting devolution management
*/
public List<DevolutionError> retrieveDevolutionErrors() {
return client.getList(ENDPOINT_DEVOLUTION + "/errors", DevolutionError.class);
}
public List<DevolutionError> retrieveDevolutionErrors(DevolutionFilter filter) {
return client.getList(ENDPOINT_DEVOLUTION + "/errors?" + filter.createQuery(), DevolutionError.class);
}
public long insertDevolutionError(DevolutionError devolution) {
return client.post(ENDPOINT_DEVOLUTION + "/errors/single", devolution);
}
public void deleteDevolutionErrors() {
client.delete(ENDPOINT_DEVOLUTION + "/errors");
}
public DevolutionSummary retrieveDevolutionSummaryLastBy() {
return client.getSingle(ENDPOINT_DEVOLUTION + "/summary/last", DevolutionSummary.class);
}
public long insertDevolutionSummary(DevolutionSummary devolutionSummary) {
return client.post(ENDPOINT_DEVOLUTION + "/summary/single", devolutionSummary);
}
public void deleteDevolutionSummary() {
client.delete(ENDPOINT_DEVOLUTION + "/summary");
}
/*
* End devolution management
*/
/*
* Starting user (MySizebay) management
*/
public UserTenants authenticateAndRetrieveUser(String username, String password ) {
return client.getSingle( "/users/" + username + "/" + password + "/user", UserTenants.class );
}
public List<Tenant> authenticateAndRetrieveTenants(String username, String password ) {
return client.getList( "/users/" + username + "/" + password + "/tenants", Tenant.class );
}
public List<UserTenants> retrieveAllUsersBy(String privilege) {
return client.getList( "/privileges/users?privilege=" + privilege, UserTenants.class );
}
/*
* End user (MySizebay) management
*/
/*
* Starting product management
*/
public List<Product> getProducts(int page) {
return client.getList(ENDPOINT_PRODUCT + "?page=" + page, Product.class);
}
public List<Product> getProducts(ProductFilter filter) {
return client.getList(ENDPOINT_PRODUCT + "/search/all" + "?" + filter.createQuery(), Product.class);
}
public Product getProduct(long id) {
return client.getSingle(ENDPOINT_PRODUCT + "/single/" + id, Product.class);
}
public Long getProductIdFromPermalink(String permalink){
return client.getSingle(ENDPOINT_PRODUCT + "/search/product-id"
+ "?permalink=" + permalink,
Long.class);
}
public ProductSlug retrieveProductSlugByPermalink(String permalink, String sizeLabel){
return client.getSingle(ENDPOINT_PRODUCT + "/slug"
+ "?permalink=" + permalink
+ "&size=" + sizeLabel,
ProductSlug.class);
}
public Long getAvailableProductIdFromPermalink(String permalink){
return client.getSingle(ENDPOINT_PRODUCT + "/search/product-id"
+ "?permalink=" + permalink
+ "&onlyAvailable=true",
Long.class);
}
public ProductIntegration retrieveProductIntegration(Long tenantId, String feedProductId) {
return client.getSingle(ENDPOINT_PRODUCT + "/search/feed-product-id"
+ "/" + tenantId
+ "/" + feedProductId,
ProductIntegration.class);
}
public ProductBasicInformation retrieveProductByBarcode(Long barcode) {
return client.getSingle(ENDPOINT_PRODUCT + "/search/barcode/" + barcode, ProductBasicInformation.class);
}
public ProductBasicInformation getProductBasicInfo(long id){
return client.getSingle(ENDPOINT_PRODUCT
+ "/" + id
+ "/basic-info",
ProductBasicInformation.class);
}
public ProductBasicInformation getProductBasicInfoFilterSizes(long id, String sizes){
return client.getSingle( ENDPOINT_PRODUCT
+ "/" + id
+ "/basic-info-filter-sizes"
+ "?sizes=" + sizes,
ProductBasicInformation.class);
}
public long insertProduct(Product product) {
return client.post(ENDPOINT_PRODUCT + "/single", product);
}
public void insertProductIntegration(ProductIntegration product) {
client.post(ENDPOINT_PRODUCT + "/single/integration", product);
}
public long insertMockedProduct(String permalink) {
return client.post(ENDPOINT_PRODUCT + "/mock?permalink=" + permalink, String.class);
}
public void updateProduct(long id, Product product) {
client.put(ENDPOINT_PRODUCT + "/single/" + id, product);
}
public void bulkUpdateProducts(BulkUpdateProducts products) {
client.patch(ENDPOINT_PRODUCT, products);
}
public void deleteProducts() {
client.delete(ENDPOINT_PRODUCT);
}
public void deleteProduct(long id) {
client.delete(ENDPOINT_PRODUCT + "/single/" + id);
}
public void deleteProducts(List<Integer> ids) {
client.delete(ENDPOINT_PRODUCT + "/bulk/some", ids);
}
/*
* End product management
*/
/*
* Starting brand management
*/
public List<Brand> searchForBrands(String text){
return client.getList(ENDPOINT_BRAND + SEARCH_BY_TEXT + text, Brand.class);
}
public List<Brand> getBrands(BrandFilter filter) {
return client.getList(ENDPOINT_BRAND + "?" + filter.createQuery(), Brand.class);
}
public List<Brand> getBrands(int page) {
return client.getList(ENDPOINT_BRAND + "?page=" + page, Brand.class);
}
public List<Brand> getBrands(int page, String name) {
return client.getList(ENDPOINT_BRAND + "?page=" + page + "&name=" + name, Brand.class);
}
public Brand getBrand(long id) {
return client.getSingle(ENDPOINT_BRAND + "/single/" + id, Brand.class);
}
public long insertBrand(Brand brand) {
return client.post(ENDPOINT_BRAND + "/single", brand);
}
public void associateBrandsWithStrongBrand() {
client.getSingle(ENDPOINT_BRAND + "/sync/associate-brand-with-strong-brand");
}
public void createStrongBrandBasedOnBrands(List<Integer> ids) {
client.post(ENDPOINT_BRAND + "/sync/create-strong-brand", ids);
}
public void updateBrand(long id, Brand brand) {
client.put(ENDPOINT_BRAND + "/single/" + id, brand);
}
public void deleteBrands() {
client.delete(ENDPOINT_BRAND);
}
public void deleteBrand(long id) {
client.delete(ENDPOINT_BRAND + "/single/" + id);
}
public void deleteBrands(List<Integer> ids) {
client.delete(ENDPOINT_BRAND + "/bulk/some", ids);
}
/*
* End brand management
*/
/*
* Starting category management
*/
public List<Category> getCategories() {
return client.getList(ENDPOINT_CATEGORIES, Category.class);
}
public List<Category> getCategories(int page) {
return client.getList(ENDPOINT_CATEGORIES + "?page=" + page, Category.class);
}
public List<Category> getCategories(int page, String name) {
return client.getList(ENDPOINT_CATEGORIES + "?page=" + page + "&name=" + name, Category.class);
}
public List<Category> getCategories(CategoryFilter filter) {
return client.getList(ENDPOINT_CATEGORIES + "?" + filter.createQuery(), Category.class);
}
public List<Category> searchForCategories(String text){
return client.getList(ENDPOINT_CATEGORIES + SEARCH_BY_TEXT + text, Category.class);
}
public Category getCategory(long id) {
return client.getSingle(ENDPOINT_CATEGORIES + "/single/" + id, Category.class);
}
public long insertCategory(Category brand) {
return client.post(ENDPOINT_CATEGORIES + "/single", brand);
}
public void updateCategory(long id, Category brand) {
client.put(ENDPOINT_CATEGORIES + "/single/" +id, brand);
}
public void bulkUpdateCategories(BulkUpdateCategories categories) {
client.patch(ENDPOINT_CATEGORIES, categories);
}
public void deleteCategories() {
client.delete(ENDPOINT_CATEGORIES);
}
public void deleteCategory(long id) {
client.delete(ENDPOINT_CATEGORIES + "/single/" + id);
}
public void deleteCategories(List<Integer> ids) {
client.delete(ENDPOINT_CATEGORIES + "/bulk/some", ids);
}
/*
* End category management
*/
/*
* Starting modeling management
*/
public List<Modeling> searchForModelings(long brandId, String gender) {
return searchForModelings(String.valueOf(brandId), gender);
}
public List<Modeling> searchForModelings(String brandId, String gender){
return client.getList(ENDPOINT_MODELING + "/search/brand/" + brandId + "/gender/" + gender, Modeling.class);
}
public List<Modeling> getModelings(int page){
return client.getList(ENDPOINT_MODELING + "?page=" + page, Modeling.class);
}
public List<Modeling> getModelings(ModelingFilter filter) {
return client.getList(ENDPOINT_MODELING + "/search/all" + "?" + filter.createQuery(), Modeling.class);
}
public List<Modeling> getAllSimplifiedModeling() {
return client.getList(ENDPOINT_MODELING + "/simplified/all", Modeling.class);
}
public Modeling getModeling(long id) {
return client.getSingle(ENDPOINT_MODELING + "/single/" + id, Modeling.class);
}
public long insertModeling(Modeling modeling) {
return client.post(ENDPOINT_MODELING + "/single", modeling);
}
public void updateModeling(long id, Modeling modeling) {
client.put(ENDPOINT_MODELING + "/single/" + id, modeling);
}
public void deleteModelings() {
client.delete(ENDPOINT_MODELING);
}
public void deleteModeling(long id) {
client.delete(ENDPOINT_MODELING + "/single/" + id);
}
public void deleteModelings(List<Integer> ids) {
client.delete(ENDPOINT_MODELING + "/bulk/some", ids);
}
/*
* End modeling management
*/
/*
* Starting importation error management
*/
public List<ImportationError> getImportationErrors(String page){
return client.getList(ENDPOINT_IMPORTATION_ERROR + "/errors?page=" + page, ImportationError.class);
}
public long insertImportationError(ImportationError importationError){
return client.post( ENDPOINT_IMPORTATION_ERROR + "/errors", importationError);
}
public void deleteImportationErrors() {
client.delete(ENDPOINT_PRODUCT + "/importation-errors/all");
}
public ImportationSummary getImportationSummary(){
return client.getSingle(ENDPOINT_IMPORTATION_ERROR + "/summary/last" , ImportationSummary.class);
}
public long insertImportationSummary(ImportationSummary importationSummary){
return client.post( ENDPOINT_IMPORTATION_ERROR + "/summary/single", importationSummary);
}
public void deleteImportationSummary() {
client.delete(ENDPOINT_IMPORTATION_ERROR);
}
/*
* End importation error management
*/
/*
* Starting strong brand management
*/
public List<StrongBrand> getStrongBrands(StrongBrandFilter filter) {
return client.getList(ENDPOINT_BRAND + "/strong?" + filter.createQuery(), StrongBrand.class);
}
public StrongBrand getSingleBrand(long id) {
return client.getSingle(ENDPOINT_BRAND + "/strong/single/" + id, StrongBrand.class);
}
public long insertStrongBrand(StrongBrand strongBrand){
return client.post( ENDPOINT_BRAND + "/strong/single", strongBrand);
}
public void updateStrongBrand(long id, StrongBrand strongBrand) {
client.put(ENDPOINT_BRAND + "/strong/single/" + id, strongBrand);
}
public void deleteStrongBrand(long id) {
client.delete(ENDPOINT_BRAND + "/strong/single/" + id);
}
public void deleteStrongBrands(List<Integer> ids) {
client.delete(ENDPOINT_BRAND + "/strong/bulk/some", ids);
}
/*
* End strong brand management
*/
/*
* Starting strong category management
*/
public List<StrongCategory> getAllStrongCategories(){
return client.getList(ENDPOINT_STRONG_CATEGORY, StrongCategory.class);
}
public List<StrongCategory> getAllStrongCategories(String page, String categoryName, String type){
String condition;
condition = categoryName == null ? "" : "&name=" + categoryName;
condition += type == null ? "" : "&type=" + type;
return client.getList(ENDPOINT_STRONG_CATEGORY + "?page=" + page + condition, StrongCategory.class);
}
public StrongCategory getSingleStrongCategory(long id) {
return client.getSingle(ENDPOINT_STRONG_CATEGORY + "/single/" + id, StrongCategory.class);
}
public long insertStrongCategory(StrongCategory strongCategory){
return client.post(ENDPOINT_STRONG_CATEGORY + "/single", strongCategory);
}
public void updateStrongCategory(long id, StrongCategory strongCategory) {
client.put(ENDPOINT_STRONG_CATEGORY + "/single/" + id, strongCategory);
}
public void deleteStrongCategory(long id) {
client.delete(ENDPOINT_STRONG_CATEGORY + "/single/" + id);
}
/*
* End strong category management
*/
/*
* Starting strong subcategory management
*/
public List<StrongSubcategory> getStrongSubcategories(StrongSubcategoryFilter filter){
return client.getList(ENDPOINT_STRONG_SUBCATEGORY + "?" + filter.createQuery(), StrongSubcategory.class);
}
public List<StrongSubcategory> getStrongSubcategories(int page){
return client.getList(ENDPOINT_STRONG_SUBCATEGORY + "?page=" + page, StrongSubcategory.class);
}
public StrongSubcategory getSingleStrongSubcategory(long id) {
return client.getSingle(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id, StrongSubcategory.class);
}
public long insertStrongSubcategory(StrongSubcategory strongSubcategory){
return client.post(ENDPOINT_STRONG_SUBCATEGORY + "/single", strongSubcategory);
}
public void updateStrongSubcategory(long id, StrongSubcategory strongSubcategory) {
client.put(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id, strongSubcategory);
}
public void deleteStrongSubcategory(long id) {
client.delete(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id);
}
/*
* End strong subcategory management
*/
/*
* Starting strong model management
*/
public List<StrongModel> getAllStrongModels(String page){
return client.getList(ENDPOINT_STRONG_MODEL + "?page=" + page, StrongModel.class);
}
public List<StrongModel> getAllStrongModels(String page, String modelName){
return client.getList(ENDPOINT_STRONG_MODEL + "?page=" + page + "&name=" + modelName, StrongModel.class);
}
public StrongModel getSingleStrongModel(long id) {
return client.getSingle(ENDPOINT_STRONG_MODEL + "/single/" + id, StrongModel.class);
}
public long insertStrongModel(StrongModel strongModel){
return client.post(ENDPOINT_STRONG_MODEL + "/single", strongModel);
}
public void updateStrongModel(long id, StrongModel strongModel) {
client.put(ENDPOINT_STRONG_MODEL + "/single/" + id, strongModel);
}
public void deleteStrongModel(long id) {
client.delete(ENDPOINT_STRONG_MODEL + "/single/" + id);
}
/*
* End strong model management
*/
/*
* Starting strong modeling management
*/
public List<StrongModeling> getStrongModelings(StrongModelingFilter filter) {
return client.getList(ENDPOINT_STRONG_MODELING + "?" + filter.createQuery(), StrongModeling.class);
}
public List<Long> retrieveAllOrganicTableIds(StrongModelingFilter filter) {
return client.getList(ENDPOINT_STRONG_MODELING + "/organic/ids" , Long.class);
}
public StrongModeling getSingleStrongModeling(long id) {
return client.getSingle(ENDPOINT_STRONG_MODELING + "/single/" + id, StrongModeling.class);
}
public List<StrongModeling> getAllSimplifiedStrongModelings(StrongModelingFilter filter) {
return client.getList(ENDPOINT_STRONG_MODELING + "/simplified" + "?" + filter.createQuery(), StrongModeling.class);
}
public long insertStrongModeling(StrongModeling strongModeling){
return client.post(ENDPOINT_STRONG_MODELING + "/single", strongModeling);
}
public void createStrongModelingsBasedOnBrands(String sizeSystem, List<Integer> ids) {
client.post(ENDPOINT_STRONG_MODELING + "/sync/create-strong-modelings?sizeSystem=" + sizeSystem, ids);
}
public void syncStrongModelingsWithSlugs() {
client.post(ENDPOINT_STRONG_MODELING + "/sync", null);
}
public void updateStrongModeling(long id, StrongModeling strongModeling) {
client.put(ENDPOINT_STRONG_MODELING + "/single/" + id, strongModeling);
}
public void deleteStrongModeling(long id) {
client.delete(ENDPOINT_STRONG_MODELING + "/single/" + id);
}
public void deleteStrongModelings(List<Integer> ids) {
client.delete(ENDPOINT_STRONG_MODELING + "/bulk/some", ids);
}
/*
* End strong modeling management
*/
/*
* Starting tenant management
*/
public Tenant getTenant( String appToken ){
return client.getSingle( ENDPOINT_TENANTS+ "/single/" + appToken, Tenant.class );
}
public List<Tenant> retrieveAllTenants(){
return client.getList( ENDPOINT_TENANTS, Tenant.class );
}
public List<Tenant> searchTenants(TenantFilter filter) {
return client.getList( ENDPOINT_TENANTS + "/search?monitored=" + filter.getMonitored(), Tenant.class);
}
public List<Tenant> searchAllTenants() {
return client.getList( ENDPOINT_TENANTS + "/search/all", Tenant.class);
}
public Long insertTenant(Tenant tenant) {
return client.post(ENDPOINT_TENANTS, tenant);
}
public void updateTenant(long id, Tenant tenant) {
client.put(ENDPOINT_TENANTS + "/single/" + id, tenant);
}
public void updateHashXML(String hash) {
client.put(ENDPOINT_TENANTS + "/hash", hash);
}
public void deleteTenant(long id) {
client.delete(ENDPOINT_TENANTS + "/" + id);
}
public TenantDetails retrieveTenantDetails(long id) {
return client.getSingle(ENDPOINT_TENANTS + "/details/single/" + id, TenantDetails.class);
}
public List<TenantDetails> retrieveAllTenantDetails() {
return client.getList(ENDPOINT_TENANTS + "/details", TenantDetails.class);
}
public void updateTenantDetails(TenantDetails tenantDetails) {
client.put(ENDPOINT_TENANTS + "/details/",tenantDetails);
}
public void updateTenantDetailsLogo(TenantDetails tenantDetails) {
client.put(ENDPOINT_TENANTS + "/details/logo/",tenantDetails);
}
/*
* End tenant management
*/
/*
* Starting tenant management
*/
public List<MySizebayUser> attachedUsersToTenant(long id) {
return client.getList(ENDPOINT_TENANTS + "/" + id + "/users", MySizebayUser.class);
}
public void attachUserToTenant(long id, String email) {
client.getSingle(ENDPOINT_TENANTS + "/" + id + "/users/" + email);
}
public void detachUserToTenant(long id, String email) {
client.delete(ENDPOINT_TENANTS + "/" + id + "/users/" + email);
}
/*
* End tenant management
*/
/*
* Starting importation rules management
*/
public String retrieveImportRules(long id) {
return client.getSingle(ENDPOINT_TENANTS + "/" + id + "/rules", String.class);
}
public Long insertImportationRules(long id, ImportationRules rules) {
return client.post(ENDPOINT_TENANTS + "/" + id + "/rules", rules);
}
/*
* End importation rules management
*/
/*
* Starting my sizebay user management
*/
public MySizebayUser getMySizebayUser(String username){
return client.getSingle( "/users/" + username, MySizebayUser.class);
}
public Long insertMySizebayUser(MySizebayUser user){
return client.post("/users/", user);
}
/*
* End my sizebay user management
*/
public void insertImportationSummary(long tenantId, ImportationSummary importationSummary) {
client.post( "/importations/tenantId/"+tenantId, importationSummary );
}
} |
package com.hpe.caf.worker.batch;
import java.util.Map;
public class BatchWorkerTask {
/**
* This is the definition of the batch. For example, it might be a string
* like "workbook == 5". The definition string will be interpreted by the
* type specified to the {@link #batchType} field.
*/
public String batchDefinition;
/**
* This is the type that is used to interpret the batch definition string.
* The Batch Worker will need to create an instance of this class to
* interpret the definition string, so the specified class must be made
* available on the Batch Worker's classpath.
*/
public String batchType;
/**
* This is a factory type that is used to construct the TaskMessage for each
* item of the batch. Like the type specified in the {@link #batchType}
* field, it must be available on the Batch Worker's classpath.
* <p>
* Obviously this type is highly tied to the {@link #targetPipe} field, in
* that the messages produced by this object must be compatible with the
* workers they are being sent to.
*/
public String taskMessageType;
/**
* This is a set of named parameters to be passed to the specified
* TaskMessage builder (i.e. the factory type specified by the
* {@link #taskMessageType} parameter). Their meaning is dependant on the
* type specified.
*/
public Map<String,String> taskMessageParams;
/**
* A message is constructed for each item of the batch. This field
* specifies the pipe (channel or queue) where these per-item messages are
* to be forwarded to.
*/
public String targetPipe;
} |
package skyhussars.terrained;
import javafx.scene.control.Alert;
import org.springframework.stereotype.Service;
@Service
public class AlertService {
public void info(String info, String detail) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("SkyHussars - TerrainEd");
alert.setHeaderText(info);
alert.setContentText(detail);
alert.showAndWait();
}
} |
package com.hubspot.dropwizard.guice;
import com.codahale.dropwizard.Configuration;
import com.codahale.dropwizard.ConfiguredBundle;
import com.codahale.dropwizard.setup.Bootstrap;
import com.codahale.dropwizard.setup.Environment;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.servlet.GuiceFilter;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.spi.container.servlet.ServletContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.List;
public class GuiceBundle<T extends Configuration> implements ConfiguredBundle<T> {
final Logger logger = LoggerFactory.getLogger(GuiceBundle.class);
private final AutoConfig autoConfig;
private final List<Module> modules;
private Injector injector;
private DropwizardEnvironmentModule dropwizardEnvironmentModule;
private Optional<Class<T>> configurationClass;
private GuiceContainer container;
public static class Builder<T extends Configuration> {
private AutoConfig autoConfig;
private List<Module> modules = Lists.newArrayList();
private Optional<Class<T>> configurationClass = Optional.<Class<T>>absent();
public Builder<T> addModule(Module module) {
Preconditions.checkNotNull(module);
modules.add(module);
return this;
}
public Builder<T> setConfigClass(Class<T> clazz) {
configurationClass = Optional.of(clazz);
return this;
}
public Builder<T> enableAutoConfig(String... basePackages) {
Preconditions.checkNotNull(basePackages.length > 0);
Preconditions.checkArgument(autoConfig == null, "autoConfig already enabled!");
autoConfig = new AutoConfig(basePackages);
return this;
}
public GuiceBundle<T> build() {
return new GuiceBundle<T>(autoConfig, modules, configurationClass);
}
}
public static <T extends Configuration> Builder<T> newBuilder() {
return new Builder<T>();
}
private GuiceBundle(AutoConfig autoConfig, List<Module> modules, Optional<Class<T>> configurationClass) {
Preconditions.checkNotNull(modules);
Preconditions.checkArgument(!modules.isEmpty());
this.modules = modules;
this.autoConfig = autoConfig;
this.configurationClass = configurationClass;
}
@Override
public void initialize(Bootstrap<?> bootstrap) {
container = new GuiceContainer();
JerseyContainerModule jerseyContainerModule = new JerseyContainerModule(container);
if (configurationClass.isPresent()) {
dropwizardEnvironmentModule = new DropwizardEnvironmentModule<T>(configurationClass.get());
} else {
dropwizardEnvironmentModule = new DropwizardEnvironmentModule<Configuration>(Configuration.class);
}
modules.add(jerseyContainerModule);
modules.add(dropwizardEnvironmentModule);
injector = Guice.createInjector(modules);
if (autoConfig != null) {
autoConfig.initialize(bootstrap, injector);
}
}
@Override
public void run(final T configuration, final Environment environment) {
container.setResourceConfig(environment.jersey().getResourceConfig());
environment.jersey().replace(new Function<ResourceConfig, ServletContainer>() {
@Nullable
@Override
public ServletContainer apply(ResourceConfig resourceConfig) {
return container;
}
});
environment.servlets().addFilter("Guice Filter", GuiceFilter.class);
setEnvironment(configuration, environment);
if (autoConfig != null) {
autoConfig.run(environment, injector);
}
}
@SuppressWarnings("unchecked")
private void setEnvironment(final T configuration, final Environment environment) {
dropwizardEnvironmentModule.setEnvironmentData(configuration, environment);
}
public Injector getInjector() {
return injector;
}
} |
package com.imcode.imcms.domain.dto;
import com.imcode.imcms.model.UserData;
import com.imcode.imcms.persistence.entity.User;
import imcode.server.LanguageMapper;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.Date;
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(exclude = {"password", "password2"}, callSuper = true)
public class UserFormData extends UserData {
private static final long serialVersionUID = 4260651400624470608L;
private Integer id;
private String login;
private String password;
private String password2;
private String firstName;
private String lastName;
private String title;
private String company;
private String address;
private String zip;
private String city;
private String province;
private String country;
private String langCode;
private String email;
private boolean active;
private Date createDate;
private Integer[] userPhoneNumberType;
private String[] userPhoneNumber;
private int[] roleIds;
private int[] userAdminRoleIds;
public UserFormData(UserData from) {
super(from);
}
public UserFormData(User from) {
super(from);
this.setCreateDate(from.getCreateDate());
this.setActive(from.isActive());
this.setLangCode(LanguageMapper.convert639_2to639_1(from.getLanguageIso639_2()));
}
} |
package tld.testmod.client.midi;
import javax.annotation.Nullable;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiMessage;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Transmitter;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import tld.testmod.ModLogger;
import tld.testmod.network.PacketDispatcher;
import tld.testmod.network.server.ActiveReceiverMessage;
public enum MidiUtils implements Receiver
{
INSTANCE;
static BiMap<Integer, BlockPos> playerIdUsingBlock = HashBiMap.create();
static IActiveNoteReceiver instrument;
static World world;
static BlockPos pos = null;
static IBlockState state;
static EntityPlayer player;
static EnumHand hand;
static EnumFacing facing;
static float hitX, hitY, hitZ;
static ItemStack stack = ItemStack.EMPTY;
public void setNoteReceiver(IActiveNoteReceiver instrumentIn, World worldIn, BlockPos posIn, @Nullable IBlockState stateIn, EntityPlayer playerIn, EnumHand handIn, @Nullable EnumFacing facingIn,
float hitXIn, float hitYIn, float hitZIn, ItemStack stackIn)
{
instrument = instrumentIn;
world = worldIn;
pos = posIn;
state = stateIn;
player = playerIn;
hand = handIn;
facing = facingIn;
hitX = hitXIn;
hitY = hitYIn;
hitZ = hitZIn;
stack = stackIn;
if (worldIn.isRemote)
{
MidiDevice device;
MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
for (int i = 0; i < infos.length; i++)
{
try
{
device = MidiSystem.getMidiDevice(infos[i]);
// does the device have any transmitters?
// if it does, add it to the device list
if (device.isOpen()) device.close();
ModLogger.info("%s, %d", infos[i], device.getMaxTransmitters());
if (device.getMaxTransmitters() != 0 && !(device instanceof Sequencer))
{
Transmitter trans = device.getTransmitter();
trans.setReceiver(getReceiver());
// open each device
device.open();
// if code gets this far without throwing an exception
// print a success message
ModLogger.info("%s was opened", device.getDeviceInfo());
}
} catch (MidiUnavailableException e)
{
ModLogger.error(e);
}
}
}
}
public void setNoteReceiver(IActiveNoteReceiver instrumentIn, World worldIn, BlockPos posIn, @Nullable IBlockState stateIn, EntityPlayer playerIn, EnumHand handIn, @Nullable EnumFacing facingIn,
float hitXIn, float hitYIn, float hitZIn)
{
setNoteReceiver(instrumentIn, worldIn, posIn, stateIn, playerIn, handIn, facingIn, hitXIn, hitYIn, hitZIn, ItemStack.EMPTY);
}
public void setNoteReceiver(IActiveNoteReceiver instrumentIn, World worldIn, EntityPlayer playerIn, EnumHand handIn, ItemStack stackIn)
{
setNoteReceiver(instrumentIn, worldIn, playerIn.getPosition(), null, playerIn, handIn, null, 0, 0, 0, stackIn);
}
private Receiver getReceiver()
{
return INSTANCE;
}
@Override
public void send(MidiMessage msg, long timeStamp)
{
byte[] message = msg.getMessage();
int command = msg.getStatus() & 0xF0;
int channel = msg.getStatus() & 0x0F;
boolean allChannels = true;
boolean sendNoteOff = false;
switch (command)
{
case ShortMessage.NOTE_OFF:
message[2] = 0;
break;
case ShortMessage.NOTE_ON:
break;
default:
return;
}
boolean channelFlag = allChannels ? true : channel == 1;
boolean noteOffFlag = sendNoteOff ? true : message[2] != 0;
if (pos != null && channelFlag && noteOffFlag)
{
// NOTE_ON | NOTE_OFF MIDI message [ (message & 0xF0 | channel & 0x0F), note, volume ]
ActiveReceiverMessage packet = new ActiveReceiverMessage(pos, player.getEntityId(), hand, message[1], message[2]);
PacketDispatcher.sendToServer(packet);
ModLogger.info(" msg: %x, %x, %x, %d", msg.getStatus(), message[1], message[2], timeStamp);
}
}
@Override
public void close()
{
pos = null;
stack = ItemStack.EMPTY;
}
public void notifyRemoved(World worldIn, BlockPos posIn)
{
if (pos != null && pos.equals(posIn))
{
ModLogger.info("ActiveNoteReceiver Removed: %s", posIn);
pos = null;
stack = ItemStack.EMPTY;
}
}
public void notifyRemoved(World worldIn, ItemStack stackIn)
{
if (stackIn.equals(stack) && stack.getMetadata() == stackIn.getMetadata())
{
ModLogger.info("ActiveNoteReceiver Removed: %s", stackIn.getDisplayName());
pos = null;
stack = ItemStack.EMPTY;
}
}
} |
package net.fortuna.ical4j.model.component;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.Date;
import net.fortuna.ical4j.model.DateList;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.TimeZone;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.parameter.Value;
import net.fortuna.ical4j.model.property.DtStart;
import net.fortuna.ical4j.model.property.RDate;
import net.fortuna.ical4j.model.property.RRule;
import net.fortuna.ical4j.model.property.TzOffsetFrom;
import net.fortuna.ical4j.model.property.TzOffsetTo;
import net.fortuna.ical4j.util.Dates;
import net.fortuna.ical4j.util.PropertyValidator;
import net.fortuna.ical4j.util.TimeZones;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* $Id$ [05-Apr-2004]
*
* Defines an iCalendar sub-component representing a timezone observance. Class made abstract such that only Standard
* and Daylight instances are valid.
* @author Ben Fortuna
*/
public abstract class Observance extends Component implements Comparable {
private static final long serialVersionUID = 2523330383042085994L;
/**
* one of 'standardc' or 'daylightc' MUST occur and each MAY occur more than once.
*/
public static final String STANDARD = "STANDARD";
/**
* Token for daylight observance.
*/
public static final String DAYLIGHT = "DAYLIGHT";
private transient Log log = LogFactory.getLog(Observance.class);
// TODO: clear cache when observance definition changes (??)
private Map onsets = new TreeMap();
private Date initialOnset = null;
/**
* Used for parsing times in a UTC date-time representation.
*/
private static final String UTC_PATTERN = "yyyyMMdd'T'HHmmss";
private static final DateFormat UTC_FORMAT = new SimpleDateFormat(
UTC_PATTERN);
static {
UTC_FORMAT.setTimeZone(TimeZone.getTimeZone(TimeZones.UTC_ID));
UTC_FORMAT.setLenient(false);
}
/* If this is set we have rrules. If we get a date after this rebuild onsets */
private Date onsetLimit;
private boolean rdatesCached = false;
/**
* Constructs a timezone observance with the specified name and no properties.
* @param name the name of this observance component
*/
protected Observance(final String name) {
super(name);
}
/**
* Constructor protected to enforce use of sub-classes from this library.
* @param name the name of the time type
* @param properties a list of properties
*/
protected Observance(final String name, final PropertyList properties) {
super(name, properties);
}
/**
* {@inheritDoc}
*/
public final void validate(final boolean recurse) throws ValidationException {
// From "4.8.3.3 Time Zone Offset From":
// Conformance: This property MUST be specified in a "VTIMEZONE"
// calendar component.
PropertyValidator.getInstance().assertOne(Property.TZOFFSETFROM,
getProperties());
// From "4.8.3.4 Time Zone Offset To":
// Conformance: This property MUST be specified in a "VTIMEZONE"
// calendar component.
PropertyValidator.getInstance().assertOne(Property.TZOFFSETTO,
getProperties());
/*
* ; the following are each REQUIRED, ; but MUST NOT occur more than once dtstart / tzoffsetto / tzoffsetfrom /
*/
PropertyValidator.getInstance().assertOne(Property.DTSTART,
getProperties());
/*
* ; the following are optional, ; and MAY occur more than once comment / rdate / rrule / tzname / x-prop
*/
if (recurse) {
validateProperties();
}
}
/**
* Returns the latest applicable onset of this observance for the specified date.
* @param date the latest date that an observance onset may occur
* @return the latest applicable observance date or null if there is no applicable observance onset for the
* specified date
*/
public final Date getLatestOnset(final Date date) {
if (initialOnset == null) {
try {
initialOnset = calculateOnset(((DtStart) getProperty(Property.DTSTART)).getDate());
} catch (ParseException e) {
log.error("Unexpected error calculating initial onset", e);
// XXX: is this correct?
return null;
}
}
// observance not applicable if date is before the effective date of this observance..
if (date.before(initialOnset)) {
return null;
}
final long start = System.currentTimeMillis();
if ((onsetLimit != null) && (date.after(onsetLimit))) {
onsets.clear();
rdatesCached = false;
}
Date onset = getCachedOnset(date);
final boolean cacheHit = onset != null;
if (onset == null) {
onset = initialOnset;
// collect all onsets for the purposes of caching..
final DateList cacheableOnsets = new DateList();
// Date nextOnset = null;
if (!rdatesCached) {
// check rdates for latest applicable onset..
final PropertyList rdates = getProperties(Property.RDATE);
for (final Iterator i = rdates.iterator(); i.hasNext();) {
final RDate rdate = (RDate) i.next();
for (final Iterator j = rdate.getDates().iterator(); j.hasNext();) {
try {
final Date rdateOnset = calculateOnset((Date) j.next());
if (!rdateOnset.after(date) && rdateOnset.after(onset)) {
onset = rdateOnset;
}
/*
* else if (rdateOnset.after(date) && rdateOnset.after(onset) && (nextOnset == null ||
* rdateOnset.before(nextOnset))) { nextOnset = rdateOnset; }
*/
cacheableOnsets.add(rdateOnset);
} catch (ParseException e) {
log.error("Unexpected error calculating onset", e);
}
}
}
rdatesCached = true;
}
// check recurrence rules for latest applicable onset..
final PropertyList rrules = getProperties(Property.RRULE);
Value dateType;
if (date instanceof DateTime) {
dateType = Value.DATE_TIME;
}
else {
dateType = Value.DATE;
}
for (final Iterator i = rrules.iterator(); i.hasNext();) {
final RRule rrule = (RRule) i.next();
// include future onsets to determine onset period..
final Calendar cal = Dates.getCalendarInstance(date);
cal.setTime(date);
cal.add(Calendar.YEAR, 10);
onsetLimit = Dates.getInstance(cal.getTime(), dateType);
final DateList recurrenceDates = rrule.getRecur().getDates(onset,
onsetLimit, dateType);
for (final Iterator j = recurrenceDates.iterator(); j.hasNext();) {
final Date rruleOnset = (Date) j.next();
if (!rruleOnset.after(date) && rruleOnset.after(onset)) {
onset = rruleOnset;
}
/*
* else if (rruleOnset.after(date) && rruleOnset.after(onset) && (nextOnset == null ||
* rruleOnset.before(nextOnset))) { nextOnset = rruleOnset; }
*/
cacheableOnsets.add(rruleOnset);
}
}
// cache onsets..
Collections.sort(cacheableOnsets);
Date cacheableOnset = null;
Date nextOnset = null;
for (final Iterator i = cacheableOnsets.iterator(); i.hasNext();) {
cacheableOnset = nextOnset;
nextOnset = (Date) i.next();
if (cacheableOnset != null) {
onsets.put(new Period(new DateTime(cacheableOnset),
new DateTime(nextOnset)), cacheableOnset);
}
}
// as we don't have an onset following the final onset, we must
// cache it with an arbitrary period length..
if (nextOnset != null) {
final Calendar finalOnsetPeriodEnd = Calendar.getInstance();
finalOnsetPeriodEnd.setTime(nextOnset);
finalOnsetPeriodEnd.add(Calendar.YEAR, 100);
onsets.put(new Period(new DateTime(nextOnset), new DateTime(
finalOnsetPeriodEnd.getTime())), nextOnset);
}
/*
* Period onsetPeriod = null; if (nextOnset != null) { onsetPeriod = new Period(new DateTime(onset), new
* DateTime(nextOnset)); } else { onsetPeriod = new Period(new DateTime(onset), new DateTime(date)); }
* onsets.put(onsetPeriod, onset);
*/
}
if (log.isTraceEnabled()) {
log.trace("Cache " + (cacheHit ? "hit" : "miss")
+ " - retrieval time: "
+ (System.currentTimeMillis() - start) + "ms");
}
return onset;
}
/**
* Returns a cached onset for the specified date.
* @param date
* @return a cached onset date or null if no cached onset is applicable for the specified date
*/
private Date getCachedOnset(final Date date) {
for (final Iterator i = onsets.entrySet().iterator(); i.hasNext();) {
final Map.Entry entry = (Map.Entry)i.next();
if (((Period)entry.getKey()).includes(date, Period.INCLUSIVE_START)) {
return (Date) entry.getValue();
}
}
return null;
}
/**
* Returns the mandatory dtstart property.
* @return the DTSTART property or null if not specified
*/
public final DtStart getStartDate() {
return (DtStart) getProperty(Property.DTSTART);
}
/**
* Returns the mandatory tzoffsetfrom property.
* @return the TZOFFSETFROM property or null if not specified
*/
public final TzOffsetFrom getOffsetFrom() {
return (TzOffsetFrom) getProperty(Property.TZOFFSETFROM);
}
/**
* Returns the mandatory tzoffsetto property.
* @return the TZOFFSETTO property or null if not specified
*/
public final TzOffsetTo getOffsetTo() {
return (TzOffsetTo) getProperty(Property.TZOFFSETTO);
}
/**
* {@inheritDoc}
*/
public final int compareTo(final Object arg0) {
return compareTo((Observance) arg0);
}
/**
* @param arg0 another observance instance
* @return a positve value if this observance starts earlier than the other,
* a negative value if it occurs later than the other, or zero if they start
* at the same time
*/
public final int compareTo(final Observance arg0) {
// TODO: sort by RDATE??
final DtStart dtStart = (DtStart) getProperty(Property.DTSTART);
final DtStart dtStart0 = (DtStart) arg0.getProperty(Property.DTSTART);
return dtStart.getDate().compareTo(dtStart0.getDate());
}
/**
* @param stream
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
log = LogFactory.getLog(Observance.class);
}
// private Date calculateOnset(DateProperty dateProperty) {
// return calculateOnset(dateProperty.getValue());
private Date calculateOnset(Date date) throws ParseException {
return calculateOnset(date.toString());
}
private Date calculateOnset(String dateStr) throws ParseException {
// Translate local onset into UTC time by parsing local time
// as GMT and adjusting by TZOFFSETFROM
// try {
java.util.Date utcOnset = null;
synchronized(UTC_FORMAT) {
utcOnset = UTC_FORMAT.parse(dateStr);
}
final long offset = getOffsetFrom().getOffset().getOffset();
return new DateTime(utcOnset.getTime() - offset);
// } catch (ParseException e) {
// throw new RuntimeException(e);
}
} |
package com.noveogroup.android.log;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The logger manager.
* <p/>
* To configure this logger manager you can include an
* {@code android-logger.properties} file in src directory.
* The format of configuration file is:
* <pre>
* # root logger configuration
* root=<level>:<tag>
* # package / class logger configuration
* logger.<package or class name>=<level>:<tag>
* </pre>
* You can use values of {@link Logger.Level} enum as level constants.
* For example, the following configuration will
* log all ERROR messages with tag "MyApplication" and all
* messages from classes {@code com.example.server.*} with
* tag "MyApplication-server":
* <pre>
* root=ERROR:MyApplication
* logger.com.example.server=DEBUG:MyApplication-server
* </pre>
* <p/>
*/
public final class LoggerManager {
private LoggerManager() {
throw new UnsupportedOperationException();
}
private static final Handler DEFAULT_HANDLER = new PatternHandler(Logger.Level.VERBOSE, "%logger", "%date %caller%n");
private static final Logger DEFAULT_LOGGER = new SimpleLogger(Logger.ROOT_LOGGER_NAME, DEFAULT_HANDLER);
private static final int MAX_LOG_TAG_LENGTH = 23;
private static final String PROPERTIES_NAME = "android-logger.properties";
private static final String CONF_ROOT = "root";
private static final String CONF_LOGGER = "logger.";
private static final Pattern CONF_LOGGER_REGEX = Pattern.compile("(.*?):(.*)");
private static void loadProperties(Properties properties) throws IOException {
InputStream inputStream = null;
try {
inputStream = LoggerManager.class.getClassLoader().getResourceAsStream(PROPERTIES_NAME);
if (inputStream != null) {
properties.load(inputStream);
} else {
inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(PROPERTIES_NAME);
if (inputStream != null) {
properties.load(inputStream);
}
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
private static Handler decodeHandler(String handlerString) {
// todo implement handler decoding from new format
Matcher matcher = CONF_LOGGER_REGEX.matcher(handlerString);
if (matcher.matches()) {
String levelString = matcher.group(1);
String tag = matcher.group(2);
if (tag.length() > 23) {
String trimmedTag = tag.substring(0, MAX_LOG_TAG_LENGTH);
DEFAULT_LOGGER.w("Android doesn't support tags %d characters longer. Tag '%s' will be trimmed to '%s'", MAX_LOG_TAG_LENGTH, tag, trimmedTag);
tag = trimmedTag;
}
try {
return new PatternHandler(Logger.Level.valueOf(levelString), tag, null);
} catch (IllegalArgumentException e) {
DEFAULT_LOGGER.w("Cannot parse '%s' as logging level. Only %s are allowed",
levelString, Arrays.toString(Logger.Level.values()));
return new PatternHandler(Logger.Level.VERBOSE, handlerString, null);
}
} else {
return new PatternHandler(Logger.Level.VERBOSE, handlerString, null);
}
}
private static Map<String, Handler> loadConfiguration() {
Map<String, Handler> handlerMap = new HashMap<String, Handler>();
// read properties file
Properties properties = new Properties();
try {
loadProperties(properties);
} catch (IOException e) {
DEFAULT_LOGGER.e(e, "Cannot configure logger from '%s'. Default configuration will be used", PROPERTIES_NAME);
handlerMap.put(null, DEFAULT_HANDLER);
return handlerMap;
}
// something is wrong if property file is empty
if (!properties.propertyNames().hasMoreElements()) {
DEFAULT_LOGGER.e("Logger configuration file is empty. Default configuration will be used");
handlerMap.put(null, DEFAULT_HANDLER);
return handlerMap;
}
// parse properties to logger map
for (Enumeration<?> names = properties.propertyNames(); names.hasMoreElements(); ) {
String propertyName = (String) names.nextElement();
String propertyValue = properties.getProperty(propertyName);
if (propertyName.equals(CONF_ROOT)) {
handlerMap.put(null, decodeHandler(propertyValue));
} else if (propertyName.startsWith(CONF_LOGGER)) {
String loggerName = propertyName.substring(CONF_LOGGER.length());
if (loggerName.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) {
loggerName = null;
}
handlerMap.put(loggerName, decodeHandler(propertyValue));
} else {
DEFAULT_LOGGER.e("unknown key '%s' in '%s' file", propertyName, PROPERTIES_NAME);
}
}
// logger map should have root logger (corresponding to "null" key)
if (!handlerMap.containsKey(null)) {
handlerMap.put(null, DEFAULT_HANDLER);
}
return handlerMap;
}
private static final Map<String, Handler> HANDLER_MAP = Collections.unmodifiableMap(loadConfiguration());
private static Handler findHandler(String name) {
String currentKey = null;
if (name != null) {
for (String key : HANDLER_MAP.keySet()) {
if (key != null && name.startsWith(key)) {
// check that key corresponds to a name of sub-package
if (key.length() >= name.length()
|| name.charAt(key.length()) == '.' || name.charAt(key.length()) == '$') {
// update current best matching key
if (currentKey == null || currentKey.length() < key.length()) {
currentKey = key;
}
}
}
}
}
Handler handler = HANDLER_MAP.get(currentKey);
return handler != null ? handler : DEFAULT_HANDLER;
}
private static final Map<String, Logger> LOGGER_CACHE = new WeakHashMap<String, Logger>();
/**
* Returns logger corresponding to the specified name.
*
* @param name the name.
* @return the {@link Logger} implementation.
*/
public static Logger getLogger(String name) {
Logger logger;
// try to find a logger in the cache
synchronized (LOGGER_CACHE) {
logger = LOGGER_CACHE.get(name);
}
// load logger from configuration
if (logger == null) {
logger = new SimpleLogger(name, findHandler(name));
synchronized (LOGGER_CACHE) {
LOGGER_CACHE.put(logger.getName(), logger);
}
}
// return logger
return logger;
}
/**
* Returns logger corresponding to the specified class.
*
* @param aClass the class.
* @return the {@link Logger} implementation.
*/
public static Logger getLogger(Class<?> aClass) {
return getLogger(aClass == null ? null : aClass.getName());
}
/**
* Returns logger corresponding to the caller class.
*
* @return the {@link Logger} implementation.
*/
public static Logger getLogger() {
return getLogger(Utils.getCallerClassName());
}
} |
package org.jfree.data.time.ohlc;
import java.io.Serializable;
import java.util.List;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.time.RegularTimePeriod;
import org.jfree.data.time.TimePeriodAnchor;
import org.jfree.data.xy.AbstractXYDataset;
import org.jfree.data.xy.OHLCDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.util.ObjectUtilities;
/**
* A collection of {@link OHLCSeries} objects.
*
* @since 1.0.4
*
* @see OHLCSeries
*/
public class OHLCSeriesCollection extends AbstractXYDataset
implements OHLCDataset, Serializable {
/** Storage for the data series. */
private List data;
private TimePeriodAnchor xPosition = TimePeriodAnchor.MIDDLE;
/**
* Creates a new instance of <code>OHLCSeriesCollection</code>.
*/
public OHLCSeriesCollection() {
this.data = new java.util.ArrayList();
}
/**
* Returns the position within each time period that is used for the X
* value when the collection is used as an {@link XYDataset}.
*
* @return The anchor position (never <code>null</code>).
*
* @since 1.0.11
*/
public TimePeriodAnchor getXPosition() {
return this.xPosition;
}
/**
* Sets the position within each time period that is used for the X values
* when the collection is used as an {@link XYDataset}, then sends a
* {@link DatasetChangeEvent} is sent to all registered listeners.
*
* @param anchor the anchor position (<code>null</code> not permitted).
*
* @since 1.0.11
*/
public void setXPosition(TimePeriodAnchor anchor) {
if (anchor == null) {
throw new IllegalArgumentException("Null 'anchor' argument.");
}
this.xPosition = anchor;
notifyListeners(new DatasetChangeEvent(this, this));
}
/**
* Adds a series to the collection and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param series the series (<code>null</code> not permitted).
*/
public void addSeries(OHLCSeries series) {
if (series == null) {
throw new IllegalArgumentException("Null 'series' argument.");
}
this.data.add(series);
series.addChangeListener(this);
fireDatasetChanged();
}
/**
* Returns the number of series in the collection.
*
* @return The series count.
*/
public int getSeriesCount() {
return this.data.size();
}
public OHLCSeries getSeries(int series) {
if ((series < 0) || (series >= getSeriesCount())) {
throw new IllegalArgumentException("Series index out of bounds");
}
return (OHLCSeries) this.data.get(series);
}
public Comparable getSeriesKey(int series) {
// defer argument checking
return getSeries(series).getKey();
}
public int getItemCount(int series) {
// defer argument checking
return getSeries(series).getItemCount();
}
/**
* Returns the x-value for a time period.
*
* @param period the time period (<code>null</code> not permitted).
*
* @return The x-value.
*/
protected synchronized long getX(RegularTimePeriod period) {
long result = 0L;
if (this.xPosition == TimePeriodAnchor.START) {
result = period.getFirstMillisecond();
}
else if (this.xPosition == TimePeriodAnchor.MIDDLE) {
result = period.getMiddleMillisecond();
}
else if (this.xPosition == TimePeriodAnchor.END) {
result = period.getLastMillisecond();
}
return result;
}
/**
* Returns the x-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The x-value.
*/
public double getXValue(int series, int item) {
OHLCSeries s = (OHLCSeries) this.data.get(series);
OHLCItem di = (OHLCItem) s.getDataItem(item);
RegularTimePeriod period = di.getPeriod();
return getX(period);
}
/**
* Returns the x-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The x-value.
*/
public Number getX(int series, int item) {
return new Double(getXValue(series, item));
}
/**
* Returns the y-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The y-value.
*/
public Number getY(int series, int item) {
OHLCSeries s = (OHLCSeries) this.data.get(series);
OHLCItem di = (OHLCItem) s.getDataItem(item);
return new Double(di.getYValue());
}
/**
* Returns the open-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The open-value.
*/
public double getOpenValue(int series, int item) {
OHLCSeries s = (OHLCSeries) this.data.get(series);
OHLCItem di = (OHLCItem) s.getDataItem(item);
return di.getOpenValue();
}
/**
* Returns the open-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The open-value.
*/
public Number getOpen(int series, int item) {
return new Double(getOpenValue(series, item));
}
/**
* Returns the close-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The close-value.
*/
public double getCloseValue(int series, int item) {
OHLCSeries s = (OHLCSeries) this.data.get(series);
OHLCItem di = (OHLCItem) s.getDataItem(item);
return di.getCloseValue();
}
/**
* Returns the close-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The close-value.
*/
public Number getClose(int series, int item) {
return new Double(getCloseValue(series, item));
}
/**
* Returns the high-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The high-value.
*/
public double getHighValue(int series, int item) {
OHLCSeries s = (OHLCSeries) this.data.get(series);
OHLCItem di = (OHLCItem) s.getDataItem(item);
return di.getHighValue();
}
/**
* Returns the high-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The high-value.
*/
public Number getHigh(int series, int item) {
return new Double(getHighValue(series, item));
}
/**
* Returns the low-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The low-value.
*/
public double getLowValue(int series, int item) {
OHLCSeries s = (OHLCSeries) this.data.get(series);
OHLCItem di = (OHLCItem) s.getDataItem(item);
return di.getLowValue();
}
/**
* Returns the low-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The low-value.
*/
public Number getLow(int series, int item) {
return new Double(getLowValue(series, item));
}
/**
* Returns <code>null</code> always, because this dataset doesn't record
* any volume data.
*
* @param series the series index (ignored).
* @param item the item index (ignored).
*
* @return <code>null</code>.
*/
public Number getVolume(int series, int item) {
return null;
}
/**
* Returns <code>Double.NaN</code> always, because this dataset doesn't
* record any volume data.
*
* @param series the series index (ignored).
* @param item the item index (ignored).
*
* @return <code>Double.NaN</code>.
*/
public double getVolumeValue(int series, int item) {
return Double.NaN;
}
/**
* Tests this instance for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof OHLCSeriesCollection)) {
return false;
}
OHLCSeriesCollection that = (OHLCSeriesCollection) obj;
if (!this.xPosition.equals(that.xPosition)) {
return false;
}
return ObjectUtilities.equal(this.data, that.data);
}
/**
* Returns a clone of this instance.
*
* @return A clone.
*
* @throws CloneNotSupportedException if there is a problem.
*/
public Object clone() throws CloneNotSupportedException {
OHLCSeriesCollection clone
= (OHLCSeriesCollection) super.clone();
clone.data = (List) ObjectUtilities.deepClone(this.data);
return clone;
}
} |
package com.sap.mentors.lemonaid.entities;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="mentors")
public class Mentor {
@Id
private String id;
private String fullName;
@ManyToOne private MentorStatus status;
private String jobTitle;
private String company;
@ManyToOne private RelationshipToSap relationshipToSap;
@ManyToOne private LineOfBusiness lineOfBusiness1;
@ManyToOne private LineOfBusiness lineOfBusiness2;
@ManyToOne private LineOfBusiness lineOfBusiness3;
@ManyToOne private Industry industry1;
@ManyToOne private Industry industry2;
@ManyToOne private Industry industry3;
@ManyToOne private SapSoftwareSolution sapExpertise1;
@ManyToOne private ExpertiseLevel sapExpertise1Level;
@ManyToOne private SapSoftwareSolution sapExpertise2;
@ManyToOne private ExpertiseLevel sapExpertise2Level;
@ManyToOne private SapSoftwareSolution sapExpertise3;
@ManyToOne private ExpertiseLevel sapExpertise3Level;
@ManyToOne private SoftSkill softSkill1;
@ManyToOne private SoftSkill softSkill2;
@ManyToOne private SoftSkill softSkill3;
@ManyToOne private SoftSkill softSkill4;
@ManyToOne private SoftSkill softSkill5;
@ManyToOne private SoftSkill softSkill6;
@Lob private String bio;
private String email1;
private String email2;
private int preferredEmail;
private String address;
private String city;
private String state;
private String zip;
@ManyToOne private Country country;
private String phone;
@ManyToOne private Region region;
private int shirtNumber;
private String shirtText;
@ManyToOne private Size shirtSize;
@ManyToOne private Gender shirtMF;
private String scnUrl;
private String twitterId;
private String linkedInUrl;
private String xingUrl;
private String facebookUrl;
private boolean interestInMentorCommunicationStrategy;
private boolean interestInMentorManagementModel;
private boolean interestInMentorMix;
private boolean interestInOtherIdeas;
private int hoursAvailable;
@ManyToOne private Region topicLeadRegion;
@ManyToOne private Topic topic1;
private String topic1Executive;
@ManyToOne private Topic topic2;
private String topic2Executive;
@ManyToOne private Topic topic3;
private String topic3Executive;
@ManyToOne private Topic topic4;
private String topic4Executive;
private boolean topicLeadInterest;
@ManyToOne private Topic topicInterest;
public Mentor() {}
public Mentor(
String id, String fullName, MentorStatus status,
String jobTitle, String company, RelationshipToSap relationshipToSap,
LineOfBusiness lineOfBusiness1, LineOfBusiness lineOfBusiness2, LineOfBusiness lineOfBusiness3,
Industry industry1, Industry industry2, Industry industry3,
SapSoftwareSolution sapExpertise1, ExpertiseLevel sapExpertise1Level, SapSoftwareSolution sapExpertise2, ExpertiseLevel sapExpertise2Level, SapSoftwareSolution sapExpertise3, ExpertiseLevel sapExpertise3Level,
SoftSkill softSkill1, SoftSkill softSkill2, SoftSkill softSkill3, SoftSkill softSkill4, SoftSkill softSkill5, SoftSkill softSkill6,
String bio,
String email1, String email2, int preferredEmail,
String address, String city, String state, String zip, Country country, String phone,
Region region,
int shirtNumber, String shirtText, Size shirtSize, Gender shirtMF,
String scnUrl, String twitterId, String linkedInUrl, String xingUrl, String facebookUrl,
boolean interestInMentorCommunicationStrategy, boolean interestInMentorManagementModel, boolean interestInMentorMix, boolean interestInOtherIdeas, int hoursAvailable,
Region topicLeadRegion, Topic topic1, String topic1Executive, Topic topic2, String topic2Executive, Topic topic3, String topic3Executive, Topic topic4, String topic4Executive, boolean topicLeadInterest, Topic topicInterest)
{
this.id = id;
this.fullName = fullName;
this.status = status;
this.jobTitle = jobTitle;
this.company = company;
this.relationshipToSap = relationshipToSap;
this.lineOfBusiness1 = lineOfBusiness1;
this.lineOfBusiness2 = lineOfBusiness2;
this.lineOfBusiness3 = lineOfBusiness3;
this.industry1 = industry1;
this.industry2 = industry2;
this.industry3 = industry3;
this.sapExpertise1 = sapExpertise1;
this.sapExpertise1Level = sapExpertise1Level;
this.sapExpertise2 = sapExpertise2;
this.sapExpertise2Level = sapExpertise2Level;
this.sapExpertise3 = sapExpertise3;
this.sapExpertise3Level = sapExpertise3Level;
this.softSkill1 = softSkill1;
this.softSkill2 = softSkill2;
this.softSkill3 = softSkill3;
this.softSkill4 = softSkill4;
this.softSkill5 = softSkill5;
this.softSkill6 = softSkill6;
this.bio = bio;
this.email1 = email1;
this.email2 = email2;
this.preferredEmail = 1;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.country = country;
this.phone = phone;
this.region = region;
this.shirtNumber = shirtNumber;
this.shirtText = shirtText;
this.shirtSize = shirtSize;
this.shirtMF = shirtMF;
this.scnUrl = scnUrl;
this.twitterId = twitterId;
this.linkedInUrl = linkedInUrl;
this.xingUrl = xingUrl;
this.facebookUrl = facebookUrl;
this.interestInMentorCommunicationStrategy = interestInMentorCommunicationStrategy;
this.interestInMentorManagementModel = interestInMentorManagementModel;
this.interestInMentorMix = interestInMentorMix;
this.interestInOtherIdeas = interestInOtherIdeas;
this.hoursAvailable = hoursAvailable;
this.topicLeadRegion = topicLeadRegion;
this.topic1 = topic1;
this.topic1Executive = topic1Executive;
this.topic2 = topic2;
this.topic2Executive = topic2Executive;
this.topic3 = topic3;
this.topic3Executive = topic3Executive;
this.topic4 = topic4;
this.topic4Executive = topic4Executive;
this.topicLeadInterest = topicLeadInterest;
this.topicInterest = topicInterest;
}
@Override
public String toString() {
return String.format(
"Mentor[id=%d, fullName='%s']",
id, fullName);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public MentorStatus getStatus() {
return status;
}
public void setStatus(MentorStatus status) {
this.status = status;
}
public String getStatusId() {
return status.getId();
}
public void setStatusId(String statusId) {
status = new MentorStatus(statusId);
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public RelationshipToSap getRelationshipToSap() {
return relationshipToSap;
}
public void setRelationshipToSap(RelationshipToSap relationshipToSap) {
this.relationshipToSap = relationshipToSap;
}
public LineOfBusiness getLineOfBusiness1() {
return lineOfBusiness1;
}
public void setLineOfBusiness1(LineOfBusiness lineOfBusiness1) {
this.lineOfBusiness1 = lineOfBusiness1;
}
public LineOfBusiness getLineOfBusiness2() {
return lineOfBusiness2;
}
public void setLineOfBusiness2(LineOfBusiness lineOfBusiness2) {
this.lineOfBusiness2 = lineOfBusiness2;
}
public LineOfBusiness getLineOfBusiness3() {
return lineOfBusiness3;
}
public void setLineOfBusiness3(LineOfBusiness lineOfBusiness3) {
this.lineOfBusiness3 = lineOfBusiness3;
}
public Industry getIndustry1() {
return industry1;
}
public void setIndustry1(Industry industry1) {
this.industry1 = industry1;
}
public Industry getIndustry2() {
return industry2;
}
public void setIndustry2(Industry industry2) {
this.industry2 = industry2;
}
public Industry getIndustry3() {
return industry3;
}
public void setIndustry3(Industry industry3) {
this.industry3 = industry3;
}
public SapSoftwareSolution getSapExpertise1() {
return sapExpertise1;
}
public void setSapExpertise1(SapSoftwareSolution sapExpertise1) {
this.sapExpertise1 = sapExpertise1;
}
public ExpertiseLevel getSapExpertise1Level() {
return sapExpertise1Level;
}
public void setSapExpertise1Level(ExpertiseLevel sapExpertise1Level) {
this.sapExpertise1Level = sapExpertise1Level;
}
public SapSoftwareSolution getSapExpertise2() {
return sapExpertise2;
}
public void setSapExpertise2(SapSoftwareSolution sapExpertise2) {
this.sapExpertise2 = sapExpertise2;
}
public ExpertiseLevel getSapExpertise2Level() {
return sapExpertise2Level;
}
public void setSapExpertise2Level(ExpertiseLevel sapExpertise2Level) {
this.sapExpertise2Level = sapExpertise2Level;
}
public SapSoftwareSolution getSapExpertise3() {
return sapExpertise3;
}
public void setSapExpertise3(SapSoftwareSolution sapExpertise3) {
this.sapExpertise3 = sapExpertise3;
}
public ExpertiseLevel getSapExpertise3Level() {
return sapExpertise3Level;
}
public void setSapExpertise3Level(ExpertiseLevel sapExpertise3Level) {
this.sapExpertise3Level = sapExpertise3Level;
}
public SoftSkill getSoftSkill1() {
return softSkill1;
}
public void setSoftSkill1(SoftSkill softSkill1) {
this.softSkill1 = softSkill1;
}
public SoftSkill getSoftSkill2() {
return softSkill2;
}
public void setSoftSkill2(SoftSkill softSkill2) {
this.softSkill2 = softSkill2;
}
public SoftSkill getSoftSkill3() {
return softSkill3;
}
public void setSoftSkill3(SoftSkill softSkill3) {
this.softSkill3 = softSkill3;
}
public SoftSkill getSoftSkill4() {
return softSkill4;
}
public void setSoftSkill4(SoftSkill softSkill4) {
this.softSkill4 = softSkill4;
}
public SoftSkill getSoftSkill5() {
return softSkill5;
}
public void setSoftSkill5(SoftSkill softSkill5) {
this.softSkill5 = softSkill5;
}
public SoftSkill getSoftSkill6() {
return softSkill6;
}
public void setSoftSkill6(SoftSkill softSkill6) {
this.softSkill6 = softSkill6;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public String getEmail1() {
return email1;
}
public void setEmail1(String email1) {
this.email1 = email1;
}
public String getEmail2() {
return email2;
}
public void setEmail2(String email2) {
this.email2 = email2;
}
public int getPreferredEmail() {
return preferredEmail;
}
public void setPreferredEmail(int preferredEmail) {
this.preferredEmail = preferredEmail;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public String getCountryId() {
return country.getId();
}
public void setCountryId(String countryId) {
country = new Country(countryId);
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public String getScnUrl() {
return scnUrl;
}
public void setScnUrl(String scnUrl) {
this.scnUrl = scnUrl;
}
public String getTwitterId() {
return twitterId;
}
public void setTwitterId(String twitterId) {
this.twitterId = twitterId;
}
public String getLinkedInUrl() {
return linkedInUrl;
}
public void setLinkedInUrl(String linkedInUrl) {
this.linkedInUrl = linkedInUrl;
}
public String getXingUrl() {
return xingUrl;
}
public void setXingUrl(String xingUrl) {
this.xingUrl = xingUrl;
}
public String getFacebookUrl() {
return facebookUrl;
}
public void setFacebookUrl(String facebookUrl) {
this.facebookUrl = facebookUrl;
}
public int getShirtNumber() {
return shirtNumber;
}
public void setShirtNumber(int shirtNumber) {
this.shirtNumber = shirtNumber;
}
public String getShirtText() {
return shirtText;
}
public void setShirtText(String shirtText) {
this.shirtText = shirtText;
}
public Size getShirtSize() {
return shirtSize;
}
public void setShirtSize(Size shirtSize) {
this.shirtSize = shirtSize;
}
public Gender getShirtMF() {
return shirtMF;
}
public void setShirtMF(Gender shirtMF) {
this.shirtMF = shirtMF;
}
public boolean isInterestInMentorCommunicationStrategy() {
return interestInMentorCommunicationStrategy;
}
public void setInterestInMentorCommunicationStrategy(boolean interestInMentorCommunicationStrategy) {
this.interestInMentorCommunicationStrategy = interestInMentorCommunicationStrategy;
}
public boolean isInterestInMentorManagementModel() {
return interestInMentorManagementModel;
}
public void setInterestInMentorManagementModel(boolean interestInMentorManagementModel) {
this.interestInMentorManagementModel = interestInMentorManagementModel;
}
public boolean isInterestInMentorMix() {
return interestInMentorMix;
}
public void setInterestInMentorMix(boolean interestInMentorMix) {
this.interestInMentorMix = interestInMentorMix;
}
public boolean isInterestInOtherIdeas() {
return interestInOtherIdeas;
}
public void setInterestInOtherIdeas(boolean interestInOtherIdeas) {
this.interestInOtherIdeas = interestInOtherIdeas;
}
public int getHoursAvailable() {
return hoursAvailable;
}
public void setHoursAvailable(int hoursAvailable) {
this.hoursAvailable = hoursAvailable;
}
public Region getTopicLeadRegion() {
return topicLeadRegion;
}
public void setTopicLeadRegion(Region topicLeadRegion) {
this.topicLeadRegion = topicLeadRegion;
}
public Topic getTopic1() {
return topic1;
}
public void setTopic1(Topic topic1) {
this.topic1 = topic1;
}
public String getTopic1Executive() {
return topic1Executive;
}
public void setTopic1Executive(String topic1Executive) {
this.topic1Executive = topic1Executive;
}
public Topic getTopic2() {
return topic2;
}
public void setTopic2(Topic topic2) {
this.topic2 = topic2;
}
public String getTopic2Executive() {
return topic2Executive;
}
public void setTopic2Executive(String topic2Executive) {
this.topic2Executive = topic2Executive;
}
public Topic getTopic3() {
return topic3;
}
public void setTopic3(Topic topic3) {
this.topic3 = topic3;
}
public String getTopic3Executive() {
return topic3Executive;
}
public void setTopic3Executive(String topic3Executive) {
this.topic3Executive = topic3Executive;
}
public Topic getTopic4() {
return topic4;
}
public void setTopic4(Topic topic4) {
this.topic4 = topic4;
}
public String getTopic4Executive() {
return topic4Executive;
}
public void setTopic4Executive(String topic4Executive) {
this.topic4Executive = topic4Executive;
}
public boolean isTopicLeadInterest() {
return topicLeadInterest;
}
public void setTopicLeadInterest(boolean topicLeadInterest) {
this.topicLeadInterest = topicLeadInterest;
}
public Topic getTopicInterest() {
return topicInterest;
}
public void setTopicInterest(Topic topicInterest) {
this.topicInterest = topicInterest;
}
public String getLineOfBusiness1Id() {
if (this.getLineOfBusiness1() == null) {
return null;
} else {
return this.getLineOfBusiness1().getId();
}
}
public void setLineOfBusiness1Id(String lineOfBusiness1Id) {
this.lineOfBusiness1 = new LineOfBusiness(lineOfBusiness1Id);
}
public String getLineOfBusiness2Id() {
if (this.getLineOfBusiness2() == null) {
return null;
} else {
return this.getLineOfBusiness2().getId();
}
}
public void setLineOfBusiness2Id(String lineOfBusiness2Id) {
this.lineOfBusiness2 = new LineOfBusiness(lineOfBusiness2Id);
}
public String getLineOfBusiness3Id() {
if (this.getLineOfBusiness3() == null) {
return null;
} else {
return this.getLineOfBusiness3().getId();
}
}
public void setLineOfBusiness3Id(String lineOfBusiness3Id) {
this.lineOfBusiness3 = new LineOfBusiness(lineOfBusiness3Id);
}
public String getIndustry1Id() {
if (this.getIndustry1() == null) {
return null;
} else {
return this.getIndustry1().getId();
}
}
public void setIndustry1Id(String industry1Id) {
this.industry1 = new Industry(industry1Id);
}
public String getIndustry2Id() {
if (this.getIndustry2() == null) {
return null;
} else {
return this.getIndustry2().getId();
}
}
public void setIndustry2Id(String industry2Id) {
this.industry2 = new Industry(industry2Id);
}
public String getIndustry3Id() {
if (this.getIndustry3() == null) {
return null;
} else {
return this.getIndustry3().getId();
}
}
public void setIndustry3Id(String industry3Id) {
this.industry3 = new Industry(industry3Id);
}
public String getSapExpertise1Id() {
if (this.getSapExpertise1() == null) {
return null;
} else {
return this.getSapExpertise1().getId();
}
}
public void setSapExpertise1Id(String sapExpertise1Id) {
this.sapExpertise1 = new SapSoftwareSolution(sapExpertise1Id);
}
public String getSapExpertise1LevelId() {
if (this.getSapExpertise1Level() == null) {
return null;
} else {
return this.getSapExpertise1Level().getId();
}
}
public void setSapExpertise1LevelId(String sapExpertise1LevelId) {
this.sapExpertise1Level = new ExpertiseLevel(sapExpertise1LevelId);
}
public String getSapExpertise2Id() {
if (this.getSapExpertise2() == null) {
return null;
} else {
return this.getSapExpertise2().getId();
}
}
public void setSapExpertise2Id(String sapExpertise2Id) {
this.sapExpertise2 = new SapSoftwareSolution(sapExpertise2Id);
}
public String getSapExpertise2LevelId() {
if (this.getSapExpertise2Level() == null) {
return null;
} else {
return this.getSapExpertise2Level().getId();
}
}
public void setSapExpertise2LevelId(String sapExpertise2LevelId) {
this.sapExpertise2Level = new ExpertiseLevel(sapExpertise2LevelId);
}
public String getSapExpertise3Id() {
if (this.getSapExpertise3() == null) {
return null;
} else {
return this.getSapExpertise3().getId();
}
}
public void setSapExpertise3Id(String sapExpertise3Id) {
this.sapExpertise3 = new SapSoftwareSolution(sapExpertise3Id);
}
public String getSapExpertise3LevelId() {
if (this.getSapExpertise3Level() == null) {
return null;
} else {
return this.getSapExpertise3Level().getId();
}
}
public void setSapExpertise3LevelId(String sapExpertise3LevelId) {
this.sapExpertise3Level = new ExpertiseLevel(sapExpertise3LevelId);
}
public String getSoftSkill1Id() {
if (this.getSoftSkill1() == null) {
return null;
} else {
return this.getSoftSkill1().getId();
}
}
public void setSoftSkill1Id(String softSkill1Id) {
this.softSkill1 = new SoftSkill(softSkill1Id);
}
public String getSoftSkill2Id() {
if (this.getSoftSkill2() == null) {
return null;
} else {
return this.getSoftSkill2().getId();
}
}
public void setSoftSkill2Id(String softSkill2Id) {
this.softSkill2 = new SoftSkill(softSkill2Id);
}
public String getSoftSkill3Id() {
if (this.getSoftSkill3() == null) {
return null;
} else {
return this.getSoftSkill3().getId();
}
}
public void setSoftSkill3Id(String softSkill3Id) {
this.softSkill3 = new SoftSkill(softSkill3Id);
}
public String getSoftSkill4Id() {
if (this.getSoftSkill4() == null) {
return null;
} else {
return this.getSoftSkill4().getId();
}
}
public void setSoftSkill4Id(String softSkill4Id) {
this.softSkill4 = new SoftSkill(softSkill4Id);
}
public String getSoftSkill5Id() {
if (this.getSoftSkill5() == null) {
return null;
} else {
return this.getSoftSkill5().getId();
}
}
public void setSoftSkill5Id(String softSkill5Id) {
this.softSkill5 = new SoftSkill(softSkill5Id);
}
public String getSoftSkill6Id() {
if (this.getSoftSkill6() == null) {
return null;
} else {
return this.getSoftSkill6().getId();
}
}
public void setSoftSkill6Id(String softSkill6Id) {
this.softSkill6 = new SoftSkill(softSkill6Id);
}
public String getRegionId() {
if (this.getRegion() == null) {
return null;
} else {
return this.getRegion().getId();
}
}
public void setRegionId(String regionId) {
this.region = new Region(regionId);
}
public String getShirtSizeId() {
if (this.getShirtSize() == null) {
return null;
} else {
return this.getShirtSize().getId();
}
}
public void setShirtSizeId(String shirtSizeId) {
this.shirtSize = new Size(shirtSizeId);
}
public String getShirtMFId() {
if (this.getShirtMF() == null) {
return null;
} else {
return this.getShirtMF().getId();
}
}
public void setShirtMFId(String shirtMFId) {
this.shirtMF = new Gender(shirtMFId);
}
public String getTopicLeadRegionId() {
if (this.getTopicLeadRegion() == null) {
return null;
} else {
return this.getTopicLeadRegion().getId();
}
}
public void setTopicLeadRegionId(String topicLeadRegionId) {
this.topicLeadRegion = new Region(topicLeadRegionId);
}
public String getTopic1Id() {
if (this.getTopic1() == null) {
return null;
} else {
return this.getTopic1().getId();
}
}
public void setTopic1Id(String topic1Id) {
this.topic1 = new Topic(topic1Id);
}
public String getTopic2Id() {
if (this.getTopic2() == null) {
return null;
} else {
return this.getTopic2().getId();
}
}
public void setTopic2Id(String topic2Id) {
this.topic2 = new Topic(topic2Id);
}
public String getTopic3Id() {
if (this.getTopic3() == null) {
return null;
} else {
return this.getTopic3().getId();
}
}
public void setTopic3Id(String topic3Id) {
this.topic3 = new Topic(topic3Id);
}
public String getTopic4Id() {
if (this.getTopic4() == null) {
return null;
} else {
return this.getTopic4().getId();
}
}
public void setTopic4Id(String topic4Id) {
this.topic4 = new Topic(topic4Id);
}
public String getTopicInterestId() {
if (this.getTopicInterest() == null) {
return null;
} else {
return this.getTopicInterest().getId();
}
}
public void setTopicInterestId(String topicInterestId) {
this.topicInterest = new Topic(topicInterestId);
}
} |
import hudson.model.FreeStyleProject;
import hudson.model.Hudson;
import hudson.tasks.BuildTrigger;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.jvnet.hudson.test.HudsonTestCase;
/**
* @author KevinV
*
*/
public class DownstreamDependencyTest extends HudsonTestCase {
@Override
@Before
public void setUp() throws Exception {
super.setUp();
}
@Test
public void testDownstreamDependency() throws IOException {
String proj1 = "Proj1";
String proj2 = "Proj2";
FreeStyleProject project1 = createFreeStyleProject(proj1);
FreeStyleProject project2 = createFreeStyleProject(proj2);
DownstreamDependency myDD = new DownstreamDependency(project1, project2);
assertEquals("Upstream project should be " + proj1, project1, myDD.getUpstreamProject());
assertEquals("Downstream project should be " + proj2, project2, myDD.getDownstreamProject());
}
@Test
public void testShouldTriggerBuild() throws Exception {
String proj1 = "Proj1";
String proj2 = "Proj2";
String proj3 = "Proj3";
FreeStyleProject project1 = createFreeStyleProject(proj1);
FreeStyleProject project2 = createFreeStyleProject(proj2);
FreeStyleProject project3 = createFreeStyleProject(proj3);
// Add TEST_PROJECT2 as a Manually executed pipeline project
// Add TEST_PROJECT3 as a Post-build action -> build other projects
project1.getPublishersList().add(new BuildPipelineTrigger(proj2));
project1.getPublishersList().add(new BuildTrigger(proj3, true));
// Important; we must do this step to ensure that the dependency graphs are updated
Hudson.getInstance().rebuildDependencyGraph();
// Build project1 and wait until completion
buildAndAssertSuccess(project1);
waitUntilNoActivity();
assertNull(project2.getLastBuild());
assertNotNull(project3.getLastBuild());
}
} |
package ca.corefacility.bioinformatics.irida.ria.integration;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import ca.corefacility.bioinformatics.irida.web.controller.test.listeners.IntegrationUITestListener;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseTearDown;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import ca.corefacility.bioinformatics.irida.config.data.IridaApiJdbcDataSourceConfig;
import ca.corefacility.bioinformatics.irida.config.data.MongoDatasourceConfig;
import ca.corefacility.bioinformatics.irida.config.services.IridaApiPropertyPlaceholderConfig;
import ca.corefacility.bioinformatics.irida.ria.integration.pages.LoginPage;
/**
* Common functionality to all UI integration tests.
*/
@ActiveProfiles("it")
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = {IridaApiJdbcDataSourceConfig.class,
IridaApiPropertyPlaceholderConfig.class, MongoDatasourceConfig.class})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class})
@DatabaseTearDown("classpath:/ca/corefacility/bioinformatics/irida/test/integration/TableReset.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class AbstractIridaUIITChromeDriver {
private static final Logger logger = LoggerFactory.getLogger(AbstractIridaUIITChromeDriver.class);
public static final int DRIVER_TIMEOUT_IN_SECONDS = IntegrationUITestListener.DRIVER_TIMEOUT_IN_SECONDS;
private static boolean isSingleTest = false;
@Rule
public ScreenshotOnFailureWatcher watcher = new ScreenshotOnFailureWatcher();
@Rule
public MongoDbRule mongoDbRule = newMongoDbRule().defaultSpringMongoDb("test");
/**
* Code to execute before *each* test.
*/
@Before
public void setUpTest() {
// logout before everything else.
LoginPage.logout(driver());
}
/**
* Code to execute after *each* test.
*/
@After
public void tearDown() {
// NOTE: DO **NOT** log out in this method. This method happens because
// the @After method happens immediately after test failure, but before
// the @Rule TestWatcher checks the outcome of the test. We want to take
// a screenshot of the application state **before** logging out.
}
/**
* Code to execute *once* after the class is finished.
*/
@AfterClass
public static void destroy() {
if (isSingleTest) {
logger.debug("Closing ChromeDriver for single test class.");
IntegrationUITestListener.stopWebDriver();
}
}
/**
* Get a reference to the {@link WebDriver} used in the tests.
* @return the instance of {@link WebDriver} used in the tests.
*/
public static WebDriver driver() {
if (IntegrationUITestListener.driver() == null) {
logger.debug("Starting ChromeDriver for a single test class.");
System.setProperty("webdriver.chrome.driver", "src/main/webapp/node_modules/chromedriver/lib/chromedriver/chromedriver");
isSingleTest = true;
IntegrationUITestListener.startWebDriver();
}
return IntegrationUITestListener.driver();
}
/**
* Simple test watcher for taking screenshots of the browser on failure.
*
*/
private static class ScreenshotOnFailureWatcher extends TestWatcher {
private static final Logger logger = LoggerFactory.getLogger(ScreenshotOnFailureWatcher.class);
/**
* {@inheritDoc}
*/
@Override
protected void failed(final Throwable t, final Description description) {
logger.debug("Handling exception of type [" + t.getClass() + "], taking screenshot.");
final TakesScreenshot takesScreenshot = (TakesScreenshot) driver();
final Path screenshot = Paths.get(takesScreenshot.getScreenshotAs(OutputType.FILE).toURI());
try {
final Path destination = Files.createTempFile(
"irida-" + description.getTestClass().getSimpleName() + "#" + description.getMethodName(),
".png");
Files.move(screenshot, destination, StandardCopyOption.REPLACE_EXISTING);
logger.info("Screenshot deposited at: [" + destination.toString() + "]");
} catch (final IOException e) {
logger.error("Unable to write screenshot out.", e);
}
}
}
} |
package com.sri.ai.praise.lbp.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.common.annotations.Beta;
import com.sri.ai.expresso.api.Expression;
import com.sri.ai.expresso.helper.Expressions;
import com.sri.ai.grinder.api.RewritingProcess;
import com.sri.ai.grinder.helper.GrinderUtil;
import com.sri.ai.grinder.helper.Justification;
import com.sri.ai.grinder.helper.Trace;
import com.sri.ai.grinder.helper.concurrent.BranchRewriteTask;
import com.sri.ai.grinder.helper.concurrent.RewriteOnBranch;
import com.sri.ai.grinder.library.Disequality;
import com.sri.ai.grinder.library.Equality;
import com.sri.ai.grinder.library.FunctorConstants;
import com.sri.ai.grinder.library.StandardizedApartFrom;
import com.sri.ai.grinder.library.boole.ForAll;
import com.sri.ai.grinder.library.boole.Implication;
import com.sri.ai.grinder.library.boole.Not;
import com.sri.ai.grinder.library.controlflow.IfThenElse;
import com.sri.ai.grinder.library.equality.CheapDisequalityModule;
import com.sri.ai.grinder.library.equality.cardinality.CardinalityUtil;
import com.sri.ai.grinder.library.set.Sets;
import com.sri.ai.grinder.library.set.extensional.ExtensionalSet;
import com.sri.ai.grinder.library.set.intensional.IntensionalSet;
import com.sri.ai.grinder.library.set.tuple.Tuple;
import com.sri.ai.praise.LPIUtil;
import com.sri.ai.praise.lbp.LBPRewriter;
import com.sri.ai.util.Util;
/**
* Default implementation of {@link LBPRewriter#R_set_diff}.
*
* @author oreilly
*
*/
@Beta
public class SetDifference extends AbstractLBPHierarchicalRewriter implements LBPRewriter {
private static final Expression _emptySet = ExtensionalSet.makeEmptySetExpression();
public SetDifference() {
}
@Override
public String getName() {
return R_set_diff;
}
/**
* @see LBPRewriter#R_set_diff
*/
@Override
public Expression rewriteAfterBookkeeping(Expression expression, RewritingProcess process) {
// Assert input arguments
// an expression of the form: 'S1 \ S2'.
if (!expression.hasFunctor(FunctorConstants.SET_DIFFERENCE) || expression.numberOfArguments() != 2) {
throw new IllegalArgumentException("Invalid input argument expression:"+expression);
}
Expression set1 = expression.get(0);
Expression set2 = expression.get(1);
if (Justification.isEnabled()) {
Justification.log(Expressions.apply(FunctorConstants.SET_DIFFERENCE, set1, set2));
}
Expression result = null;
// Cases:
if (IfThenElse.isIfThenElse(set1)) {
// Externalizes Conditionals
// if S1 is 'if C then Alpha else Beta'
// return R_basic(if C then R_set_diff(Alpha \ S2) else
// R_set_diff(Beta \ S2))
result = rewriteS1Conditional(set1, set2, process);
}
else if (IfThenElse.isIfThenElse(set2)) {
// Externalizes Conditionals
// if S2 is 'if C then Alpha else Beta'
// return R_basic(if C then R_set_diff(S1 \ Alpha) else
// R_set_diff(S1 \ Beta))
result = rewriteS2Conditional(set1, set2, process);
}
else if (set1.equals(_emptySet) || (isUnion(set1) && set1.numberOfArguments() == 0)) {
// ALBP-122: ensure logic is short-circuited if S1 is empty.
result = _emptySet;
}
else if (set2.equals(_emptySet) || (isUnion(set2) && set2.numberOfArguments() == 0)) {
// if S2 is the empty set
result = set1;
}
else if (isUnionOfUniSets(set1)
&& (Sets.isUniSet(set2) || isUnion(set2))) {
// if S1 is S11 union S1rest, where S1i and S2 are unisets
// return R_set_diff(S11 \ S2) union R_set_diff(S1rest \ S2)
result = rewriteS1UnionUniSets(set1, set2, process);
}
else if (isUnion(set2) && Sets.isSet(set1) && isUnionOfSets(set2)) {
// if S2 is S21 union S2rest, where S1 and S2i are sets
// return R_set_diff(R_set_diff(S1 \ S21) \ S2rest)
result = rewriteS2UnionUniSets(set1, set2, process);
}
else if (isUnionOfMultiSetsOrSingletons(set1) && Sets.isSingletonExtensionalSet(set2)) {
// if S1 is S11 union S1rest, where each S1i is a multiset
// guaranteed to have unique elements,
// or a singleton, and S2 is a singleton { b }
// return
// R_basic(if R_in(b in S11)
// then R_set_diff(S11 \ S2) union S1rest
// else S11 union R_set_diff(S1rest \ S2))
result = rewriteS1UnionMultiSetsOrSingletons(set1, set2, process);
}
else if (Sets.isExtensionalMultiSet(set1) && Sets.isSingletonExtensionalSet(set2)) {
// if S1 is {{a1,...,an}} and S2 is { b }
// return R_DifferenceOfExtensionalAndExtensionalSet({{a1,...,an}},
// {b}, 1, 1)
result = rewriteS1ExtensionalMultiSet(set1, set2, process);
}
else if (Sets.isIntensionalMultiSet(set1) && Sets.isSingletonExtensionalSet(set2)) {
// if S1 is {{ Alpha | C }}_I and S2 is { b }
// {{ Alpha' | C' }}_I' <- standardize {{ Alpha | C}}_I apart from {b}
// C'' <- R_formula_simplification(C' and not Alpha' = b) with cont. variables extended by I'
// return R_basic({{ Alpha' | C'' }}_I')
result = rewriteS1IntensionalMultiSet(set1, set2, process);
}
else if (Sets.isMultiSet(set1) && Sets.isExtensionalUniSet(set2)) {
// if S1 is a multiset and S2 is {b1, ..., bm}
// return R_set_diff(R_set_diff(S1, {b1}), {b2,...,bm})
result = rewriteS1MultiSetS2ExtensionalUniSet(set1, set2, process);
}
else if (Sets.isMultiSet(set1) && isUnion(set2)) {
// if S1 is a multiset and S2 is S21 union ... union S2m
// return R_set_diff(R_set_diff(S1, S21), S22 union ... union S2m)
result = rewriteS1MultiSetS2Union(set1, set2, process);
}
else if (Sets.isExtensionalUniSet(set1)
&& Sets.isExtensionalUniSet(set2)) {
// if S1 is {a1,...,an} and S2 is {b1,...,bm}
// return R_DifferenceOfExtensionalAndExtensionalSet({a1,...,an},
// {b1,...,bm}, 1, 1)
result = rewriteS1andS2ExtensionalUniSets(set1, set2, process);
}
else if (Sets.isIntensionalUniSet(set1)
&& Sets.isExtensionalUniSet(set2)) {
// if S1 is { Alpha | C }_I and S2 is {b1,...,bm}
// { Alpha' | C' }_I' <- standardize { Alpha | C }_I apart from {b1,...,bm}
// C'' <- R_formula_implification(C' and not (Disjunction_i Alpha' = b_i)) with cont. variables extended by I'
// return R_basic({ Alpha' | C'' }_I')
result = rewriteS1IntensionalS2ExtensionalUniSets(set1, set2, process);
}
else if (Sets.isIntensionalUniSet(set1)
&& Sets.isIntensionalUniSet(set2)) {
// if S1 is { Alpha | C }_I and S2 is { Alpha' | C' }_I'
// { Alpha' | C' }_I' <- standardize { Alpha' | C' }_I' apart from (Alpha, C)
// C''<- R_formula_simplification(C and for all I' : C' => Alpha != Alpha') with cont. variables extended by I
// return R_basic({ Alpha | C'' }_I
result = rewriteS1andS2IntensionalUniSets(set1, set2, process);
}
else if (Sets.isExtensionalUniSet(set1)
&& Sets.isIntensionalUniSet(set2)) {
// if S1 is {a1,...,an} and S2 is { Alpha | C }_I
// return
// R_DifferenceOfExtensionalAndIntensionalSet ({a1,...,an}, { Alpha | C }_I, 1)
result = rewriteS1ExtensionalS2IntensionalUniSets(set1, set2, process);
}
else {
throw new IllegalArgumentException("Arguments set1 and set2 do not conform to expected types");
}
return result;
}
// PRIVATE METHODS
private static boolean isUnionOfSets(Expression expression) {
boolean result = false;
if (isUnion(expression)) {
result = true;
for (Expression u_i : expression.getArguments()) {
if (IfThenElse.isIfThenElse(u_i) || isUnion(u_i)) {
// Skip these, as they will be handled later on
// by the recursive calls to R_set_diff
continue;
}
if (!Sets.isSet(u_i)) {
result = false;
break;
}
}
}
return result;
}
private static boolean isUnionOfUniSets(Expression expression) {
boolean result = false;
if (isUnion(expression)) {
result = true;
for (Expression u_i : expression.getArguments()) {
if (IfThenElse.isIfThenElse(u_i) || isUnion(u_i)) {
// Skip these, as they will be handled later on
// by the recursive calls to R_set_diff
continue;
}
if (!Sets.isUniSet(u_i)) {
result = false;
break;
}
}
}
return result;
}
private static boolean isUnionOfMultiSetsOrSingletons(Expression expression) {
boolean result = false;
if (isUnion(expression)) {
result = true;
if (expression.numberOfArguments() > 0) {
boolean multisetExists = false;
for (Expression u_i : expression.getArguments()) {
if (IfThenElse.isIfThenElse(u_i) || isUnion(u_i)) {
// Skip these, as they will be handled later on
// by the recursive calls to R_set_diff
continue;
}
if (Sets.isMultiSet(u_i)) {
multisetExists = true;
}
else if (!Sets.isSingletonExtensionalSet(u_i)) {
result = false;
break;
}
}
// At least 1 multiset should be present otherwise
// this would return true if a union of unisets
// with single elements.
result = result && multisetExists;
}
}
return result;
}
private static boolean isUnion(Expression expression) {
if (Expressions.hasFunctor(expression, FunctorConstants.UNION)) {
return true;
}
return false;
}
private Expression rewriteS1Conditional(Expression set1, Expression set2, RewritingProcess process) {
Trace.log("if S1 is 'if C then Alpha else Beta'");
Trace.log(" return R_basic(if C then R_set_diff(Alpha \\ S2) else R_set_diff(Beta \\ S2))");
Expression condition = IfThenElse.getCondition(set1);
Expression thenBranch = IfThenElse.getThenBranch(set1);
Expression elseBranch = IfThenElse.getElseBranch(set1);
Justification.beginEqualityStep("externalizing conditional");
if (Justification.isEnabled()) {
Expression currentExpression =
IfThenElse.make(
condition,
Expressions.apply(FunctorConstants.SET_DIFFERENCE, thenBranch, set2),
Expressions.apply(FunctorConstants.SET_DIFFERENCE, elseBranch, set2));
Justification.endEqualityStep(currentExpression);
}
Justification.beginEqualityStep("solving set differences in then and else branches");
Expression result = GrinderUtil.branchAndMergeOnACondition(
condition,
newCallSetDifferenceRewrite(), new Expression[] { thenBranch, set2 },
newCallSetDifferenceRewrite(), new Expression[] { elseBranch, set2 },
R_check_branch_reachable,
R_basic, process);
Justification.endEqualityStep(result);
return result;
}
private Expression rewriteS2Conditional(Expression set1, Expression set2, RewritingProcess process) {
Trace.log("if S2 is 'if C then Alpha else Beta'");
Trace.log(" return R_basic(if C then R_set_diff(S1 \\ Alpha) else R_set_diff(S1 \\ Beta))");
Expression condition = IfThenElse.getCondition(set2);
Expression thenBranch = IfThenElse.getThenBranch(set2);
Expression elseBranch = IfThenElse.getElseBranch(set2);
Justification.beginEqualityStep("externalizing conditional");
if (Justification.isEnabled()) {
Expression currentExpression =
IfThenElse.make(
condition,
Expressions.apply(FunctorConstants.SET_DIFFERENCE, set1, thenBranch),
Expressions.apply(FunctorConstants.SET_DIFFERENCE, set1, elseBranch));
Justification.endEqualityStep(currentExpression);
}
Justification.beginEqualityStep("solving set differences in then and else branches");
Expression result = GrinderUtil.branchAndMergeOnACondition(
condition,
newCallSetDifferenceRewrite(), new Expression[] { set1, thenBranch },
newCallSetDifferenceRewrite(), new Expression[] { set1, elseBranch },
R_check_branch_reachable,
R_basic, process);
Justification.endEqualityStep(result);
return result;
}
private Expression rewriteS1UnionUniSets(Expression set1, Expression set2, RewritingProcess process) {
Trace.log("if S1 is S11 union S1rest, where S1i and S2 are unisets");
Trace.log(" return R_set_diff(S11 \\ S2) union R_set_diff(S1rest \\ S2)");
Expression set11 = getFirstOfUnion(set1);
Expression set1rest = getRestOfUnion(set1);
Trace.log("// S11={}", set11);
Trace.log("// S1rest={}", set1rest);
Justification.beginEqualityStep("distributing difference over union");
if (Justification.isEnabled()) {
Expression currentExpression =
Expressions.apply(
FunctorConstants.UNION,
Expressions.apply(FunctorConstants.SET_DIFFERENCE, set11, set2),
Expressions.apply(FunctorConstants.SET_DIFFERENCE, set1rest, set2));
Justification.endEqualityStep(currentExpression);
}
Justification.beginEqualityStep("solving set differences inside union");
Expression d1 = process.rewrite(R_set_diff, LPIUtil.argForSetDifferenceRewriteCall(set11, set2));
Trace.log("// R_set_diff(S11 \\ S2)={}", d1);
Expression d2 = process.rewrite(R_set_diff, LPIUtil.argForSetDifferenceRewriteCall(set1rest, set2));
Trace.log("// R_set_diff(S1rest \\ S2)={}", d2);
Expression result = Expressions.make(FunctorConstants.UNION, d1, d2);
Justification.endEqualityStep(result);
return result;
}
private Expression rewriteS2UnionUniSets(Expression set1, Expression set2, RewritingProcess process) {
Trace.log("if S2 is S21 union S2rest, where S1 and S2i are sets");
Trace.log(" return R_set_diff(R_set_diff(S1 \\ S21) \\ S2rest)");
Expression set21 = getFirstOfUnion(set2);
Expression set2rest = getRestOfUnion(set2);
Trace.log("// S21={}", set21);
Trace.log("// S2rest={}", set2rest);
Justification.beginEqualityStep("difference from union is successive differences");
if (Justification.isEnabled()) {
Expression currentExpression =
Expressions.apply(
FunctorConstants.SET_DIFFERENCE,
Expressions.apply(FunctorConstants.SET_DIFFERENCE, set1, set21),
set2rest);
Justification.endEqualityStep(currentExpression);
}
Justification.beginEqualityStep("solving first difference");
Expression d1 = process.rewrite(R_set_diff, LPIUtil.argForSetDifferenceRewriteCall(set1, set21));
if (Justification.isEnabled()) {
Expression currentExpression = Expressions.apply(FunctorConstants.SET_DIFFERENCE, d1, set2rest);
Justification.endEqualityStep(currentExpression);
}
Justification.beginEqualityStep("solving remaining difference");
Trace.log("// R_set_diff(S1 \\ S21)={}", d1);
Expression result = process.rewrite(R_set_diff, LPIUtil.argForSetDifferenceRewriteCall(d1, set2rest));
Justification.endEqualityStep(result);
return result;
}
private Expression rewriteS1UnionMultiSetsOrSingletons(Expression set1, Expression set2, RewritingProcess process) {
Trace.log("if S1 is S11 union S1rest, where each S1i is a multiset guaranteed to have unique elements,");
Trace.log(" or a singleton, and S2 is a singleton { b }");
Trace.log(" return");
Trace.log(" R_basic(if R_in(b in S11)");
Trace.log(" then R_set_diff(S11 \\ S2) union S1rest");
Trace.log(" else S11 union R_set_diff(S1rest \\ S2))");
final Expression b = set2.get(0);
final Expression set11 = getFirstOfUnion(set1);
final Expression set1Rest = getRestOfUnion(set1);
Trace.log("// S11={}", set11);
Trace.log("// S1rest={}", set1Rest);
Expression result = null;
Justification.beginEqualityStep("if single element in second set is in first set in the union, subtract from it; otherwise, subtract from the remaining sets");
Expression currentExpression = null;
if (Justification.isEnabled()) {
currentExpression =
IfThenElse.make(
Expressions.apply("in", b, set11),
Expressions.apply(
FunctorConstants.UNION,
Expressions.apply("-", set11, set2),
set1Rest
),
Expressions.apply(
FunctorConstants.UNION,
set11,
Expressions.apply("-", set1Rest, set2)));
Justification.endEqualityStep(currentExpression);
}
// Create the condition
// if R_in(b in S11)
Justification.beginEqualityStep("computing condition");
Expression condition = process.rewrite(R_in, LPIUtil.argForInRewriteCall(b, set11));
if (Justification.isEnabled()) {
currentExpression = currentExpression.set(0, condition);
Justification.endEqualityStep(currentExpression);
}
// Create the then branch computation routine
RewriteOnBranch callSetDifferenceRewriteOnThenBranch = new RewriteOnBranch() {
@Override
public Expression rewrite(Expression[] expressions, RewritingProcess process) {
// then R_set_diff(S11 \ S2) union S1rest
Expression set11DiffS2 = process.rewrite(R_set_diff, LPIUtil.argForSetDifferenceRewriteCall(expressions[0], expressions[1]));
Expression result = Expressions.make(FunctorConstants.UNION, set11DiffS2, set1Rest);
return result;
}
};
// Create the else branch computation routine
RewriteOnBranch callSetDifferenceRewriteOnElseBranch = new RewriteOnBranch() {
@Override
public Expression rewrite(Expression[] expressions, RewritingProcess process) {
// else S11 union R_set_diff(S1rest \ S2)
Expression set1restDiffS2 = process.rewrite(R_set_diff, LPIUtil.argForSetDifferenceRewriteCall(expressions[0], expressions[1]));
Expression result = Expressions.make(FunctorConstants.UNION, set11, set1restDiffS2);
return result;
}
};
Justification.beginEqualityStep("computing differences at then and else branches");
result = GrinderUtil.branchAndMergeOnACondition(
condition,
callSetDifferenceRewriteOnThenBranch, new Expression[] { set11, set2 },
callSetDifferenceRewriteOnElseBranch, new Expression[] { set1Rest, set2 },
R_check_branch_reachable,
R_basic, process);
Justification.endEqualityStep(result);
return result;
}
private Expression rewriteS1ExtensionalMultiSet(Expression set1, Expression set2, RewritingProcess process) {
Trace.log("if S1 is {{a1,...,an}} and S2 is { b }");
Trace.log(" return R_DifferenceOfExtensionalAndExtensionalSet({{a1,...,an}}, {b}, 1, 1)");
Justification.beginEqualityStep("computing difference of extensional sets");
Expression result = process.rewrite(R_DifferenceOfExtensionalAndExtensionalSet,
LPIUtil.argForDifferenceOfExtensionalAndExtensionalSetRewriteCall(set1, set2, 0, 0));
Justification.endEqualityStep(result);
return result;
}
private Expression rewriteS1IntensionalMultiSet(Expression set1, Expression set2, RewritingProcess process) {
Expression result = null;
Trace.log("if S1 is {{ Alpha | C }}_I and S2 is { b }");
Expression b = ExtensionalSet.getElements(set2).get(0);
if (CheapDisequalityModule.isACheapDisequality(IntensionalSet.getHead(set1), b, process)) {
Justification.beginEqualityStep("is guaranteed Alpha != b'");
Trace.log(" is guaranteed Alpha != b'");
Trace.log(" return S1");
result = set1;
Justification.endEqualityStep(result);
} else {
Trace.log(" {{ Alpha' | C' }}_I' <- standardize {{ Alpha | C}}_I apart from {b}");
Justification.beginEqualityStep("difference is intensional set constrained so that its elements are not equal to " + b);
Expression saS1 = StandardizedApartFrom
.standardizedApartFrom(
set1, set2, process);
Trace.log("// {{ Alpha' | C' }}_I'={}", saS1);
Expression alphaPrime = IntensionalSet.getHead(saS1);
Expression cPrime = IntensionalSet.getCondition(saS1);
Expression iPrime = IntensionalSet.getScopingExpression(saS1);
Expression alphaPrimeEqualb = Equality.make(alphaPrime, b);
Expression notAlphaPrimeEqualb = Not.make(alphaPrimeEqualb);
Expression cPrimeAndNotAlphaPrimeEqualb = CardinalityUtil.makeAnd(cPrime, notAlphaPrimeEqualb);
if (Justification.isEnabled()) {
Expression currentExpression = IntensionalSet.make(Sets.getLabel(saS1), iPrime, alphaPrime, cPrimeAndNotAlphaPrimeEqualb);
Justification.endEqualityStep(currentExpression);
}
Trace.log(" C'' <- R_formula_simplification(C' and not Alpha' = b) with cont. variables extended by I'");
Justification.beginEqualityStep("simplifying condition");
RewritingProcess processIPrime = GrinderUtil.extendContextualVariables(iPrime, process);
Expression cPrimePrime = processIPrime.rewrite(R_formula_simplification, cPrimeAndNotAlphaPrimeEqualb);
result = IntensionalSet.make(Sets.getLabel(saS1), iPrime, alphaPrime, cPrimePrime);
Justification.endEqualityStep(result);
Trace.log(" return R_basic({{ Alpha' | C'' }}_I')");
Justification.beginEqualityStep("simplifying overall expression");
result = process.rewrite(R_basic, result);
Justification.endEqualityStep(result);
}
return result;
}
private Expression rewriteS1MultiSetS2ExtensionalUniSet(Expression set1, Expression set2, RewritingProcess process) {
Trace.log("if S1 is a multiset and S2 is {b1, ..., bm}");
Trace.log(" return R_set_diff(R_set_diff(S1, {b1}), {b2,...,bm})");
Justification.beginEqualityStep("computing difference of multiset and extensional uniset");
Expression b1 = ExtensionalSet.makeSingletonOfSameTypeAs(set2, ExtensionalSet.getElements(set2).get(0));
Expression s1DiffB1Result = process.rewrite(R_set_diff, LPIUtil.argForSetDifferenceRewriteCall(set1, b1));
Expression b2ToBm = ExtensionalSet.removeNonDestructively(set2, 0);
Expression result = process.rewrite(R_set_diff, LPIUtil.argForSetDifferenceRewriteCall(s1DiffB1Result, b2ToBm));
Justification.endEqualityStep(result);
return result;
}
private Expression rewriteS1MultiSetS2Union(Expression set1, Expression set2, RewritingProcess process) {
Trace.log("if S1 is a multiset and S2 is S21 union ... union S2m");
Trace.log(" return R_set_diff(R_set_diff(S1, S21), S22 union ... union S2m)");
Justification.beginEqualityStep("computing difference of multiset and union");
Expression s21 = set2.get(0);
Expression s1DiffS21Result = process.rewrite(R_set_diff, LPIUtil.argForSetDifferenceRewriteCall(set1, s21));
List<Expression> rest = Util.rest(set2.getArguments());
Expression s22UnionS2m = Expressions.make(FunctorConstants.UNION, rest);
Expression result = process.rewrite(R_set_diff, LPIUtil.argForSetDifferenceRewriteCall(s1DiffS21Result, s22UnionS2m));
Justification.endEqualityStep(result);
return result;
}
private Expression rewriteS1andS2ExtensionalUniSets(Expression set1, Expression set2, RewritingProcess process) {
Trace.log("if S1 is {a1,...,an} and S2 is {b1,...,bm}");
Trace.log(" return R_DifferenceOfExtensionalAndExtensionalSet({a1,...,an}, {b1,...,bm}, 1, 1)");
Justification.beginEqualityStep("computing difference of extensional sets");
Expression result = process.rewrite(R_DifferenceOfExtensionalAndExtensionalSet,
LPIUtil.argForDifferenceOfExtensionalAndExtensionalSetRewriteCall(set1, set2, 0, 0));
Justification.endEqualityStep(result);
return result;
}
private Expression rewriteS1IntensionalS2ExtensionalUniSets(Expression set1, Expression set2, RewritingProcess process) {
Trace.log("if S1 is { Alpha | C }_I and S2 is {b1,...,bm}");
Expression result = null;
if (ExtensionalSet.cardinality(set2) == 0) {
Justification.beginEqualityStep("second set is empty, so result is simply the first set"); // * - closed at end
result = set1;
}
else {
Trace.log(" { Alpha' | C' }_I' <- standardize { Alpha | C }_I apart from {b1,...,bm}");
List<Expression> disjuncts = new ArrayList<Expression>();
Expression saS1 = StandardizedApartFrom
.standardizedApartFrom(
set1, set2, process);
Expression alphaPrime = IntensionalSet.getHead(saS1);
Expression cPrime = IntensionalSet.getCondition(saS1);
Expression iPrime = IntensionalSet.getScopingExpression(saS1);
for (Expression b_i : ExtensionalSet.getElements(set2)) {
Expression equality = Equality.make(alphaPrime, b_i);
disjuncts.add(equality);
}
Justification.beginEqualityStep("difference is intensional set constrained so that its elements are not equal any element in " + set2);
Trace.log(" C'' <- R_formula_implification(C' and not (Disjunction_i Alpha' = b_i)) with cont. variables extended by I'");
RewritingProcess processIPrime = GrinderUtil.extendContextualVariables(iPrime, process);
BranchRewriteTask[] disjunctRewriters = new BranchRewriteTask[disjuncts.size()];
for (int i = 0; i < disjuncts.size(); i++) {
disjunctRewriters[i] = new BranchRewriteTask(
new RewriteOnBranch() {
@Override
public Expression rewrite(Expression[] expressions, RewritingProcess process) {
Expression result = process.rewrite(R_formula_simplification, expressions[0]);
return result;
}
},
new Expression[] {disjuncts.get(i)});
}
Expression disjunction = GrinderUtil.branchAndMergeOnADisjunction(disjunctRewriters, processIPrime);
Expression cPrimePrime = null;
if (disjunction.equals(Expressions.TRUE)) {
Trace.log("// Shortcircuited, disjunct always true, therefore FALSE.");
// C' and not or( ..., true, ...) is always false
cPrimePrime = Expressions.FALSE;
Justification.beginEqualityStep("last simplified condition is always true, so set condition is always false"); // * - closed at end
}
else {
Expression notDisjunction = Not.make(disjunction);
Expression cPrimeAndNotDisjunction = CardinalityUtil.makeAnd(cPrime, notDisjunction);
Justification.beginEqualityStep("simplifying set condition"); // * - closed at end
cPrimePrime = processIPrime.rewrite(R_formula_simplification, cPrimeAndNotDisjunction);
}
result = IntensionalSet.make(Sets.getLabel(saS1), iPrime, alphaPrime, cPrimePrime);
}
// * - this is closing three beginSteps above, marked with *
Justification.endEqualityStep(result);
Trace.log(" return R_basic({ Alpha' | C'' }_I')");
Justification.beginEqualityStep("simplifying overall expression");
result = process.rewrite(R_basic, result);
Justification.endEqualityStep(result);
return result;
}
private Expression rewriteS1andS2IntensionalUniSets(Expression set1, Expression set2, RewritingProcess process) {
Expression result = null;
Trace.log("if S1 is { Alpha | C }_I and S2 is { Alpha' | C' }_I'");
Expression alpha = IntensionalSet.getHead(set1);
Expression alphaPrime = IntensionalSet.getHead(set2);
// Perform a cheap disequality first
if (CheapDisequalityModule.isACheapDisequality(alpha, alphaPrime, process)) {
Justification.beginEqualityStep("is guaranteed Alpha != Alpha'");
Trace.log(" is guaranteed Alpha != Alpha'");
Trace.log(" return S1");
result = set1;
Justification.endEqualityStep(result);
}
else {
Expression c = IntensionalSet.getCondition(set1);
Expression i = IntensionalSet.getScopingExpression(set1);
Trace.log(" { Alpha' | C' }_I' <- standardize { Alpha' | C' }_I' apart from (Alpha, C)");
Expression tupleAlphaC = Tuple.make(Arrays.asList(alpha, c));
Expression saS2 = StandardizedApartFrom
.standardizedApartFrom(
set2, tupleAlphaC, process);
alphaPrime = IntensionalSet.getHead(saS2);
Expression cPrime = IntensionalSet.getCondition(saS2);
List<Expression> iPrime = IntensionalSet.getIndexExpressions(saS2);
Expression neq = Disequality.make(alpha, alphaPrime);
Expression impl = Implication.make(cPrime, neq);
Expression forAllIPrime = ForAll.make(iPrime, impl);
Expression cAndForAllPrimeI = CardinalityUtil.makeAnd(c, forAllIPrime);
if (Justification.isEnabled()) {
Justification.beginEqualityStep("difference set is an intensional set with the condition of the first and the negation of the condition of the second");
Expression currentExpression = IntensionalSet.make(Sets.getLabel(set1), i, alpha, cAndForAllPrimeI);
Justification.endEqualityStep(currentExpression);
}
Trace.log(" C''<- R_formula_simplification(C and for all I' : C' => Alpha != Alpha') with cont. variables extended by I");
Justification.beginEqualityStep("simplifying set condition");
// Note: As an optimization, instead of simplifying the overall conjunct as described in the
// pseudo-code in a single shot, i.e:
// RewritingProcess processI = GrinderUtil.extendContextualVariables(i, process);
// Expression cPrimePrime = processI.rewrite(R_formula_simplification, cAndForAllPrimeI);
// We will break it apart so that the more expensive quantified formula is resolved first.
// However, we do this simplification under the assumption 'c' is true (this is the same
// theory/logic used in ConjunctsHoldTrueForEachOther). A more constrained context can
// help improve overall performance.
RewritingProcess processI = GrinderUtil.extendContextualVariablesAndConstraint(i, c, process);
forAllIPrime = processI.rewrite(R_simplify, forAllIPrime);
cAndForAllPrimeI = CardinalityUtil.makeAnd(c, forAllIPrime);
processI = GrinderUtil.extendContextualVariables(i, process);
Expression cPrimePrime = processI.rewrite(R_formula_simplification, cAndForAllPrimeI);
result = IntensionalSet.make(Sets.getLabel(set1), i, alpha, cPrimePrime);
Justification.endEqualityStep(result);
Trace.log(" return R_basic({ Alpha | C'' }_I)");
Justification.beginEqualityStep("simplifying overall expression");
result = process.rewrite(R_basic, result);
Justification.endEqualityStep(result);
}
return result;
}
private Expression rewriteS1ExtensionalS2IntensionalUniSets(Expression set1, Expression set2, RewritingProcess process) {
Trace.log("if S1 is {a1,...,an} and S2 is { Alpha | C }_I");
Trace.log(" return R_DifferenceOfExtensionalAndIntensionalSet ({a1,...,an}, { Alpha | C }_I, 1)");
Justification.beginEqualityStep("difference between extensional and intensional set");
Expression result = process.rewrite(R_DifferenceOfExtensionalAndIntensionalSet,
LPIUtil.argForDifferenceOfExtensionalAndIntensionalSetRewriteCall(set1, set2, 0));
Justification.endEqualityStep(result);
return result;
}
private RewriteOnBranch newCallSetDifferenceRewrite() {
return new RewriteOnBranch() {
@Override
public Expression rewrite(Expression[] expressions, RewritingProcess process) {
Expression result = process.rewrite(R_set_diff, LPIUtil.argForSetDifferenceRewriteCall(expressions[0], expressions[1]));
return result;
}
};
}
private static Expression getFirstOfUnion(Expression union) {
Expression result = null;
if (union.numberOfArguments() == 0) {
// Handle the case 'union()'
result = _emptySet;
}
else {
result = union.get(0);
}
return result;
}
private static Expression getRestOfUnion(Expression union) {
Expression result = null;
List<Expression> rest = union.getArguments();
if (rest.size() > 0) {
rest = Util.rest(union.getArguments());
}
switch (rest.size()) {
case 0: // Handle the case 'union()'
result = _emptySet;
break;
case 1: // Handle the case 'union({...})'
result = union.get(1);
break;
default:
result = Expressions.make(FunctorConstants.UNION, rest.toArray());
break;
}
return result;
}
} |
package ca.corefacility.bioinformatics.irida.ria.integration;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.TestWatcher;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import ca.corefacility.bioinformatics.irida.IridaApplication;
import ca.corefacility.bioinformatics.irida.config.IridaIntegrationTestUriConfig;
import ca.corefacility.bioinformatics.irida.config.data.IridaApiTestFilesystemConfig;
import ca.corefacility.bioinformatics.irida.junit5.listeners.IntegrationUITestListener;
import ca.corefacility.bioinformatics.irida.ria.integration.pages.AbstractPage;
import ca.corefacility.bioinformatics.irida.ria.integration.pages.LoginPage;
import ca.corefacility.bioinformatics.irida.utils.NullReplacementDatasetLoader;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseTearDown;
import com.github.springtestdbunit.annotation.DbUnitConfiguration;
import com.google.common.base.Strings;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Common functionality to all UI integration tests.
*/
@Tag("IntegrationTest")
@Tag("UI")
@ActiveProfiles("it")
@SpringBootTest(classes = { IridaApplication.class, IridaApiTestFilesystemConfig.class },webEnvironment = WebEnvironment.RANDOM_PORT)
@Import(IridaIntegrationTestUriConfig.class)
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class })
@DatabaseTearDown("classpath:/ca/corefacility/bioinformatics/irida/test/integration/TableReset.xml")
@DbUnitConfiguration(dataSetLoader = NullReplacementDatasetLoader.class)
public class AbstractIridaUIITChromeDriver {
private static final Logger logger = LoggerFactory.getLogger(AbstractIridaUIITChromeDriver.class);
public static final int DRIVER_TIMEOUT_IN_SECONDS = IntegrationUITestListener.DRIVER_TIMEOUT_IN_SECONDS;
private static boolean isSingleTest = false;
private static final String CHROMEDRIVER_PROP_KEY = "webdriver.chrome.driver";
private static final String CHROMEDRIVER_LOCATION = "src/main/webapp/chromedriver";
@RegisterExtension
public ScreenshotOnFailureWatcher watcher = new ScreenshotOnFailureWatcher();
/**
* Code to execute before *each* test.
*/
@BeforeEach
public void setUpTest() throws IOException {
// logout before everything else.
LoginPage.logout(driver());
}
/**
* Code to execute after *each* test.
*/
@AfterEach
public void tearDown() {
// NOTE: DO **NOT** log out in this method. This method happens because
// the @After method happens immediately after test failure, but before
// the @Rule TestWatcher checks the outcome of the test. We want to take
// a screenshot of the application state **before** logging out.
}
/**
* Code to execute *once* after the class is finished.
*/
@AfterAll
public static void destroy() {
if (isSingleTest) {
logger.debug("Closing ChromeDriver for single test class.");
IntegrationUITestListener.stopWebDriver();
}
}
/**
* Get a reference to the {@link WebDriver} used in the tests.
* @return the instance of {@link WebDriver} used in the tests.
*/
public static WebDriver driver() {
if (IntegrationUITestListener.driver() == null) {
final String chromeDriverProp = System.getProperty(CHROMEDRIVER_PROP_KEY);
System.setProperty(CHROMEDRIVER_PROP_KEY,
Strings.isNullOrEmpty(chromeDriverProp) ? CHROMEDRIVER_LOCATION : chromeDriverProp);
logger.debug(
"Starting ChromeDriver for a single test class. Using `chromedriver` at '" + System.getProperty(
CHROMEDRIVER_PROP_KEY) + "'");
isSingleTest = true;
IntegrationUITestListener.startWebDriver();
}
return IntegrationUITestListener.driver();
}
/**
* Method to use on any page to check to ensure that internationalization messages are being
* automatically loaded onto the page.
*
* @param page - the instance of {@link AbstractPage} to check for internationalization.
* @param entries - a {@link List} of bundle names. This will correspond to the loaded webpack bundles.
* @param header - Expected text for the main heading on the page. Needs to have class name `t-main-heading`
*/
public void checkTranslations(AbstractPage page, List<String> entries, String header) {
// Always check for app :)
assertTrue(page.ensureTranslationsLoaded("app"), "Translations should be loaded for the app bundle");
entries.forEach(entry -> assertTrue(page.ensureTranslationsLoaded(entry),
"Translations should be loaded for " + entry + " bundle"));
if (!Strings.isNullOrEmpty(header)) {
assertTrue(page.ensurePageHeadingIsTranslated(header), "Page title has been properly translated");
}
}
/**
* Simple test watcher for taking screenshots of the browser on failure.
*/
private static class ScreenshotOnFailureWatcher implements TestWatcher {
private static final Logger logger = LoggerFactory.getLogger(ScreenshotOnFailureWatcher.class);
/**
* {@inheritDoc}
*/
@Override
public void testFailed(ExtensionContext context, Throwable t) {
logger.debug("Handling exception of type [" + t.getClass() + "], taking screenshot: " + t.getMessage(), t);
final TakesScreenshot takesScreenshot = (TakesScreenshot) driver();
final Path screenshot = Paths.get(takesScreenshot.getScreenshotAs(OutputType.FILE).toURI());
try {
final Path destination = Files.createTempFile(
"irida-" + context.getRequiredTestClass().getSimpleName() + "#" + context.getRequiredTestMethod().getName(),
".png");
Files.move(screenshot, destination, StandardCopyOption.REPLACE_EXISTING);
logger.info("Screenshot deposited at: [" + destination.toString() + "]");
} catch (final IOException e) {
logger.error("Unable to write screenshot out.", e);
}
}
}
} |
package org.carlspring.strongbox.data.server;
import org.carlspring.strongbox.config.ConnectionConfig;
import org.carlspring.strongbox.config.ConnectionConfigOrientDB;
import org.carlspring.strongbox.data.domain.GenericEntityHook;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import com.orientechnologies.orient.graph.server.command.OServerCommandGetGephi;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.OServerMain;
import com.orientechnologies.orient.server.config.OServerCommandConfiguration;
import com.orientechnologies.orient.server.config.OServerConfiguration;
import com.orientechnologies.orient.server.config.OServerEntryConfiguration;
import com.orientechnologies.orient.server.config.OServerHookConfiguration;
import com.orientechnologies.orient.server.config.OServerNetworkConfiguration;
import com.orientechnologies.orient.server.config.OServerNetworkListenerConfiguration;
import com.orientechnologies.orient.server.config.OServerNetworkProtocolConfiguration;
import com.orientechnologies.orient.server.config.OServerParameterConfiguration;
import com.orientechnologies.orient.server.config.OServerUserConfiguration;
import com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.carlspring.strongbox.data.PropertyUtils.getVaultDirectory;
/**
* An embedded configuration of OrientDb server.
*
* @author Alex Oreshkevich
*/
public class EmbeddedOrientDbServer
implements OrientDbServer
{
private static final Logger logger = LoggerFactory.getLogger(EmbeddedOrientDbServer.class);
private OServer server;
private OServerConfiguration serverConfiguration;
@Inject
private ConnectionConfig connectionConfig;
@PostConstruct
public void start()
{
try
{
prepareStudio();
init();
activate();
}
catch (Exception e)
{
throw new RuntimeException("Unable to start the embedded OrientDb server!", e);
}
}
public File getStudioClasspathLocation()
{
return new File(OServer.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath()).toPath().resolveSibling("orientdb-studio-2.2.0.jar").toFile();
}
private void prepareStudio() throws IOException
{
String studioEnabled = System.getProperty(ConnectionConfigOrientDB.PROPERTY_STUDIO_ENABLED);
if (studioEnabled != null && Boolean.FALSE.equals(studioEnabled))
{
logger.info(String.format("OrientDB Studio disabled with [%], skip initialization.",
ConnectionConfigOrientDB.PROPERTY_STUDIO_ENABLED));
return;
}
File studioClasspathLocation = getStudioClasspathLocation();
Path studioPath = Paths.get(getStudioPath()).resolve("studio");
if (Files.exists(studioPath))
{
logger.info(String.format("OrientDB Studio already available at [%s], skip initialization.\\If you want to force initialize Studio please remove its folder above.",
studioPath.toAbsolutePath().toString()));
return;
}
logger.info(String.format("Initialize OrientDB Studio at [%s].", studioPath.toAbsolutePath().toString()));
Files.createDirectories(studioPath);
try (JarFile jar = new JarFile(studioClasspathLocation))
{
Enumeration<JarEntry> enumEntries = jar.entries();
while (enumEntries.hasMoreElements())
{
JarEntry file = enumEntries.nextElement();
if (!file.getName().startsWith("META-INF/resources/webjars/orientdb-studio/2.2.0/"))
{
continue;
}
File f = studioPath.resolve(file.getName().replace("META-INF/resources/webjars/orientdb-studio/2.2.0/",
""))
.toFile();
if (file.isDirectory() && !f.mkdir())
{
logger.error(String.format("Failed to initialize OrientDB Studio at [%s]",
studioPath.toAbsolutePath().toString()));
return;
}
try (InputStream is = jar.getInputStream(file))
{
try (FileOutputStream fos = new java.io.FileOutputStream(f))
{
while (is.available() > 0)
{
fos.write(is.read());
}
}
}
}
}
}
private void init()
throws Exception
{
String database = connectionConfig.getDatabase();
logger.info(String.format("Initialize Embedded OrientDB server for [%s]", database));
server = OServerMain.create();
serverConfiguration = new OServerConfiguration();
OServerHookConfiguration hookConfiguration = new OServerHookConfiguration();
serverConfiguration.hooks = Arrays.asList(new OServerHookConfiguration[] { hookConfiguration });
hookConfiguration.clazz = GenericEntityHook.class.getName();
OServerNetworkListenerConfiguration httpListener = new OServerNetworkListenerConfiguration();
httpListener.ipAddress = connectionConfig.getHost();
httpListener.portRange = "2480";
httpListener.protocol = "http";
httpListener.socket = "default";
OServerCommandConfiguration httpCommandConfiguration1 = new OServerCommandConfiguration();
httpCommandConfiguration1.implementation = OServerCommandGetStaticContent.class.getCanonicalName();
httpCommandConfiguration1.pattern = "GET|www GET|studio/ GET| GET|*.htm GET|*.html GET|*.xml GET|*.jpeg GET|*.jpg GET|*.png GET|*.gif GET|*.js GET|*.css GET|*.swf GET|*.ico GET|*.txt GET|*.otf GET|*.pjs GET|*.svg GET|*.json GET|*.woff GET|*.ttf GET|*.svgz";
httpCommandConfiguration1.stateful = false;
httpCommandConfiguration1.parameters = new OServerEntryConfiguration[] { new OServerEntryConfiguration(
"http.cache:*.htm *.html",
"Cache-Control: no-cache, no-store, max-age=0, must-revalidate\\r\\nPragma: no-cache"),
new OServerEntryConfiguration(
"http.cache:default",
"Cache-Control: max-age=120") };
OServerCommandConfiguration httpCommandConfiguration2 = new OServerCommandConfiguration();
httpCommandConfiguration2.implementation = OServerCommandGetGephi.class.getCanonicalName();
httpListener.commands = new OServerCommandConfiguration[] { httpCommandConfiguration1,
httpCommandConfiguration2 };
httpListener.parameters = new OServerParameterConfiguration[] { new OServerParameterConfiguration("utf-8",
"network.http.charset") };
OServerNetworkListenerConfiguration binaryListener = new OServerNetworkListenerConfiguration();
binaryListener.ipAddress = connectionConfig.getHost();
binaryListener.portRange = connectionConfig.getPort().toString();
binaryListener.protocol = "binary";
binaryListener.socket = "default";
OServerNetworkProtocolConfiguration binaryProtocol = new OServerNetworkProtocolConfiguration();
binaryProtocol.name = "binary";
binaryProtocol.implementation = "com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary";
OServerNetworkProtocolConfiguration httpProtocol = new OServerNetworkProtocolConfiguration();
httpProtocol.name = "http";
httpProtocol.implementation = "com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpDb";
// prepare network configuration
OServerNetworkConfiguration networkConfiguration = new OServerNetworkConfiguration();
networkConfiguration.protocols = new LinkedList<>();
networkConfiguration.protocols.add(binaryProtocol);
networkConfiguration.protocols.add(httpProtocol);
networkConfiguration.listeners = new LinkedList<>();
networkConfiguration.listeners.add(binaryListener);
networkConfiguration.listeners.add(httpListener);
// add users (incl system-level root user)
List<OServerUserConfiguration> users = new LinkedList<>();
users.add(buildUser(connectionConfig.getUsername(), connectionConfig.getPassword(), "*"));
System.setProperty("ORIENTDB_ROOT_PASSWORD", connectionConfig.getUsername());
// add other properties
List<OServerEntryConfiguration> properties = new LinkedList<>();
properties.add(buildProperty("server.database.path", getDatabasePath()));
properties.add(buildProperty("plugin.dynamic", "false"));
properties.add(buildProperty("log.console.level", "linfo"));
//properties.add(buildProperty("log.file.level", "fine"));
properties.add(buildProperty("orientdb.www.path", getStudioPath()));
serverConfiguration.network = networkConfiguration;
serverConfiguration.users = users.toArray(new OServerUserConfiguration[users.size()]);
serverConfiguration.properties = properties.toArray(new OServerEntryConfiguration[properties.size()]);
}
private void activate()
throws Exception
{
if (!server.isActive())
{
server.startup(serverConfiguration);
server.activate();
}
}
private OServerUserConfiguration buildUser(String name,
String password,
String resources)
{
OServerUserConfiguration user = new OServerUserConfiguration();
user.name = name;
user.password = password;
user.resources = resources;
return user;
}
private OServerEntryConfiguration buildProperty(String name,
String value)
{
OServerEntryConfiguration property = new OServerEntryConfiguration();
property.name = name;
property.value = value;
return property;
}
private String getDatabasePath()
{
return getVaultDirectory() + "/db";
}
private String getStudioPath()
{
return getVaultDirectory() + "/www";
}
@PreDestroy
@Override
public void stop()
{
server.shutdown();
}
} |
// ooo-util - a place for OOO utilities
package com.threerings.servlet.util;
import java.util.Collection;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.samskivert.util.StringUtil;
import com.samskivert.util.Tuple;
public class QueryBuilder
{
public String getOnly (String key)
{
return getOnly(key, null);
}
public String getOnly (String key, String defaultValue)
{
return Iterables.getOnlyElement(get(key), defaultValue);
}
/**
* Retrieve the first value for the given key, or null if the key is not defined.
*/
public String getFirst (String key)
{
Collection<String> values = get(key);
return values.isEmpty() ? null : values.iterator().next();
}
/**
* Returns the current values for key or an empty collection if there isn't a value.
*/
public Collection<String> get (String key)
{
return _params.get(key);
}
/**
* Adds the given value to the parameter mapping under key adding to any current value.
* {@link String#valueOf} is called on <code>val</code> to turn it into a string.
*/
public QueryBuilder add (String key, Object val)
{
_params.put(key, String.valueOf(val));
return this;
}
/**
* Adds all the parameters in <code>req</code> to the parameters being constructed.
*/
public QueryBuilder addAll (HttpServletRequest req)
{
for (Tuple<String, String> entry : new Parameters(req).entries()) {
add(entry.left, entry.right);
}
return this;
}
/**
* Adds all the parameters in <code>map</code> to the parameters being constructed.
*/
public QueryBuilder addAll (Map<?, ?> map)
{
for (Map.Entry<?, ?> entry : map.entrySet()) {
add(String.valueOf(entry.getKey()), entry.getValue());
}
return this;
}
/**
* Appends the query in this builder to the given StringBuilder with a question mark.
*/
public String toUrl (StringBuilder base)
{
return _params.isEmpty() ? base.toString() : encode(base.append('?'), _params.entries());
}
/**
* Appends the query in this builder to the given String with a question mark.
*/
public String toUrl (String base)
{
return toUrl(new StringBuilder(base));
}
/**
* Returns the query in this builder.
*/
public String toString ()
{
return encode(new StringBuilder(), _params.entries());
}
protected static String encode (StringBuilder out, Iterable<Map.Entry<String, String>> entries)
{
boolean appended = false;
for (Map.Entry<String, String> entry : entries) {
out.append(StringUtil.encode(entry.getKey())).
append('=').
append(StringUtil.encode(entry.getValue())).
append('&');
appended = true;
}
if (appended) { // Drop the extra ampersand
out.setLength(out.length() - 1);
}
return out.toString();
}
protected final Multimap<String, String> _params = ArrayListMultimap.create();
} |
package com.tkhoon.framework.helper;
import com.tkhoon.framework.FrameworkConstant;
import com.tkhoon.framework.bean.Multipart;
import com.tkhoon.framework.bean.Multiparts;
import com.tkhoon.framework.exception.UploadException;
import com.tkhoon.framework.util.CollectionUtil;
import com.tkhoon.framework.util.FileUtil;
import com.tkhoon.framework.util.StreamUtil;
import com.tkhoon.framework.util.StringUtil;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UploadHelper {
private static final Logger logger = LoggerFactory.getLogger(UploadHelper.class);
private static final int uploadLimit = ConfigHelper.getConfigNumber(FrameworkConstant.APP_UPLOAD_LIMIT);
// FileUpload
private static ServletFileUpload fileUpload;
public static void init(ServletContext servletContext) {
// Tomcat work
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
// FileUpload
fileUpload = new ServletFileUpload(new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, repository));
if (uploadLimit != 0) {
fileUpload.setFileSizeMax(uploadLimit * 1024 * 1024);
if (logger.isDebugEnabled()) {
logger.debug("[Smart] limit of uploading: {}M", uploadLimit);
}
}
}
public static boolean isMultipart(HttpServletRequest request) {
// multipart
return ServletFileUpload.isMultipartContent(request);
}
public static List<Object> createMultipartParamList(HttpServletRequest request) throws Exception {
List<Object> paramList = new ArrayList<Object>();
Map<String, String> fieldMap = new HashMap<String, String>();
List<Multipart> multipartList = new ArrayList<Multipart>();
List<FileItem> fileItemList;
try {
fileItemList = fileUpload.parseRequest(request);
} catch (FileUploadBase.FileSizeLimitExceededException e) {
throw new UploadException(e);
}
for (FileItem fileItem : fileItemList) {
String fieldName = fileItem.getFieldName();
if (fileItem.isFormField()) {
String fieldValue = fileItem.getString(FrameworkConstant.CHARSET_UTF);
fieldMap.put(fieldName, fieldValue);
} else {
String originalFileName = FileUtil.getRealFileName(fileItem.getName());
String fileName = FileUtil.getRealFileName(fileItem.getName());
if (StringUtil.isNotEmpty(originalFileName)) {
String uploadedFileName = FileUtil.getEncodedFileName(originalFileName);
String contentType = fileItem.getContentType();
long fileSize = fileItem.getSize();
InputStream inputSteam = fileItem.getInputStream();
// Multipart multipartList
Multipart multipart = new Multipart(uploadedFileName, contentType, fileSize, inputSteam);
multipartList.add(multipart);
// fieldMap
fieldMap.put(fieldName, uploadedFileName);
}
}
}
paramList.add(fieldMap);
if (CollectionUtil.isNotEmpty(multipartList)) {
paramList.add(new Multiparts(multipartList));
} else {
paramList.add(null);
}
return paramList;
}
public static void uploadFile(String basePath, Multipart multipart) {
try {
if (multipart != null) {
String filePath = basePath + multipart.getFileName();
FileUtil.createFile(filePath);
InputStream inputStream = new BufferedInputStream(multipart.getInputStream());
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
StreamUtil.copyStream(inputStream, outputStream);
}
} catch (Exception e) {
logger.error("", e);
throw new RuntimeException(e);
}
}
public static void uploadFiles(String basePath, Multiparts multiparts) {
for (Multipart multipart : multiparts.getAll()) {
uploadFile(basePath, multipart);
}
}
} |
package de.luckycrew.halloween.item;
import java.util.List;
import info.u_team.u_team_core.creativetab.UCreativeTab;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.*;
import net.minecraft.potion.*;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.*;
public class ItemCandyBag extends ItemFood {
private String name;
public ItemCandyBag(String name, UCreativeTab tab) {
super(4, 2.0F, false);
this.name = name;
setCreativeTab(tab);
register();
setAlwaysEdible();
setHasSubtypes(true);
}
private void register() {
setUnlocalizedName(name);
GameRegistry.registerItem(this, name);
}
@SideOnly(Side.CLIENT)
public boolean hasEffect(ItemStack stack) {
return stack.getMetadata() > 0;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SideOnly(Side.CLIENT)
public void getSubItems(Item item, CreativeTabs tab, List list) {
list.add(new ItemStack(item, 1, 0));
list.add(new ItemStack(item, 1, 1));
}
@Override
public EnumRarity getRarity(ItemStack stack) {
return stack.getMetadata() == 0 ? EnumRarity.RARE : EnumRarity.EPIC;
}
@Override
public void onFoodEaten(ItemStack stack, World worldIn, EntityPlayer player) {
if (!worldIn.isRemote) {
if (stack.getMetadata() == 0) {
player.addPotionEffect(new PotionEffect(Potion.absorption.id, 1200, 1));
} else {
player.addPotionEffect(new PotionEffect(Potion.absorption.id, 2400, 4));
player.addPotionEffect(new PotionEffect(Potion.regeneration.id, 1200, 1));
player.addPotionEffect(new PotionEffect(Potion.resistance.id, 600, 2));
player.addPotionEffect(new PotionEffect(Potion.moveSpeed.id, 1200, 0));
player.addPotionEffect(new PotionEffect(Potion.jump.id, 1200, 0));
}
}
}
} |
package de.unistuttgart.ims.uimautil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.configuration2.Configuration;
import org.apache.uima.UIMAException;
import org.apache.uima.cas.CASException;
import org.apache.uima.cas.Feature;
import org.apache.uima.cas.FeaturePath;
import org.apache.uima.cas.Type;
import org.apache.uima.fit.factory.JCasFactory;
import org.apache.uima.fit.factory.TypeSystemDescriptionFactory;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.apache.uima.resource.metadata.TypeDescription;
import org.apache.uima.resource.metadata.TypeSystemDescription;
import de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import de.unistuttgart.ims.uimautil.export.Column;
import de.unistuttgart.ims.uimautil.export.CoveredColumn;
import de.unistuttgart.ims.uimautil.export.FeaturePathColumn;
import de.unistuttgart.ims.uimautil.export.PrimitiveColumn;
public class CoNLLExport {
Configuration configuration;
List<Column> columnList;
Type type;
Class<? extends Annotation> annotationClass;
Class<? extends Annotation> coveredAnnotationClass;
List<List<Object>> result = new LinkedList<List<Object>>();
public List<List<Object>> getResult() {
return result;
}
public List<? extends List<Object>> convert(JCas jcas) {
Collection<? extends Annotation> annotationList = JCasUtil.select(jcas, annotationClass);
// print entries
for (Annotation a : annotationList) {
result.addAll(printFeatureValues(a, columnList.iterator()));
}
return result;
}
public void init(Configuration config, JCas jcas, Class<? extends Annotation> annotationClass,
Class<? extends Annotation> coveredAnnotationClass) throws UIMAException {
this.configuration = config;
this.annotationClass = annotationClass;
this.coveredAnnotationClass = coveredAnnotationClass;
this.result = new LinkedList<List<Object>>();
TypeSystemDescription tsd;
jcas = JCasFactory.createJCas();
tsd = TypeSystemDescriptionFactory.createTypeSystemDescription();
TypeDescription td = tsd.getType(annotationClass.getName());
type = jcas.getTypeSystem().getType(td.getName());
Type coveredType = null;
if (coveredAnnotationClass != null) {
coveredType = jcas.getTypeSystem().getType(coveredAnnotationClass.getName());
}
columnList = getColumns(jcas, type, coveredType);
String confKey = type.getName().replaceAll("\\.", "..");
String[] confValues = configuration.getString(confKey + ".paths", "").split(",");
String[] confValueLabels = configuration.getString(confKey + ".labels", "").split(",");
for (int i = 0; i < confValues.length; i++) {
String confEntry = confValues[i].trim();
String confEntryLabel = confValueLabels[i].trim();
if (confEntry.equalsIgnoreCase("|DocumentId")) {
columnList.add(0, new Column(new String[] { confEntryLabel }) {
@Override
public Object getValue(Annotation a) {
try {
return DocumentMetaData.get(a.getCAS()).getDocumentId();
} catch (Exception e) {
return "";
}
}
@Override
public boolean isMultiplying() {
return false;
}
});
} else if (confEntry.equalsIgnoreCase("|Length")) {
columnList.add(0, new Column(new String[] { confEntryLabel }) {
@Override
public Object getValue(Annotation a) {
try {
JCas jcas = a.getCAS().getJCas();
return JCasUtil.select(jcas, Token.class).size();
} catch (CASException e) {
e.printStackTrace();
return 0;
}
}
@Override
public boolean isMultiplying() {
return false;
}
});
}
}
// assemble the header
List<Object> header = new LinkedList<Object>();
for (Column ee : columnList) {
for (String s : ee.getLabel()) {
header.add(s);
}
}
result.add(header);
}
private ArrayList<ArrayList<Object>> printFeatureValues(Annotation a, Iterator<Column> eelist) {
ArrayList<ArrayList<Object>> r = new ArrayList<ArrayList<Object>>();
r.add(new ArrayList<Object>());
while (eelist.hasNext()) {
Column ee = eelist.next();
Object value = ee.getValue(a);
if (ee.isMultiplying()) {
ArrayList<ArrayList<ArrayList<Object>>> clones = new ArrayList<ArrayList<ArrayList<Object>>>();
Object[] vals = (Object[]) value;
for (int j = 1; j < vals.length; j++) {
clones.add(deepClone(r));
}
for (List<Object> l : r) {
if (vals.length == 0) {
l.add("");
} else
for (Object o : (Object[]) vals[0]) {
l.add(o);
}
}
for (int j = 1; j < vals.length; j++) {
for (ArrayList<Object> l : clones.get(j - 1)) {
for (Object o : (Object[]) vals[j]) {
l.add(o);
}
}
r.addAll(clones.get(j - 1));
}
} else {
for (List<Object> l : r) {
l.add(value);
}
}
}
return r;
}
private String[] getFeaturePathsForType(Type type) {
String confKey = type.getName().replaceAll("\\.", "..") + ".paths";
String confEntry = configuration.getString(confKey, null);
if (confEntry != null && !confEntry.isEmpty())
return confEntry.split(",");
else
return new String[0];
}
private String[] getColumnHeadersForType(Type type) {
String confKey = type.getName().replaceAll("\\.", "..") + ".labels";
String confEntry = configuration.getString(confKey, null);
if (confEntry != null && !confEntry.isEmpty())
return confEntry.split(",");
else
return new String[0];
}
@SuppressWarnings("unchecked")
private ArrayList<ArrayList<Object>> deepClone(ArrayList<ArrayList<Object>> list) {
ArrayList<ArrayList<Object>> ret = new ArrayList<ArrayList<Object>>();
for (ArrayList<Object> l : list) {
ret.add((ArrayList<Object>) l.clone());
}
return ret;
}
@SuppressWarnings("unchecked")
private List<Column> getColumns(JCas jcas, Type type, Type coveredType) {
List<Column> eelist = new LinkedList<Column>();
for (Feature fd : type.getFeatures()) {
if (fd.getRange().isPrimitive()) {
PrimitiveColumn pee = new PrimitiveColumn(jcas.getTypeSystem().getFeatureByFullName(fd.getName()));
eelist.add(pee);
}
}
String[] paths = this.getFeaturePathsForType(type);
String[] labels = this.getColumnHeadersForType(type);
for (int i = 0; i < paths.length; i++) {
String path = paths[i];
if (path.startsWith("|"))
continue;
FeaturePath fp = jcas.createFeaturePath();
try {
fp.initialize(path);
fp.typeInit(type);
if (labels.length > i) {
eelist.add(new FeaturePathColumn(fp, labels[i]));
} else {
eelist.add(new FeaturePathColumn(fp));
}
} catch (CASException e) {
e.printStackTrace();
}
}
String[] covTypes = this.getCoveringsForType(type);
for (int j = 0; j < covTypes.length; j++) {
paths = getFeaturePathsForType(jcas.getTypeSystem().getType(covTypes[j]));
labels = getColumnHeadersForType(jcas.getTypeSystem().getType(covTypes[j]));
FeaturePath[] path = new FeaturePath[paths.length];
for (int i = 0; i < path.length; i++) {
path[i] = jcas.createFeaturePath();
try {
labels[i] = Class.forName(covTypes[j]).getSimpleName() + "/" + labels[i];
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
try {
path[i].initialize(paths[i]);
path[i].typeInit(jcas.getTypeSystem().getType(covTypes[j]));
} catch (CASException e) {
e.printStackTrace();
}
}
try {
Column ee = new CoveredColumn((Class<? extends Annotation>) Class.forName(covTypes[j]), path);
ee.setLabel(labels);
eelist.add(ee);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
if (coveredType != null)
{
labels = getColumnHeadersForType(coveredType);
paths = getFeaturePathsForType(coveredType);
FeaturePath[] path = new FeaturePath[paths.length];
for (int i = 0; i < path.length; i++) {
path[i] = jcas.createFeaturePath();
try {
labels[i] = coveredType.getShortName() + "/" + labels[i];
path[i].initialize(paths[i]);
path[i].typeInit(coveredType);
} catch (CASException e) {
e.printStackTrace();
}
}
try {
Column ee = new CoveredColumn((Class<? extends Annotation>) Class.forName(coveredType.getName()), path);
ee.setLabel(labels);
eelist.add(ee);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return eelist;
}
private String[] getCoveringsForType(Type type) {
String confKey = type.getName().replaceAll("\\.", "..") + ".covered";
String confEntry = configuration.getString(confKey, null);
if (confEntry != null && !confEntry.isEmpty())
return confEntry.split(",");
else
return new String[0];
}
} |
package edu.mssm.pharm.maayanlab.Enrichr;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.mssm.pharm.maayanlab.FileUtils;
import edu.mssm.pharm.maayanlab.JSONify;
@WebServlet(urlPatterns = {"/genemap"}, loadOnStartup=1)
public class GeneMap extends HttpServlet {
private static final long serialVersionUID = 5506636247908679426L;
private static final HashMap<String, String> backgroundTypes = new HashMap<String, String>() {{
put(Enrichment.BIOCARTA, "%1$s is a member of the %2$s.");
put(Enrichment.CHEA, "%2$s binds to the promoter region of %1$s.");
put(Enrichment.CCLE, "%1$s is up-regulated in %2$s cells.");
put(Enrichment.CHROMOSOME_LOCATION, "%1$s is found in chromosome segment %2$s.");
put(Enrichment.CORUM, "%1$s is part of the %2$s.");
put(Enrichment.UPREGULATED_CMAP, "In cells treated by the drug %2$s, %1$s is up-regulated.");
put(Enrichment.DOWNREGULATED_CMAP, "In cells treated by the drug %2$s, %1$s is down-regulated.");
put(Enrichment.ENCODE, "%2$s binds to the promoter region of %1$s.");
put(Enrichment.GENESIGDB, "%1$s is found in the table of %2$s.");
put(Enrichment.GENOME_BROWSER_PWMS, "%2$s binds to the promoter region of %1$s.");
put(Enrichment.GO_BP, "%1$s is involved in the biological process %2$s.");
put(Enrichment.GO_CC, "%1$s is found in %2$s.");
put(Enrichment.GO_MF, "%1$s has the molecular function of %2$s.");
put(Enrichment.HM, "%1$s is associated with the histone modification, %2$s.");
put(Enrichment.HMDB_METABOLITES, "%2$s is a co-factor of %1$s.");
put(Enrichment.COMPLEXOME, "%1$s was found in a complex with the %2$s complexome.");
put(Enrichment.HUMAN_GENE_ATLAS, "%1$s is up-regulated in %2$s cells.");
put(Enrichment.KEA, "%2$s phosphorylates %1$s.");
put(Enrichment.KEGG, "%1$s is a member of the %2$s pathway.");
put(Enrichment.MGI_MP, "Knockdown of %1$s results in %2$s phenotype.");
put(Enrichment.MICRORNA, "%1$s is the predicted target of %2$s.");
put(Enrichment.MOUSE_GENE_ATLAS, "%1$s is up-regulated in %2$s cells.");
put(Enrichment.NCI60, "%1$s is up-regulated in %2$s cells.");
put(Enrichment.OMIM_DISEASE, "%1$s is associated with the genetic disease %2$s.");
put(Enrichment.OMIM_EXPANDED, "%1$s is associated with a subnetwork around the genetic disease %2$s.");
put(Enrichment.PFAM_INTERPRO, "%1$s has a %2$s protein domain.");
put(Enrichment.PPI_HUB_PROTEINS, "%1$s directly interacts with the hub protein %2$s.");
put(Enrichment.REACTOME, "%1$s is a member of the %2$s pathway.");
put(Enrichment.TRANSFAC_JASPAR, "%2$s has a binding site at the promoter of %1$s.");
put(Enrichment.VIRUSMINT, "%1$s interacts with a viral protein from %2$s.");
put(Enrichment.WIKIPATHWAYS, "%1$s is a member of the %2$s pathway.");
}};
public final HashMap<String, HashMap<String, ArrayList<String>>> geneMap = new HashMap<String, HashMap<String, ArrayList<String>>>();
@Override
public void init() {
constructMap();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
searchQuery(request.getParameter("gene"), response);
}
private void constructMap() {
for (String backgroundType : backgroundTypes.keySet()) {
// Read background list and ranks
Collection<String> backgroundLines = FileUtils.readResource(backgroundType + ".gmt");
for (String line : backgroundLines) {
String[] splitLine = line.split("\t");
String termName = splitLine[0];
for (int i = 2; i < splitLine.length; i++) {
String gene = splitLine[i].toUpperCase();
if (!geneMap.containsKey(gene))
geneMap.put(gene, new HashMap<String, ArrayList<String>>());
if (!geneMap.get(gene).containsKey(backgroundType))
geneMap.get(gene).put(backgroundType, new ArrayList<String>());
geneMap.get(gene).get(backgroundType).add(termName);
}
}
}
for (Iterator<String> geneItr = geneMap.keySet().iterator(); geneItr.hasNext(); ) {
String gene = geneItr.next();
if (geneMap.get(gene).size() < 3)
geneItr.remove();
}
}
private void query(String gene, HttpServletResponse response) {
JSONify json = new JSONify();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
json.add("gene", gene);
}
private void searchQuery(String gene, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HashMap<String, ArrayList<String>> backgrounds = geneMap.get(gene);
if (backgrounds == null) {
out.println("No terms found for gene " + gene + ".");
}
else {
for (String backgroundType : geneMap.get(gene).keySet()) {
String format = backgroundTypes.get(backgroundType);
for (String termName : backgrounds.get(backgroundType)) {
String ans = String.format(format, "<span class=\"gene\">" + gene + "</span>", "<span class=\"term\">" + termName + "</span>");
out.print(ans);
out.println("<br>");
}
}
}
}
} |
package org.apereo.cas.aup;
import org.apereo.cas.authentication.principal.Principal;
import org.apereo.cas.util.CollectionUtils;
import lombok.Data;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;
/**
* This is {@link AcceptableUsagePolicyStatus}.
*
* @author Misagh Moayyed
* @since 6.1.0
*/
@Data
public class AcceptableUsagePolicyStatus implements Serializable {
private final boolean accepted;
private final Principal principal;
private final MultiValuedMap<String, Object> properties = new ArrayListValuedHashMap<>();
/**
* Factory method. Indicate AUP has been accepted.
*
* @param principal the principal
* @return the acceptable usage policy status
*/
public static AcceptableUsagePolicyStatus accepted(final Principal principal) {
return new AcceptableUsagePolicyStatus(true, principal);
}
/**
* Factory method. Indicate AUP has been denied.
*
* @param principal the principal
* @return the acceptable usage policy status
*/
public static AcceptableUsagePolicyStatus denied(final Principal principal) {
return new AcceptableUsagePolicyStatus(false, principal);
}
/**
* Sets property.
*
* @param name the name
* @param value the value
* @return the property
*/
public AcceptableUsagePolicyStatus setProperty(final String name, final Object value) {
this.properties.remove(name);
addProperty(name, value);
return this;
}
/**
* Clear properties.
*
* @return the acceptable usage policy status
*/
public AcceptableUsagePolicyStatus clearProperties() {
this.properties.clear();
return this;
}
/**
* Add property.
*
* @param name the name
* @param value the value
* @return the acceptable usage policy status
*/
public AcceptableUsagePolicyStatus addProperty(final String name, final Object value) {
this.properties.put(name, value);
return this;
}
/**
* Gets property.
*
* @param name the name
* @return the property
*/
public Collection<Object> getProperty(final String name) {
return this.properties.get(name);
}
/**
* Gets property or default.
*
* @param name the name
* @param defaultValue the default value
* @return the property or default
*/
public Collection<Object> getPropertyOrDefault(final String name, final Object defaultValue) {
return getPropertyOrDefault(name, CollectionUtils.wrapList(defaultValue));
}
/**
* Gets property or default.
*
* @param name the name
* @param defaultValues the default values
* @return the property or default
*/
public Collection<Object> getPropertyOrDefault(final String name, final Object... defaultValues) {
if (this.properties.containsKey(name)) {
return this.properties.get(name);
}
return Arrays.stream(defaultValues).collect(Collectors.toList());
}
/**
* Gets property or default.
*
* @param name the name
* @param defaultValues the default values
* @return the property or default
*/
public Collection<Object> getPropertyOrDefault(final String name, final Collection<Object> defaultValues) {
if (this.properties.containsKey(name)) {
return this.properties.get(name);
}
return defaultValues;
}
} |
package eu.fusepool.datalifecycle.utils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
/**
* Provides an utility method to retrieve files paths from a local file system or from
* a remote http server. A file name must end with one of the following extensions: .xml, .rdf.
* An url that does not end with the mentioned extensions is supposed to refer to a folder in a local file
* system (file scheme) or in a remote one (http scheme).
* @author luigi
*
*/
public class FileUtil {
public static ArrayList<String> getFileList(URL url, String [] fileNameExtensions) throws IOException {
ArrayList<String> fileList = new ArrayList<String>();
String scheme = url.getProtocol();
String fileName = url.getFile();
String path = url.getPath();
String ref = url.toString();
boolean isFile = false;
for(int i = 0; i < fileNameExtensions.length; i++){
if(ref.endsWith(fileNameExtensions[i]))
isFile = true;
}
if(isFile){
fileList.add(ref);
}
else {
if("file".equals(scheme)) {
File dir = new File(fileName);
if(dir.isDirectory()) {
String [] files = dir.list();
for(int i = 0; i < files.length; i++ ) {
for(int j = 0; j < fileNameExtensions.length; j++)
if(files[i].endsWith(fileNameExtensions[j]))
fileList.add(scheme + "://" + path + files[i]);
}
}
}
if("http".equals(scheme)){
String html = IOUtils.toString(url);
Pattern pattern = Pattern.compile("(<a href=\")(.*?)(\">)");
Matcher matcher = pattern.matcher(html);
while(matcher.find()){
String match = matcher.group(2);
for(int i = 0; i < fileNameExtensions.length; i++)
if(match.endsWith(fileNameExtensions[i]))
fileList.add(ref + match);
}
}
}
return fileList;
}
public static void main(String [] args) throws IOException {
//String dataurl = "file:///home/luigi/projects/bfh/fusepool/data_sources/patents/MAREC/rdf/00/";
String dataurl = "http://raw.fusepool.info/pmc/Acc_Chem_Res/";
String [] filenameExtension = {".nxml"};
URL url = new URL(dataurl);
ArrayList<String> fileList = FileUtil.getFileList(url, filenameExtension);
Iterator<String> ifile = fileList.iterator();
while(ifile.hasNext()){
System.out.println(ifile.next());
}
}
} |
package eu.ydp.empiria.player.client.module.connection.presenter;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.doReturn;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.gwt.xml.client.Element;
import eu.ydp.empiria.player.client.AbstractJAXBTestBase;
import eu.ydp.empiria.player.client.controller.variables.objects.response.Response;
import eu.ydp.empiria.player.client.controller.variables.processor.item.VariableProcessor;
import eu.ydp.empiria.player.client.controller.variables.processor.item.VariableProcessorTemplate;
import eu.ydp.empiria.player.client.module.ResponseModelChangeListener;
import eu.ydp.empiria.player.client.module.components.multiplepair.MultiplePairModuleConnectType;
import eu.ydp.empiria.player.client.module.components.multiplepair.MultiplePairModuleView;
import eu.ydp.empiria.player.client.module.connection.ConnectionModuleModel;
import eu.ydp.empiria.player.client.module.connection.structure.MatchInteractionBean;
import eu.ydp.empiria.player.client.util.events.multiplepair.PairConnectEvent;
import eu.ydp.empiria.player.client.util.events.multiplepair.PairConnectEventTypes;
import eu.ydp.empiria.player.client.util.file.xml.XmlData;
import eu.ydp.gwtutil.xml.XMLParser;
public class ConnectionModulePresenterJUnitTest extends AbstractJAXBTestBase<MatchInteractionBean> {
private ConnectionModulePresenterImpl connectionModulePresenter;
private MultiplePairModuleView moduleView;
private ConnectionModuleModel connectionModuleModel;
@Test
public void shouldValidateConnectionRequestAsInvalid() {
String source = "CONNECTION_RESPONSE_1_0";
String target = "CONNECTION_RESPONSE_1_3";
PairConnectEvent event = new PairConnectEvent(PairConnectEventTypes.CONNECTED, source, target);
connectionModulePresenter.onConnectionEvent(event);
Mockito.verify(moduleView, Mockito.times(1)).disconnect(source, target);
}
@Test
public void shouldValidateConnectionRequestAsValid() {
PairConnectEvent event = new PairConnectEvent(PairConnectEventTypes.CONNECTED, "CONNECTION_RESPONSE_1_0", "CONNECTION_RESPONSE_1_4");
connectionModulePresenter.onConnectionEvent(event);
Mockito.verify(connectionModuleModel, Mockito.times(1)).addAnswer(event.getItemsPair());
}
@Test
public void shouldDisconnectPairOnDisconnectedEvent() {
PairConnectEvent event = new PairConnectEvent(PairConnectEventTypes.DISCONNECTED, "CONNECTION_RESPONSE_1_0", "CONNECTION_RESPONSE_1_4");
connectionModulePresenter.onConnectionEvent(event);
Mockito.verify(connectionModuleModel, Mockito.times(1)).removeAnswer(event.getItemsPair());
}
@Test
public void markCorrectAnswers() {
connectionModulePresenter.onConnectionEvent(new PairConnectEvent(PairConnectEventTypes.CONNECTED, "CONNECTION_RESPONSE_1_0", "CONNECTION_RESPONSE_1_1"));
connectionModulePresenter.onConnectionEvent(new PairConnectEvent(PairConnectEventTypes.CONNECTED, "CONNECTION_RESPONSE_1_3", "CONNECTION_RESPONSE_1_1"));
connectionModulePresenter.onConnectionEvent(new PairConnectEvent(PairConnectEventTypes.CONNECTED, "CONNECTION_RESPONSE_1_3", "CONNECTION_RESPONSE_1_4"));
doReturn(Arrays.asList(true, false, true)).when(connectionModulePresenter).evaluateResponse();
connectionModulePresenter.markCorrectAnswers();
Mockito.verify(moduleView, Mockito.times(1)).connect("CONNECTION_RESPONSE_1_0", "CONNECTION_RESPONSE_1_1", MultiplePairModuleConnectType.CORRECT);
Mockito.verify(moduleView, Mockito.times(1)).connect("CONNECTION_RESPONSE_1_3", "CONNECTION_RESPONSE_1_4", MultiplePairModuleConnectType.CORRECT);
//Mockito.verify(moduleView, Mockito.times(1)).connect("CONNECTION_RESPONSE_1_3", "CONNECTION_RESPONSE_1_1", MultiplePairModuleConnectType.WRONG);
}
@Before
public void init() {
connectionModulePresenter = spy(new ConnectionModulePresenterImpl());
connectionModuleModel = spy(new ConnectionModuleModel(new Response(mockResponseElement()), mock(ResponseModelChangeListener.class)));
connectionModulePresenter.setModel(connectionModuleModel);
MatchInteractionBean bean = createBeanFromXMLString(mockStructure());
connectionModulePresenter.setBean(bean);
moduleView = mock(MultiplePairModuleView.class);
connectionModulePresenter.setModuleView(moduleView);
}
VariableProcessor mockVariableProcessor() {
XmlData xmlData = mock(XmlData.class);
VariableProcessor variableProcessor = VariableProcessorTemplate.fromNode(xmlData.getDocument().getElementsByTagName("variableProcessing"));
return variableProcessor;
}
private Element mockResponseElement() {
StringBuilder sb = new StringBuilder();
sb.append("<responseDeclaration baseType=\"directedPair\" cardinality=\"multiple\" evaluate=\"user\" identifier=\"CONNECTION_RESPONSE_1\">");
sb.append(" <correctResponse>");
sb.append(" <value>CONNECTION_RESPONSE_1_0 CONNECTION_RESPONSE_1_1</value>");
sb.append(" <value>CONNECTION_RESPONSE_1_3 CONNECTION_RESPONSE_1_4</value>");
sb.append(" </correctResponse>");
sb.append("</responseDeclaration>");
return XMLParser.parse(sb.toString()).getDocumentElement();
}
private String mockStructure() {
return "<matchInteraction id=\"dummy1\" responseIdentifier=\"CONNECTION_RESPONSE_1\" shuffle=\"true\">" +
"<simpleMatchSet>" +
"<simpleAssociableChoice fixed=\"false\" identifier=\"CONNECTION_RESPONSE_1_0\" matchMax=\"2\">" +
"a </simpleAssociableChoice>" +
"<simpleAssociableChoice fixed=\"false\" identifier=\"CONNECTION_RESPONSE_1_3\" matchMax=\"2\">" +
"b </simpleAssociableChoice>" +
"</simpleMatchSet>" +
"<simpleMatchSet>" +
"<simpleAssociableChoice fixed=\"false\" identifier=\"CONNECTION_RESPONSE_1_4\" matchMax=\"2\">" +
"c </simpleAssociableChoice>" +
"<simpleAssociableChoice fixed=\"false\" identifier=\"CONNECTION_RESPONSE_1_1\" matchMax=\"2\">" +
"d </simpleAssociableChoice>" +
"</simpleMatchSet>" +
"</matchInteraction>";
}
// class ConnectionModulePresenterMock extends ConnectionModulePresenterImpl {
// @Override
// List<Boolean> evaluateResponse() {
// VariableProcessor variableProcessor = mockVariableProcessor();
// return variableProcessor.evaluateAnswer(model.getResponse());
} |
package example.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("static_pages")
public class StaticPageController {
@RequestMapping("/")
public String root() {
return "forward:home";
}
@RequestMapping("/home")
public ModelAndView home() {
return new ModelAndView("static_pages/home");
}
@RequestMapping("/help")
public ModelAndView help() {
return new ModelAndView("static_pages/help");
}
@RequestMapping("/about")
public ModelAndView about() {
return new ModelAndView("static_pages/about");
}
} |
package fr.aumgn.bukkitutils.playerref;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
/**
* Hold a reference to a player.
*/
public final class PlayerRef {
private static final Map<String, PlayerRef> playersRef =
new HashMap<String, PlayerRef>();
public static PlayerRef get(OfflinePlayer player) {
return get(player.getName());
}
public static PlayerRef get(String name) {
String lname = name.toLowerCase(Locale.ENGLISH);
if (!playersRef.containsKey(lname)) {
playersRef.put(lname, new PlayerRef(lname));
}
return playersRef.get(lname);
}
private final String name;
private transient WeakReference<Player> ref;
private PlayerRef(String name) {
this.name = name;
this.ref = new WeakReference<Player>(null);
}
public String getName() {
return name;
}
public String getDisplayName() {
Player player = getPlayer();
if (player != null) {
return player.getDisplayName();
} else {
return getName();
}
}
public boolean isOnline() {
return (getPlayer() != null);
}
public boolean isOffline() {
return (getPlayer() == null);
}
public Player getPlayer() {
Player player = ref.get();
if (player == null) {
player = Bukkit.getPlayerExact(name);
ref = new WeakReference<Player>(player);
}
return player;
}
public OfflinePlayer getOfflinePlayer() {
return Bukkit.getOfflinePlayer(name);
}
@Override
public boolean equals(Object other) {
if (!(other instanceof PlayerRef)) {
return false;
}
return name.equals(((PlayerRef) other).name);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return name;
}
} |
package function.genotype.pedmap;
import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.awt.FontMapper;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import function.genotype.base.AnalysisBase4CalledVar;
import function.genotype.base.CalledVariant;
import function.genotype.base.GenotypeLevelFilterCommand;
import function.genotype.base.Sample;
import global.Data;
import function.genotype.base.SampleManager;
import global.Index;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.BufferedOutputStream;
import utils.CommonCommand;
//import utils.ErrorManager;
import utils.LogManager;
import utils.ThirdPartyToolManager;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
//import java.util.function.Function;
//import org.knowm.xchart.XYChartBuilder;
//import org.knowm.xchart.XYSeries;
import java.nio.charset.Charset;
//import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
//import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.HashSet;
//import java.util.logging.Level;
//import java.util.logging.Logger;
import java.util.stream.Collectors;
import utils.ErrorManager;
/*
import org.knowm.xchart.XYChart;
import org.knowm.xchart.internal.chartpart.Chart;
import org.knowm.xchart.XYChartBuilder;
import org.knowm.xchart.style.Styler.LegendPosition;
import org.knowm.xchart.XYSeries;
import org.knowm.xchart.XYSeries.XYSeriesRenderStyle;
import org.knowm.xchart.style.markers.SeriesMarkers;
import org.knowm.xchart.BitmapEncoder;
import org.knowm.xchart.BitmapEncoder.BitmapFormat;
import org.knowm.xchart.VectorGraphicsEncoder;*/
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.SeriesRenderingOrder;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
/**
*
* @author nick
*/
public class PedMapGenerator extends AnalysisBase4CalledVar {
BufferedWriter bwPed = null;
BufferedWriter bwMap = null;
BufferedWriter bwTmpPed = null;
final String pedFile = CommonCommand.outputPath + "output.ped";
final String mapFile = CommonCommand.outputPath + "output.map";
final String tmpPedFile = CommonCommand.outputPath + "output_tmp.ped";
int qualifiedVariants = 0;
// --eigenstrat
private static final String EIGENSTRAT_SCRIPT_PATH = Data.ATAV_HOME + "lib/run_eigenstrat.py";
// --kinship
private static final String KINSHIP_SCRIPT_PATH = Data.ATAV_HOME + "lib/run_kinship.py";
//flashpca
Map<String, SamplePCAInfo> sample_map;
@Override
public void initOutput() {
try {
bwPed = new BufferedWriter(new FileWriter(pedFile));
bwMap = new BufferedWriter(new FileWriter(mapFile));
bwTmpPed = new BufferedWriter(new FileWriter(tmpPedFile));
} catch (Exception ex) {
ErrorManager.send(ex);
}
}
@Override
public void doOutput() {
}
@Override
public void closeOutput() {
try {
bwPed.flush();
bwPed.close();
bwMap.flush();
bwMap.close();
} catch (Exception ex) {
ErrorManager.send(ex);
}
}
@Override
public void doAfterCloseOutput() {
if (PedMapCommand.isEigenstrat) {
doEigesntrat();
}
if (PedMapCommand.isKinship) {
doKinship();
}
if (PedMapCommand.isFlashPCA) {
doFlashPCA();
}
}
@Override
public void beforeProcessDatabaseData() {
}
@Override
public void afterProcessDatabaseData() {
generatePedFile();
}
@Override
public void processVariant(CalledVariant calledVar) {
try {
// ignore MNV
if (calledVar.isMNV()) {
return;
}
doOutput(calledVar);
} catch (Exception ex) {
ErrorManager.send(ex);
}
}
private void doOutput(CalledVariant calledVar) {
try {
qualifiedVariants++;
bwMap.write(calledVar.getChrStr() + "\t"
+ calledVar.getVariantIdStr() + "\t"
+ "0\t"
+ calledVar.getStartPosition());
bwMap.newLine();
outputTempGeno(calledVar);
} catch (Exception ex) {
ErrorManager.send(ex);
}
}
private void generatePedFile() {
try {
LogManager.writeAndPrint("Output the data to ped file now");
bwTmpPed.flush();
bwTmpPed.close();
File tmpFile = new File(tmpPedFile);
RandomAccessFile raf = new RandomAccessFile(tmpFile, "r");
long rowLen = 2 * SampleManager.getTotalSampleNum() + 1L;
for (Sample sample : SampleManager.getList()) {
byte pheno = (byte) (sample.getPheno() + 1);
bwPed.write(sample.getFamilyId() + " "
+ sample.getName() + " "
+ sample.getPaternalId() + " "
+ sample.getMaternalId() + " "
+ sample.getSex() + " "
+ pheno);
for (int i = 0; i < qualifiedVariants; i++) {
for (int j = 0; j < 2; j++) {
long pos = i * rowLen + 2 * sample.getIndex() + j;
raf.seek(pos);
byte allele = raf.readByte();
bwPed.write(" " + String.valueOf((char) allele));
}
}
bwPed.newLine();
}
tmpFile.delete();
} catch (Exception ex) {
ErrorManager.send(ex);
}
}
private void outputTempGeno(CalledVariant calledVar) throws Exception {
for (Sample sample : SampleManager.getList()) {
byte geno = calledVar.getGT(sample.getIndex());
switch (geno) {
case Index.HOM:
if (calledVar.isSnv()) {
bwTmpPed.write(calledVar.getAllele() + calledVar.getAllele());
} else if (calledVar.isDel()) {
bwTmpPed.write("DD");
} else {
bwTmpPed.write("II");
}
break;
case Index.HET:
if (calledVar.isSnv()) {
bwTmpPed.write(calledVar.getRefAllele() + calledVar.getAllele());
} else {
bwTmpPed.write("ID");
}
break;
case Index.REF:
if (calledVar.isSnv()) {
bwTmpPed.write(calledVar.getRefAllele() + calledVar.getRefAllele());
} else if (calledVar.isDel()) {
bwTmpPed.write("II");
} else {
bwTmpPed.write("DD");
}
break;
case Data.BYTE_NA:
bwTmpPed.write("00");
break;
default:
bwTmpPed.write("00");
LogManager.writeAndPrint("Invalid genotype: " + geno
+ " (Variant ID: " + calledVar.getVariantIdStr() + ")");
break;
}
}
bwTmpPed.newLine();
}
public void doEigesntrat() {
String cmd = ThirdPartyToolManager.PYTHON
+ " " + EIGENSTRAT_SCRIPT_PATH
+ " --sample " + GenotypeLevelFilterCommand.sampleFile
+ " --prune-sample"
+ " --genotypefile " + pedFile
+ " --snpfile " + mapFile
+ " --indivfile " + pedFile
+ " --numoutevec 10"
+ " --numoutlieriter 5"
+ " --outputdir " + CommonCommand.realOutputPath;
ThirdPartyToolManager.systemCall(new String[]{"/bin/sh", "-c", cmd});
}
public void doKinship() {
// Convert PED & MAP to BED format with PLINK
String cmd = ThirdPartyToolManager.PLINK
+ " --file " + CommonCommand.outputPath + "output"
+ " --make-bed"
+ " --out " + CommonCommand.outputPath + "plink";
ThirdPartyToolManager.systemCall(new String[]{"/bin/sh", "-c", cmd});
// Run KING to get kinship
cmd = ThirdPartyToolManager.KING
+ " -b " + CommonCommand.outputPath + "plink.bed"
+ " --kinship"
+ " --related"
+ " --degree 3"
+ " --prefix " + CommonCommand.outputPath + "king";
ThirdPartyToolManager.systemCall(new String[]{"/bin/sh", "-c", cmd});
// Run kinship pruning script
cmd = ThirdPartyToolManager.PYTHON
+ " " + KINSHIP_SCRIPT_PATH
+ " " + GenotypeLevelFilterCommand.sampleFile
+ " " + CommonCommand.outputPath + "king.kin0"
+ " " + CommonCommand.outputPath + "king.kin"
+ " --relatedness_threshold " + PedMapCommand.kinshipRelatednessThreshold
+ " --seed " + PedMapCommand.kinshipSeed
+ " --output " + CommonCommand.outputPath + "kinship_pruned_sample.txt"
+ " --verbose";
if (!PedMapCommand.sampleCoverageSummaryPath.isEmpty()) {
cmd += " --sample_coverage_summary " + PedMapCommand.sampleCoverageSummaryPath;
}
ThirdPartyToolManager.systemCall(new String[]{"/bin/sh", "-c", cmd});
}
public static void runPlinkPedToBed(String ip_name, String output_name, String remove_cmd){
LogManager.writeAndPrint("Creating bed file with plink for flashpca");
// Convert PED & MAP to BED format with PLINK
String cmd = ThirdPartyToolManager.PLINK
+ " --noweb "
+ " --file " + CommonCommand.outputPath + ip_name
+ " --make-bed"
+ " --out " + CommonCommand.outputPath + output_name
+ remove_cmd;
//plink output is automatically stored in <outputPath+plink>.log
ThirdPartyToolManager.systemCall(new String[]{"/bin/sh", "-c", cmd});
}
public void runFlashPCA(String ip_name, String out_ext, String logname){
LogManager.writeAndPrint("flashpca for eigenvalues, vectors, pcs and percent variance explained by each pc. #dimenions = " + PedMapCommand.numEvec);
try{
if(PedMapCommand.numEvec <= 0){
throw new IllegalArgumentException("number of eigenvectors as input to flashpca cant be 0");
}
}catch(Exception e){
ErrorManager.send(e);
}
String cmd = ThirdPartyToolManager.FLASHPCA
+ " --bfile " + CommonCommand.outputPath + ip_name
+ " --ndim " + PedMapCommand.numEvec
+ " --outpc " + CommonCommand.outputPath + "pcs" + out_ext
+ " --outvec " + CommonCommand.outputPath + "eigenvectors" + out_ext
+ " --outval " + CommonCommand.outputPath + "eigenvalues" + out_ext
+ " --outpve " + CommonCommand.outputPath + "pve" + out_ext
+ " 2>&1 >> " + CommonCommand.outputPath + logname;
ThirdPartyToolManager.systemCall(new String[]{"/bin/sh", "-c", cmd});
LogManager.writeAndPrint("verify flashpca mean square errors");
cmd = ThirdPartyToolManager.FLASHPCA
+ " -v" + " --bfile " + CommonCommand.outputPath + ip_name
+ " --check "
+ " --outvec " + CommonCommand.outputPath + "eigenvectors" + out_ext
+ " --outval " + CommonCommand.outputPath + "eigenvalues" + out_ext
+ " 2>&1 >> " + CommonCommand.outputPath + logname;
ThirdPartyToolManager.systemCall(new String[]{"/bin/sh", "-c", cmd});
//if condition on rms ; print a warning
try {
Charset charset = Charset.defaultCharset();
List<String> log_lines = Files.readAllLines(Paths.get(CommonCommand.outputPath + logname),charset);
String text = log_lines.get(log_lines.size() - 2);
String[] rms_str;
if(text.contains("Root mean squared error")){
rms_str = text.split(":");
}
else{
throw new NoSuchFieldException("root mean squared error could not be read from flashpca.log file");
}
double rms_val = Double.parseDouble(rms_str[rms_str.length -1].split("\\(")[0].trim());
if (rms_val > 0.0001){
ErrorManager.print("The root mean sq error of flashpca is very high " + Double.toString(rms_val),1);
}
}catch (Exception e){
ErrorManager.send(e);
}
}
public static void findOutliers(){
String cmd = ThirdPartyToolManager.PLINK
+ " --noweb "
+ " --bfile " + CommonCommand.outputPath + "plink";
/*if(PedMapCommand.isppc){
cmd = cmd + " --ppc " + String.valueOf(PedMapCommand.ppc);
}*/
cmd = cmd + " --neighbour 1 " + String.valueOf(PedMapCommand.numNeighbor)
+ " --out " + CommonCommand.outputPath + "plink_outlier"
+ " 2>&1 >> " + CommonCommand.outputPath + "flashpca.log";
ThirdPartyToolManager.systemCall(new String[]{"/bin/sh", "-c", cmd});
}
public void doFlashPCA() {
//i wanted to test for existence of bed file but can't say if the bed is current or of old run
runPlinkPedToBed("output","plink","");
String out_ext = "_flashpca";
runFlashPCA("plink",out_ext,"flashpca.log");
getevecDatafor1DPlot(CommonCommand.outputPath + "eigenvalues" + out_ext,CommonCommand.outputPath + "plot_eigenvalues_flashpca.pdf",PedMapCommand.numEvec,"eigenvalues","plot of eigenvalues","eigenvalue number","eigenvalue");
getevecDatafor1DPlot(CommonCommand.outputPath + "pve" + out_ext,CommonCommand.outputPath + "plot_pve_flashpca.pdf",PedMapCommand.numEvec,"percent variance","percent_variance explained by eigval","eigenvalue number","per_var_explained");
int ndim = 3;
if(PedMapCommand.numEvec < 3){
LogManager.writeAndPrint("number of dimensions to plot can't be greater than total number of eigenvectors");
ndim = PedMapCommand.numEvec;
}
ArrayList<Sample> sample_info = SampleManager.getList();
getdata_dim123(ndim,CommonCommand.outputPath + "eigenvectors" + out_ext,CommonCommand.outputPath + "pcs" + out_ext,sample_info);
Plot2DData(ndim, false,CommonCommand.outputPath + "plot_eigenvectors_flashpca.pdf");
LogManager.writeAndPrint("finding outliers using plink ibs clustering");
if(! PedMapCommand.isKeepOutliers){
findOutliers();
//read each line of outlier nearest file and filter based on Z-score, prop_diff parameters
HashSet<String> outlierSet = getOutliers(CommonCommand.outputPath + "plink_outlier.nearest", CommonCommand.outputPath + "outlier_file.txt");
generateNewSampleFile(outlierSet,GenotypeLevelFilterCommand.sampleFile,"pruned_sample_file.txt");//generate new sample file, can't simly change fam file
LogManager.writeAndPrint("redo flashpca with outliers removed");
String remove_cmd = " --remove " + CommonCommand.outputPath + "outlier_file.txt";
sample_map.entrySet().stream().forEach(e->e.getValue().setOutlier(outlierSet));
Plot2DData(ndim,true,CommonCommand.outputPath + "plot_eigenvectors_flashpca_color_outliers.pdf");//cases,controls.outliers - 3 colors
runPlinkPedToBed("output","plink_outlier_removed",remove_cmd);
out_ext = "_flashpca_outliers_removed";
runFlashPCA("plink_outlier_removed",out_ext,"flashpca.log");
//making plots with / without outlier
getevecDatafor1DPlot(CommonCommand.outputPath + "eigenvalues" + out_ext,CommonCommand.outputPath + "eigenvalues_flashpca_outliers_removed.pdf",PedMapCommand.numEvec,"eigenvalues no outliers","plot of eigenvalues","eigenvalue number","eigenvalue");
getevecDatafor1DPlot(CommonCommand.outputPath + "pve" + out_ext,CommonCommand.outputPath + "pve_flashpca_outliers_removed.pdf",PedMapCommand.numEvec,"percent variance no outliers","percent variance explained by eigval","eigenvalue number","per_var_explained");
sample_info = sample_map.values().stream().filter(s->!s.isOutlier()).map(SamplePCAInfo::getSample).collect(Collectors.toCollection(ArrayList::new));
getdata_dim123(ndim,CommonCommand.outputPath + "eigenvectors" + out_ext,CommonCommand.outputPath + "pcs" + out_ext,sample_info);
Plot2DData(ndim, false,CommonCommand.outputPath + "plot_eigenvectors_flashpca_outliers_removed.pdf");
}
}
public void Plot2DData(int ndim, boolean with_out, String pdf_name){
int numCharts = 2;
if(ndim == 3){
numCharts = 6;
}
List<JFreeChart> charts = new ArrayList<>(numCharts);
if(ndim == 1){
charts.add(buildChartPcs(with_out,-1,0));
charts.add(buildChartEvec(with_out,-1,0));
}else if(ndim == 2){
//numCharts = 2;//4 or 6 2D series
charts.add(buildChartPcs(with_out,0,1));
charts.add(buildChartEvec(with_out,0,1));
}else{
//numCharts = 6;//12 or 18 2D series
charts.add(buildChartPcs(with_out,0,1));
charts.add(buildChartEvec(with_out,0,1));
charts.add(buildChartPcs(with_out,1,2));
charts.add(buildChartEvec(with_out,1,2));
charts.add(buildChartPcs(with_out,0,2));
charts.add(buildChartEvec(with_out,0,2));
}
saveChartAsPDF(pdf_name,charts,630,1100);
}
public JFreeChart buildChartPcs(boolean with_out,int dim1, int dim2){
XYSeries outlier_series = new XYSeries("outlier");
XYSeries case_series = new XYSeries("case");
XYSeries ctrl_series = new XYSeries("control");
String plotName, xlabel, ylabel;
int count_case, count_ctrl, count_out;
count_out = count_ctrl = count_case = 0;
if(dim1 == -1){
plotName = "principal components (pc) 1D scatter plot";
xlabel = "sample number";
ylabel = "pc in 1D";
for(SamplePCAInfo map_val:sample_map.values()){
if(with_out && map_val.isOutlier()){
outlier_series.add(count_out++,map_val.getPCAInfoPcs(dim2));
}else{
if(map_val.getPheno() == 0){
ctrl_series.add(count_ctrl++,map_val.getPCAInfoPcs(dim2));
}else{
case_series.add(count_case++,map_val.getPCAInfoPcs(dim2));
}
}
}
}else{
plotName = "principal components (pc) 2D scatter plot";
xlabel = "pc dim " + Integer.toString(dim1+1);
ylabel = "pc dim " + Integer.toString(dim2+1);
for(SamplePCAInfo map_val:sample_map.values()){
double[] pcs_data = map_val.getPCAInfoPcs(dim1,dim2);
if(with_out && map_val.isOutlier()){
outlier_series.add(pcs_data[0],pcs_data[1]);
count_out ++;
}else{
if(map_val.getPheno() == 0){
ctrl_series.add(pcs_data[0],pcs_data[1]);
count_ctrl++;
}else{
case_series.add(pcs_data[0],pcs_data[1]);
count_case++;
}
}
}
}
System.out.println("original number of cases :" + SampleManager.getCaseNum());
System.out.println("original number of controls :" + SampleManager.getCtrlNum());
System.out.println("number of cases :" + count_case);
System.out.println("number of controls :" + count_ctrl);
System.out.println("number of outliers :" + count_out);
XYSeriesCollection data_collection = new XYSeriesCollection( );
data_collection.addSeries(ctrl_series);
data_collection.addSeries(case_series);
if(with_out){
data_collection.addSeries(outlier_series);
}
JFreeChart chart_op = ChartFactory.createScatterPlot(plotName, xlabel, ylabel, data_collection, PlotOrientation.HORIZONTAL, true, true, false);
//setting series colors - blue = case, green = control, red = outliers if they exist
XYPlot plot_op = (XYPlot) chart_op.getPlot();
plot_op.getRenderer().setSeriesPaint(0,new Color(0x00, 0xFF, 0x00)); //ctrl = green
plot_op.getRenderer().setSeriesPaint(1,new Color(0x00, 0x00, 0xFF)); //case = blue
if(with_out){
plot_op.getRenderer().setSeriesPaint(2,new Color(0xFF, 0x00, 0x00)); //outlier = red
}
plot_op.setSeriesRenderingOrder(SeriesRenderingOrder.FORWARD);
return chart_op;
}
public JFreeChart buildChartEvec(boolean with_out,int dim1, int dim2){
XYSeries outlier_series = new XYSeries("outlier");
XYSeries case_series = new XYSeries("case");
XYSeries ctrl_series = new XYSeries("control");
String plotName, xlabel, ylabel;
if(dim1 == -1){
plotName = "eigenvector (ev) 1D scatter plot";
int count_out = 0;
int count_case = 0;
int count_ctrl = 0;
xlabel = "sample number";
ylabel = "ev in 1D";
for(SamplePCAInfo map_val:sample_map.values()){
if(with_out && map_val.isOutlier()){
outlier_series.add(count_out++,map_val.getPCAInfoEvec(dim2));
}else{
if(map_val.getPheno() == 0){
ctrl_series.add(count_ctrl++,map_val.getPCAInfoEvec(dim2));
}else{
case_series.add(count_case++,map_val.getPCAInfoEvec(dim2));
}
}
}
}else{
plotName = "eigenvector (ev) 2D scatter plot";
xlabel = "ev dim " + Integer.toString(dim1+1);
ylabel = "ev dim " + Integer.toString(dim2+1);
for(SamplePCAInfo map_val:sample_map.values()){
double[] evec_data = map_val.getPCAInfoEvec(dim1,dim2);
if(with_out && map_val.isOutlier()){
outlier_series.add(evec_data[0],evec_data[1]);
}else{
if(map_val.getPheno() == 0){
ctrl_series.add(evec_data[0],evec_data[1]);
}else{
case_series.add(evec_data[0],evec_data[1]);
}
}
}
}
XYSeriesCollection data_collection = new XYSeriesCollection( );
data_collection.addSeries(ctrl_series);
data_collection.addSeries(case_series);
if(with_out){
data_collection.addSeries(outlier_series);
}
JFreeChart chart_op = ChartFactory.createScatterPlot(plotName, xlabel, ylabel, data_collection, PlotOrientation.HORIZONTAL, true, true, false);
//setting series colors - blue = case, green = control, red = outliers if they exist
XYPlot plot_op = (XYPlot) chart_op.getPlot();
plot_op.getRenderer().setSeriesPaint(0,new Color(0x00, 0xFF, 0x00)); //ctrl = green
plot_op.getRenderer().setSeriesPaint(1,new Color(0x00, 0x00, 0xFF)); //case = blue
if(with_out){
plot_op.getRenderer().setSeriesPaint(2,new Color(0xFF, 0x00, 0x00)); //outlier = red
}
plot_op.setSeriesRenderingOrder(SeriesRenderingOrder.FORWARD);
return chart_op;
}
public static void generateNewSampleFile(HashSet<String> outlierSet,String sample_file, String output_file){
try{
FileWriter fw = new FileWriter(CommonCommand.outputPath + output_file);
Files.lines(Paths.get(sample_file))
.map(line -> line.split("\\t"))
.filter(line -> !outlierSet.contains(line[1]) )
.forEach(line -> printLine(fw,line));
}catch(Exception e){
ErrorManager.send(e);
}
}
private static void printLine(FileWriter fw, String[] line){
try{
fw.write(String.join("\\t", line) + "\n");
}catch(Exception e){
ErrorManager.send(e);
}
}
public static HashSet<String> getOutliers(String filename, String outlierFile){
HashSet<String> outlierSet = new HashSet<>();
float z_thresh_sum = PedMapCommand.z_thresh * PedMapCommand.numNeighbor;
try (BufferedReader br = new BufferedReader(new FileReader(filename));
BufferedWriter writer = new BufferedWriter(new FileWriter(outlierFile))) {
String[] header = br.readLine().replaceAll("^\\s+","").split(" +");
if(!"Z".equals(header[4])){
throw new IllegalArgumentException("column names in nearest neighbor file " + filename + " are incorrect");
}
writer.write(header[0] + "\t" + header[1] + "\n");
String line;
int count_line = 1;
String iid_curr = "";
String fid_curr = "";
float sum_z = 0.0f;
while ((line = br.readLine()) != null) {
String[] data_str_line = line.replaceAll("^\\s+","").split(" +");
if( !data_str_line[0].equals(fid_curr) || !data_str_line[1].equals(iid_curr) || count_line == 1){
if(sum_z < z_thresh_sum){
System.out.println(data_str_line[0] + "\t" + data_str_line[1]);
writer.write(data_str_line[0] + "\t" + data_str_line[1] + "\n");
outlierSet.add(data_str_line[1]);
}
count_line = PedMapCommand.numNeighbor;
fid_curr = data_str_line[0];
iid_curr = data_str_line[1];
sum_z = Float.valueOf(data_str_line[4]);
}
else{
count_line = count_line - 1;
sum_z = sum_z + Float.valueOf(data_str_line[4]);
}
}
}catch(Exception e){
ErrorManager.send(e);
}
System.out.println("size of outlier set: " + outlierSet.size());
return outlierSet;
}
public void getdata_dim123(int ndim, String evec_fileName, String pcs_fileName, ArrayList<Sample> sample_info){
sample_map = sample_info.stream().collect(Collectors.toMap(Sample::getName,s -> new SamplePCAInfo(s,ndim)));
System.out.println("files from which we're reading; evec: " + evec_fileName + " pcs: " + pcs_fileName);
try {
BufferedReader br_evec = new BufferedReader(new FileReader(evec_fileName));
BufferedReader br_pcs = new BufferedReader(new FileReader(pcs_fileName));
br_evec.readLine();
br_pcs.readLine();
String evec_line;
String pcs_line;
while ((evec_line = br_evec.readLine()) != null && (pcs_line = br_pcs.readLine()) != null) {
String[] evec_str_line = evec_line.split("\\t");
String[] pcs_str_line = pcs_line.split("\\t");
if(sample_map.containsKey(evec_str_line[1])){
sample_map.get(evec_str_line[1]).setEvec(ndim,evec_str_line);
sample_map.get(evec_str_line[1]).setPcs(ndim,pcs_str_line);
}
}
}catch(Exception e){
ErrorManager.send(e);
}
}
public static void saveChartAsPDF(String filename,List<JFreeChart> charts, float ht, float wth){
try{
Document document = new Document(new Rectangle(wth,ht),0,0,0,0);
//Document document = new Document(PageSize.A0);
document.addAuthor("atav");
document.addSubject("flashpca_plot");
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
document.open();
PdfContentByte cb = writer.getDirectContent();
//writeChartAsPDF(cb, chart, PageSize.LETTER.getWidth(), PageSize.LETTER.getHeight(),true);
float ind_width = wth;
float ind_ht = ht;
int num_charts_x = 1;
int num_charts_y = 1;
if(charts.size() > 2){
ind_width = wth/3;
num_charts_x = 3;
}
if(charts.size() > 1){
ind_ht = ht / 2;
num_charts_y = 2;
}
int counter = 0;
float curr_ht = 0;
float curr_wth = 0;
for(int i =0;i < num_charts_x;i++){
for(int j=0;j<num_charts_y;j++){
PdfTemplate tp = cb.createTemplate(ind_width,ind_ht);
Graphics2D g2 = new PdfGraphics2D(tp, ind_width, ind_ht);
Rectangle2D r2D = new Rectangle2D.Double(0, 0, ind_width, ind_ht);
charts.get(counter).draw(g2,r2D,null);
g2.dispose();
cb.addTemplate(tp, curr_wth, curr_ht);
//curr_wth = curr_wth + ind_width;
curr_ht = curr_ht + ind_ht;
counter = counter + 1;
}
curr_ht = 0;
curr_wth = curr_wth + ind_width;
}
document.close();
}catch(Exception e){
ErrorManager.send(e);
}
}
public void getevecDatafor1DPlot(String input_filename, String pdf_filename, int ndim, String plotname, String plot_title, String x_name, String y_name ){
Charset charset = Charset.defaultCharset();
//double[] xdata = new double[ndim];
XYSeries xydata = new XYSeries( plotname );
try{
List<String> fileLines;
fileLines = Files.readAllLines(Paths.get(input_filename),charset);
if (fileLines.size() != ndim){
String message;
message = String.format("File %s has too many lines. #lines must equal #pcs!", input_filename);
throw new IllegalArgumentException(message);
}
for (int i =0;i < fileLines.size(); i++) {
xydata.add(i+1,Double.parseDouble(fileLines.get(i)));
}
XYSeriesCollection dataset = new XYSeriesCollection( );
dataset.addSeries(xydata);
List<JFreeChart> charts = new ArrayList<>(1);
charts.add(ChartFactory.createXYLineChart(plot_title, x_name, y_name, (XYDataset) dataset, PlotOrientation.VERTICAL ,true , true , false));
saveChartAsPDF(pdf_filename, charts,630,1100);
} catch ( IllegalArgumentException e){
ErrorManager.send(e);
}
catch ( Exception e){
ErrorManager.send(e);
}
}
@Override
public String toString() {
return "Start generating ped/map files";
}
} |
package gov.nasa.jpl.mbee.mdk.model;
import com.nomagic.generictable.GenericTableManager;
import com.nomagic.magicdraw.core.Application;
import com.nomagic.magicdraw.openapi.uml.SessionManager;
import com.nomagic.magicdraw.properties.ElementListProperty;
import com.nomagic.magicdraw.properties.ElementProperty;
import com.nomagic.magicdraw.properties.Property;
import com.nomagic.magicdraw.properties.StringProperty;
import com.nomagic.uml2.ext.jmi.helpers.ModelHelper;
import com.nomagic.uml2.ext.jmi.helpers.StereotypesHelper;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Diagram;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.NamedElement;
import gov.nasa.jpl.mbee.mdk.docgen.DocGenProfile;
import gov.nasa.jpl.mbee.mdk.docgen.docbook.*;
import gov.nasa.jpl.mbee.mdk.generator.DiagramTableTool;
import gov.nasa.jpl.mbee.mdk.util.GeneratorUtils;
import gov.nasa.jpl.mbee.mdk.util.Utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class GenericTable extends Table {
private List<String> headers;
private boolean skipIfNoDoc;
private static ArrayList<String> skipColumnIDs = new ArrayList<String>() {{
add("QPROP:Element:isEncapsulated");
add("QPROP:Element:CUSTOM_IMAGE");
}};
private int numCols = 0;
// @SuppressWarnings("unchecked")
// public List<List<DocumentElement>> getHeaders(Diagram d, List<String> columnIds, DiagramTableTool dtt) {
// List<List<DocumentElement>> res = new ArrayList<List<DocumentElement>>();
// if (this.headers != null && !this.headers.isEmpty()) {
// List<DocumentElement> row = new ArrayList<DocumentElement>();
// for (String h : this.headers) {
// row.add(new DBText(h));
// res.add(row);
// } else if (StereotypesHelper.hasStereotypeOrDerived(d, DocGenProfile.headersChoosable)) {
// List<DocumentElement> row = new ArrayList<DocumentElement>();
// for (String h : (List<String>) StereotypesHelper.getStereotypePropertyValue(d, DocGenProfile.headersChoosable, "headers")) {
// row.add(new DBText(h));
// res.add(row);
// } else {
// List<DocumentElement> row = new ArrayList<DocumentElement>();
// int count = 0;
// for (String s : dtt.getColumnNames(d, columnIds)) {
// if (count == 0) {
// count++;
// continue;
// row.add(new DBText(s));
// res.add(row);
// return res;
public List<List<DocumentElement>> getHeaders(Diagram d, List<String> columnIds, GenericTableManager gtm) {
List<List<DocumentElement>> res = new ArrayList<List<DocumentElement>>();
if (this.headers != null && !this.headers.isEmpty()) {
List<DocumentElement> row = new ArrayList<DocumentElement>();
for (String h : this.headers) {
row.add(new DBText(h));
}
res.add(row);
} else if (StereotypesHelper.hasStereotypeOrDerived(d, DocGenProfile.headersChoosable)) {
List<DocumentElement> row = new ArrayList<DocumentElement>();
for (String h : (List<String>) StereotypesHelper.getStereotypePropertyValue(d, DocGenProfile.headersChoosable, "headers")) {
row.add(new DBText(h));
}
res.add(row);
} else {
List<DocumentElement> row = new ArrayList<DocumentElement>();
int count = 0;
for (String columnid : columnIds) {
if (count == 0) {
count++;
continue;
}
if (!skipColumnIDs.contains(columnid)) {
row.add(new DBText(gtm.getColumnNameById(d, columnid)));
numCols++;
}
}
res.add(row);
}
return res;
}
// public List<List<DocumentElement>> getBody(Diagram d, List<Element> rowElements, List<String> columnIds,
// DiagramTableTool dtt, boolean forViewEditor) {
// List<List<DocumentElement>> res = new ArrayList<>();
// for (Element e : rowElements) {
// if (skipIfNoDoc && ModelHelper.getComment(e).trim().isEmpty()) {
// continue;
// List<DocumentElement> row = new ArrayList<>();
// int count = 0;
// for (String cid : columnIds) {
// if (count == 0) {
// count++;
// continue;
// row.add(Common.getTableEntryFromObject(getTableValues(dtt.getCellValue(d, e, cid))));
// res.add(row);
// return res;
public List<List<DocumentElement>> getBody(Diagram d, List<Element> rowElements, List<String> columnIds,
GenericTableManager gtm, boolean forViewEditor) {
List<List<DocumentElement>> res = new ArrayList<>();
for (Element e : rowElements) {
if (skipIfNoDoc && ModelHelper.getComment(e).trim().isEmpty()) {
continue;
}
List<DocumentElement> row = new ArrayList<>();
int count = 0;
for (String cid : columnIds) {
if (count == 0) {
count++;
continue;
}
if (skipColumnIDs.contains(cid)) {
continue;
}
DBTableEntry entry = new DBTableEntry();
Property cellValue = gtm.getCellValue(d, e, cid);
if (cellValue instanceof ElementProperty) {
Element cellelement = ((ElementProperty) cellValue).getElement();
if (cellelement instanceof NamedElement) {
entry.addElement(new DBParagraph(((NamedElement) cellelement).getName(), cellelement, From.NAME));
}
} else if (cellValue instanceof StringProperty) {
entry.addElement(new DBParagraph(cellValue.getValue()));
} else if (cellValue instanceof ElementListProperty) {
for (Element listEl : ((ElementListProperty) cellValue).getValue()) {
if (listEl instanceof NamedElement) {
entry.addElement(new DBParagraph(((NamedElement) listEl).getName(), listEl, From.NAME));
}
}
} else {
System.out.print("[WARNING] Not added : " + cellValue.toString() + " ");
}
row.add(entry);
}
res.add(row);
}
return res;
}
@SuppressWarnings("rawtypes")
public List<Object> getTableValues(Object o) {
List<Object> res = new ArrayList<>();
if (o instanceof Object[]) {
Object[] a = (Object[]) o;
for (int i = 0; i < a.length; i++) {
res.addAll(getTableValues(a[i]));
}
} else if (o instanceof Collection) {
for (Object oo : (Collection) o) {
res.addAll(getTableValues(oo));
}
} else if (o != null) {
res.add(o);
}
return res;
}
public void setSkipIfNoDoc(boolean b) {
skipIfNoDoc = b;
}
public void setHeaders(List<String> h) {
headers = h;
}
@Override
public List<DocumentElement> visit(boolean forViewEditor, String outputDir) {
List<DocumentElement> res = new ArrayList<DocumentElement>();
DiagramTableTool dtt = new DiagramTableTool();
if (getIgnore()) {
return res;
}
SessionManager.getInstance().createSession(Application.getInstance().getProject(), "Reading Generic Table");
int tableCount = 0;
List<Object> targets = isSortElementsByName() ? Utils.sortByName(getTargets()) : getTargets();
for (Object e : targets) {
if (e instanceof Diagram) {
Diagram diagram = (Diagram) e;
if (Application.getInstance().getProject().getDiagram(diagram).getDiagramType().getType()
.equals("Generic Table")) {
DBTable t = new DBTable();
GenericTableManager gtm = new GenericTableManager();
//gtm.getCellValue(diagram, , "");
// String columnid = gtm.getColumnIDByPropertyName("Owner");
// List<Element> list = gtm.getRowElements(diagram);
// List<String> columns = gtm.getColumnIds(diagram);
// for (Element element : list) {
// System.out.println("Row: " + element.getHumanName());
// for (String columnid : columns) {
// System.out.print("Column: " + columnid + " ");
// Property value = gtm.getCellValue(diagram, element, columnid);
// if (value != null) {
// System.out.print("CellValue: " + value.getName() + " ");
// if (value instanceof ElementProperty) {
// Element cellelement = ((ElementProperty) value).getElement();
// System.out.print("ElementProperty Element: " + cellelement.getHumanName() + " ");
// } else if (value instanceof StringProperty) {
// System.out.print("StringProperty: " + ((StringProperty) value).getString() + " ");
// } else if (value instanceof ElementListProperty) {
// ElementListProperty elp = (ElementListProperty) value;
// for (Element listEl : ((ElementListProperty) value).getValue()) {
// System.out.println("listel: " + listEl.getHumanName() + ", ");
// } else {
// System.out.print("Or: " + value.toString() + " ");
List<String> columnIds = gtm.getColumnIds(diagram);
//List<String> columnIds = dtt.getColumnIds(diagram);
t.setHeaders(getHeaders(diagram, columnIds, gtm));
//t.setHeaders(getHeaders(diagram, columnIds, dtt));
List<Element> rowElements = gtm.getRowElements(diagram);
//List<Element> rowElements = dtt.getRowElements(diagram);
t.setBody(getBody(diagram, rowElements, columnIds, gtm, forViewEditor));
//t.setBody(getBody(diagram, rowElements, columnIds, dtt, forViewEditor));
if (getTitles() != null && getTitles().size() > tableCount) {
t.setTitle(getTitlePrefix() + getTitles().get(tableCount) + getTitleSuffix());
} else {
t.setTitle(getTitlePrefix() + (diagram).getName() + getTitleSuffix());
}
if (getCaptions() != null && getCaptions().size() > tableCount && isShowCaptions()) {
t.setCaption(getCaptions().get(tableCount));
} else {
t.setCaption(ModelHelper.getComment(diagram));
}
//t.setCols(columnIds.size() - 1);
t.setCols(numCols);
res.add(t);
t.setStyle(getStyle());
tableCount++;
}
}
}
SessionManager.getInstance().closeSession(Application.getInstance().getProject());
dtt.closeOpenedTables();
return res;
}
@SuppressWarnings("unchecked")
@Override
public void initialize() {
super.initialize();
setHeaders((List<String>) GeneratorUtils.getListProperty(dgElement, DocGenProfile.headersChoosable,
"headers", new ArrayList<String>()));
setSkipIfNoDoc((Boolean) GeneratorUtils.getObjectProperty(dgElement, DocGenProfile.docSkippable,
"skipIfNoDoc", false));
}
} |
package gr.forth.ics.isl.example;
import eu.delving.x3ml.X3MLEngineFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import org.apache.jena.riot.Lang;
/**
* @author Yannis Marketakis (marketak 'at' ics 'dot' forth 'dot' gr)
* @author Nikos Minadakis (minadakn 'at' ics 'dot' forth 'dot' gr)
*/
public class X3MLFactoryUser {
/* The simplest possible senario. Add only the mandatory details */
private static void simplestScenario(){
X3MLEngineFactory.create()
.withMappings(new File("example/mappingsWithoutGenerator.x3ml"))
.withInputFiles(new File("example/input.xml"))
.execute();
}
/* Playing with generator policies and UUID sizes */
private static void withGeneratorPolicyScenario() throws FileNotFoundException{
X3MLEngineFactory.create()
.withMappings(new File("example/mappings.x3ml"))
.withInputFiles(new File("example/input.xml"))
.withUuidSize(2)
.withGeneratorPolicy(new File("example/generator-policy.xml"))
.execute();
}
/* Playing with multiple files */
private static void multipleInputFilesScenario(){
X3MLEngineFactory.create()
.withMappings(new File("example/mappingsWithoutGenerator.x3ml"))
.withInputFiles(new File("example/input.xml"))
.withInputFiles(new File("example/moreExamples/input1.xml"), new File("example/moreExamples/input2.xml"))
.execute();
}
/* Playing with multiple mapping files */
private static void multipleMappingFilesScenario(){
X3MLEngineFactory.create()
.withMappings(new File("example/mappingsWithoutGenerator.x3ml"), new File("example/mappingsWithoutGenerator2.x3ml"))
.withInputFiles(new File("example/input.xml"))
.execute();
}
/* Playing with multiple folders */
private static void multipleFilesAndFoldersScenario(){
X3MLEngineFactory.create()
.withMappings(new File("example/mappingsWithoutGenerator.x3ml"))
.withInputFiles(new File("example/input.xml"))
.withInputFolder(new File("example/moreExamples"), true)
.execute();
}
/* Playing with different output and output formats */
private static void outputFormatsScenario(){
X3MLEngineFactory.create()
.withMappings(new File("example/mappingsWithoutGenerator.x3ml"))
.withInputFiles(new File("example/input.xml"))
.withOutput("output.ntriples", X3MLEngineFactory.OutputFormat.NTRIPLES)
.execute();
X3MLEngineFactory.create()
.withMappings(new File("example/mappingsWithoutGenerator.x3ml"))
.withInputFiles(new File("example/input.xml"))
.withOutput(new File("output.rdf"), X3MLEngineFactory.OutputFormat.RDF_XML)
.execute();
}
/* Export the contents of the association table */
private static void exportAssocTableScenario(){
X3MLEngineFactory.create()
.withMappings(new File("example/mappingsWithoutGenerator.x3ml"))
.withInputFiles(new File("example/input.xml"))
.withAssociationTable("target/AssociationTable.xml")
.execute();
}
/* Produce more verbose logging output */
private static void verboseOutputScenario(){
X3MLEngineFactory.create()
.withVerboseLogging()
.withMappings(new File("example/mappingsWithoutGenerator.x3ml"))
.withInputFiles(new File("example/input.xml"))
.withProgressReporting()
.execute();
}
/* Playing with terminologies */
private static void terminologiesScenario(){
X3MLEngineFactory.create()
.withMappings(new File("example/moreExamples/terminologies/mappings.x3ml"))
.withInputFiles(new File("example/moreExamples/terminologies/input.xml"))
.withGeneratorPolicy(new File("example/generator-policy.xml"))
.withTerminology(new File("example/moreExamples/terminologies/terms.nt"), Lang.NT)
.execute();
}
/* The simplest possible senario. Add only the mandatory details */
private static void simplestStreamScenario() throws FileNotFoundException{
X3MLEngineFactory.create()
.withMappings(new FileInputStream(new File("example/mappingsWithoutGenerator.x3ml")))
.withInput(new FileInputStream(new File("example/input.xml")))
.execute();
}
/* Playing with generator policies and UUID sizes */
private static void withGeneratorPolicyStreamScenario() throws FileNotFoundException{
X3MLEngineFactory.create()
.withMappings(new FileInputStream(new File("example/mappings.x3ml")))
.withInput(new FileInputStream(new File("example/input.xml")))
.withUuidSize(2)
.withGeneratorPolicy(new FileInputStream(new File("example/generator-policy.xml")))
.execute();
}
/* Playing with multiple files */
private static void multipleInputStreamsScenario() throws FileNotFoundException{
X3MLEngineFactory.create()
.withMappings(new FileInputStream(new File("example/mappingsWithoutGenerator.x3ml")))
.withInput(new FileInputStream(new File("example/input.xml")))
.withInput(new FileInputStream(new File("example/moreExamples/input1.xml")),
new FileInputStream(new File("example/moreExamples/input2.xml")))
.execute();
}
/* Playing with multiple mapping files */
private static void multipleMappingStreamsScenario() throws FileNotFoundException{
X3MLEngineFactory.create()
.withMappings(new FileInputStream(new File("example/mappingsWithoutGenerator.x3ml")),
new FileInputStream(new File("example/mappingsWithoutGenerator2.x3ml")))
.withInput(new FileInputStream(new File("example/input.xml")))
.execute();
}
/* Playing with different output and output formats using streams */
private static void outputFormatsStreamsScenario() throws FileNotFoundException{
X3MLEngineFactory.create()
.withMappings(new File("example/mappingsWithoutGenerator.x3ml"))
.withInputFiles(new File("example/input.xml"))
.withOutput(System.out, X3MLEngineFactory.OutputFormat.RDF_XML)
.execute();
X3MLEngineFactory.create()
.withMappings(new File("example/mappingsWithoutGenerator.x3ml"))
.withInputFiles(new File("example/input.xml"))
.withOutput(new PrintStream(new File("output.rdf")), X3MLEngineFactory.OutputFormat.RDF_XML)
.execute();
}
/* Playing with terminologies */
private static void terminologiesStreamsScenario() throws FileNotFoundException{
X3MLEngineFactory.create()
.withMappings(new File("example/moreExamples/terminologies/mappings.x3ml"))
.withInputFiles(new File("example/moreExamples/terminologies/input.xml"))
.withGeneratorPolicy(new File("example/generator-policy.xml"))
.withTerminology(new FileInputStream(new File("example/moreExamples/terminologies/terms.nt")), Lang.NT)
.execute();
}
public static void main(String[] args) throws FileNotFoundException{
simplestScenario();
withGeneratorPolicyScenario();
multipleInputFilesScenario();
multipleMappingFilesScenario();
multipleFilesAndFoldersScenario();
outputFormatsScenario();
exportAssocTableScenario();
verboseOutputScenario();
terminologiesScenario();
/* Using Streams */
simplestStreamScenario();
withGeneratorPolicyStreamScenario();
multipleInputStreamsScenario();
multipleMappingStreamsScenario();
outputFormatsStreamsScenario();
terminologiesStreamsScenario();
}
} |
package hudson.plugins.promoted_builds;
import hudson.EnvVars;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Cause.LegacyCodeCause;
import hudson.model.Hudson;
import hudson.model.Node;
import hudson.model.Result;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.slaves.WorkspaceList;
import hudson.slaves.WorkspaceList.Lease;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildTrigger;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
/**
* Records a promotion process.
*
* @author Kohsuke Kawaguchi
*/
public class Promotion extends AbstractBuild<PromotionProcess,Promotion> {
public Promotion(PromotionProcess job) throws IOException {
super(job);
}
public Promotion(PromotionProcess job, Calendar timestamp) {
super(job, timestamp);
}
public Promotion(PromotionProcess project, File buildDir) throws IOException {
super(project, buildDir);
}
/**
* Gets the build that this promotion promoted.
*/
public AbstractBuild<?,?> getTarget() {
PromotionTargetAction pta = getAction(PromotionTargetAction.class);
return pta.resolve();
}
@Override
public String getUrl() {
return getTarget().getUrl() + "promotion/" + getParent().getName() + "/promotionBuild/" + getNumber();
}
/**
* Gets the {@link Status} object that keeps track of what {@link Promotion}s are
* performed for a build, including this {@link Promotion}.
*/
public Status getStatus() {
return getTarget().getAction(PromotedBuildAction.class).getPromotion(getParent().getName());
}
@Override
public EnvVars getEnvironment(TaskListener listener) throws IOException, InterruptedException {
EnvVars e = super.getEnvironment(listener);
// Augment environment with target build's information
String rootUrl = Hudson.getInstance().getRootUrl();
AbstractBuild<?, ?> target = getTarget();
if(rootUrl!=null)
e.put("PROMOTED_URL",rootUrl+target.getUrl());
e.put("PROMOTED_JOB_NAME", target.getParent().getName());
e.put("PROMOTED_NUMBER", Integer.toString(target.getNumber()));
e.put("PROMOTED_ID", target.getId());
// Allow the promotion status to contribute to build environment
getStatus().buildEnvVars(this, e);
return e;
}
public void run() {
run(new RunnerImpl());
}
protected class RunnerImpl extends AbstractRunner {
@Override
protected Lease decideWorkspace(Node n, WorkspaceList wsl) throws InterruptedException, IOException {
String customWorkspace = getProject().getCustomWorkspace();
if (customWorkspace != null)
// we allow custom workspaces to be concurrently used between jobs.
return Lease.createDummyLease(
n.getRootPath().child(getEnvironment(listener).expand(customWorkspace)));
return wsl.acquire(n.getWorkspaceFor((TopLevelItem)getTarget().getProject()),true);
}
protected Result doRun(BuildListener listener) throws Exception {
AbstractBuild<?, ?> target = getTarget();
listener.getLogger().println("Promoting "+target);
getStatus().addPromotionAttempt(Promotion.this);
// start with SUCCESS, unless someone makes it a failure
setResult(Result.SUCCESS);
if(!preBuild(listener,project.getBuildSteps()))
return Result.FAILURE;
if(!build(listener,project.getBuildSteps()))
return Result.FAILURE;
return null;
}
protected void post2(BuildListener listener) throws Exception {
if(getResult()== Result.SUCCESS)
getStatus().onSuccessfulPromotion(Promotion.this);
// persist the updated build record
getTarget().save();
if (getResult() == Result.SUCCESS) {
// we should evaluate any other pending promotions in case
// they had a condition on this promotion
PromotedBuildAction pba = getTarget().getAction(PromotedBuildAction.class);
for (PromotionProcess pp : pba.getPendingPromotions()) {
pp.considerPromotion(getTarget());
}
}
}
private boolean build(BuildListener listener, List<BuildStep> steps) throws IOException, InterruptedException {
for( BuildStep bs : steps ) {
if ( bs instanceof BuildTrigger) {
BuildTrigger bt = (BuildTrigger)bs;
for(AbstractProject p : bt.getChildProjects()) {
listener.getLogger().println(" scheduling build for " + p.getDisplayName());
p.scheduleBuild(0, new LegacyCodeCause());
}
} else if(!bs.perform(Promotion.this, launcher, listener)) {
listener.getLogger().println("failed build " + bs + " " + getResult());
return false;
} else {
listener.getLogger().println("build " + bs + " " + getResult());
}
}
return true;
}
private boolean preBuild(BuildListener listener, List<BuildStep> steps) {
for( BuildStep bs : steps ) {
if(!bs.prebuild(Promotion.this,listener)) {
listener.getLogger().println("failed pre build " + bs + " " + getResult());
return false;
}
}
return true;
}
}
public static final PermissionGroup PERMISSIONS = new PermissionGroup(Promotion.class, null);
public static final Permission PROMOTE = new Permission(PERMISSIONS, "Promote", null, Hudson.ADMINISTER);
} |
package hudson.plugins.tasks;
import hudson.model.AbstractBuild;
import hudson.model.ModelObject;
import hudson.plugins.tasks.model.AnnotationContainer;
import hudson.plugins.tasks.model.AnnotationProvider;
import hudson.plugins.tasks.model.FileAnnotation;
import hudson.plugins.tasks.model.Priority;
import hudson.plugins.tasks.model.WorkspaceFile;
import hudson.plugins.tasks.util.ChartBuilder;
import hudson.util.ChartUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.jfree.chart.JFreeChart;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
/**
* Provides common functionality of the different kind of tasks results details.
*/
public abstract class AbstractTasksResult extends AnnotationContainer implements ModelObject {
/** The current build as owner of this action. */
@SuppressWarnings("Se")
private final AbstractBuild<?, ?> owner;
/** Tag identifiers indicating high priority. */
private final String high;
/** Tag identifiers indicating normal priority. */
private final String normal;
/** Tag identifiers indicating low priority. */
private final String low;
/**
* Creates a new instance of <code>AbstractTasksDetail</code>.
*
* @param owner
* the current build as owner of this result object
* @param high
* tag identifiers indicating high priority
* @param normal
* tag identifiers indicating normal priority
* @param low
* tag identifiers indicating low priority
* @param annotations
* all the files that contain tasks
*/
public AbstractTasksResult(final AbstractBuild<?, ?> owner, final String high, final String normal, final String low, final Collection<FileAnnotation> annotations) {
super();
this.owner = owner;
this.high = high;
this.normal = normal;
this.low = low;
addAnnotations(annotations);
}
/**
* Creates a new instance of <code>AbstractTasksResult</code>.
*
* @param root
* the root result object that is used to get the available tasks
* @param annotations
* the annotations of the child
*/
public AbstractTasksResult(final AbstractTasksResult root, final Collection<FileAnnotation> annotations) {
this(root.owner, root.high, root.normal, root.low, annotations);
}
/**
* Returns the package category name for the scanned files. Currently, only
* java and c# files are supported.
*
* @return the package category name for the scanned files
*/
public String getPackageCategoryName() {
if (hasAnnotations()) {
WorkspaceFile file = getAnnotations().iterator().next().getWorkspaceFile();
if (file.getShortName().endsWith(".cs")) {
return "Namespace";
}
}
return "Package";
}
/**
* Returns the current build as owner of this result object.
*
* @return the owner of this details object
*/
public final AbstractBuild<?, ?> getOwner() {
return owner;
}
/**
* Returns whether this result object belongs to the last build.
*
* @return <code>true</code> if this result belongs to the last build
*/
public final boolean isCurrent() {
return getOwner().getProject().getLastBuild().number == getOwner().number;
}
/**
* Returns the actually used priorities.
*
* @return the actually used priorities.
*/
public List<String> getPriorities() {
List<String> actualPriorities = new ArrayList<String>();
for (String priority : getAvailablePriorities()) {
if (getNumberOfAnnotations(priority) > 0) {
actualPriorities.add(priority);
}
}
return actualPriorities;
}
/**
* Returns the defined priorities.
*
* @return the defined priorities.
*/
public Collection<String> getAvailablePriorities() {
ArrayList<String> priorities = new ArrayList<String>();
if (StringUtils.isNotEmpty(high)) {
priorities.add(StringUtils.capitalize(StringUtils.lowerCase(Priority.HIGH.name())));
}
if (StringUtils.isNotEmpty(normal)) {
priorities.add(StringUtils.capitalize(StringUtils.lowerCase(Priority.NORMAL.name())));
}
if (StringUtils.isNotEmpty(low)) {
priorities.add(StringUtils.capitalize(StringUtils.lowerCase(Priority.LOW.name())));
}
return priorities;
}
/**
* Returns the tags for the specified priority.
*
* @param priority
* the priority
* @return the tags for priority high
*/
public final String getTags(final String priority) {
Priority converted = Priority.valueOf(StringUtils.upperCase(priority));
if (converted == Priority.HIGH) {
return high;
}
else if (converted == Priority.NORMAL) {
return normal;
}
else {
return low;
}
}
/**
* Creates a detail graph for the specified detail object.
*
* @param request
* Stapler request
* @param response
* Stapler response
* @param detailObject
* the detail object to compute the graph for
* @param upperBound
* the upper bound of all tasks
* @throws IOException
* in case of an error
*/
protected final void createDetailGraph(final StaplerRequest request, final StaplerResponse response,
final AnnotationProvider detailObject, final int upperBound) throws IOException {
if (ChartUtil.awtProblem) {
response.sendRedirect2(request.getContextPath() + "/images/headless.png");
return;
}
ChartBuilder chartBuilder = new ChartBuilder();
JFreeChart chart = chartBuilder.createHighNormalLowChart(
detailObject.getNumberOfAnnotations(Priority.HIGH),
detailObject.getNumberOfAnnotations(Priority.NORMAL),
detailObject.getNumberOfAnnotations(Priority.LOW), upperBound);
ChartUtil.generateGraph(request, response, chart, 400, 20);
}
} |
package in.twizmwaz.cardinal.command;
import com.google.common.base.Optional;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import in.twizmwaz.cardinal.GameHandler;
import in.twizmwaz.cardinal.chat.ChatConstant;
import in.twizmwaz.cardinal.chat.LocalizedChatMessage;
import in.twizmwaz.cardinal.match.MatchState;
import in.twizmwaz.cardinal.module.modules.team.TeamModule;
import in.twizmwaz.cardinal.util.ChatUtil;
import in.twizmwaz.cardinal.util.Teams;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class JoinCommand {
@Command(aliases = {"join", "play"}, desc = "Join a team.", usage = "[team]")
public static void join(final CommandContext cmd, CommandSender sender) throws CommandException {
if (!(sender instanceof Player)) {
throw new CommandException(ChatConstant.ERROR_CONSOLE_NO_USE.getMessage(ChatUtil.getLocale(sender)));
}
if (GameHandler.getGameHandler().getMatch().getState().equals(MatchState.ENDED) || GameHandler.getGameHandler().getMatch().getState().equals(MatchState.CYCLING)) {
throw new CommandException(ChatUtil.getWarningMessage(new LocalizedChatMessage(ChatConstant.ERROR_MATCH_OVER).getMessage(((Player) sender).getLocale())));
}
Optional<TeamModule> originalTeam = Teams.getTeamByPlayer((Player) sender);
if (cmd.argsLength() == 0 && originalTeam.isPresent() && !originalTeam.get().isObserver()) {
throw new CommandException(ChatUtil.getWarningMessage(ChatColor.RED + new LocalizedChatMessage(ChatConstant.ERROR_ALREADY_JOINED, Teams.getTeamByPlayer((Player) sender).get().getCompleteName() + ChatColor.RED).getMessage(((Player) sender).getLocale())));
}
Optional<TeamModule> destinationTeam = Optional.absent();
if (cmd.argsLength() > 0) {
for (TeamModule teamModule : GameHandler.getGameHandler().getMatch().getModules().getModules(TeamModule.class)) {
if (teamModule.getName().toLowerCase().startsWith(cmd.getJoinedStrings(0).toLowerCase())) {
destinationTeam = Optional.of(teamModule);
break;
}
}
if (!destinationTeam.isPresent()) {
throw new CommandException(ChatConstant.ERROR_NO_TEAM_MATCH.getMessage(ChatUtil.getLocale(sender)));
}
if (destinationTeam.get().contains(sender)) {
throw new CommandException(ChatUtil.getWarningMessage(ChatColor.RED + new LocalizedChatMessage(ChatConstant.ERROR_ALREADY_JOINED, destinationTeam.get().getCompleteName() + ChatColor.RED).getMessage(ChatUtil.getLocale(sender))));
}
destinationTeam.get().add((Player) sender, false);
} else {
destinationTeam = Teams.getTeamWithFewestPlayers(GameHandler.getGameHandler().getMatch());
if (destinationTeam.isPresent()) {
destinationTeam.get().add((Player) sender, false);
} else {
throw new CommandException(ChatConstant.ERROR_TEAMS_FULL.getMessage(ChatUtil.getLocale(sender)));
}
}
}
@Command(aliases = {"leave"}, desc = "Leave the game.")
public static void leave(final CommandContext cmd, CommandSender sender) {
Bukkit.getServer().dispatchCommand(sender, "join observers");
}
} |
package io.avaje.metrics.agent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Helper object used to ignore known classes.
*/
class IgnoreClassHelper {
private static final Set<String> ignoreOneLevel = new HashSet<>();
private static final Set<String> ignoreTwoLevel = new HashSet<>();
static {
ignoreOneLevel.add("java");
ignoreOneLevel.add("javax");
ignoreOneLevel.add("play");
ignoreOneLevel.add("sbt");
ignoreOneLevel.add("scala");
ignoreOneLevel.add("sun");
ignoreOneLevel.add("sunw");
ignoreOneLevel.add("oracle");
ignoreOneLevel.add("groovy");
ignoreOneLevel.add("kotlin");
ignoreOneLevel.add("junit");
ignoreOneLevel.add("microsoft");
ignoreTwoLevel.add("com/sun");
ignoreTwoLevel.add("org/aopalliance");
ignoreTwoLevel.add("org/wc3");
ignoreTwoLevel.add("org/xml");
ignoreTwoLevel.add("org/junit");
ignoreTwoLevel.add("org/apache");
ignoreTwoLevel.add("org/eclipse");
ignoreTwoLevel.add("org/joda");
ignoreTwoLevel.add("com/mysql");
ignoreTwoLevel.add("org/postgresql");
ignoreTwoLevel.add("org/h2");
ignoreTwoLevel.add("com/h2database");
ignoreTwoLevel.add("org/hsqldb");
ignoreTwoLevel.add("org/ibex");
ignoreTwoLevel.add("org/sqlite");
ignoreTwoLevel.add("ch/qos");
ignoreTwoLevel.add("org/slf4j");
ignoreTwoLevel.add("org/codehaus");
ignoreTwoLevel.add("com/fasterxml");
ignoreTwoLevel.add("org/assertj");
ignoreTwoLevel.add("org/hamcrest");
ignoreTwoLevel.add("org/mockito");
ignoreTwoLevel.add("org/objenesis");
ignoreTwoLevel.add("org/objectweb");
ignoreTwoLevel.add("org/jboss");
ignoreTwoLevel.add("org/testng");
ignoreTwoLevel.add("com/intellij");
ignoreTwoLevel.add("com/google");
ignoreTwoLevel.add("com/squareup");
ignoreTwoLevel.add("com/microsoft");
ignoreTwoLevel.add("io/avaje");
}
private final String[] processPackages;
IgnoreClassHelper(Collection<String> packages) {
List<String> packageList = new ArrayList<>();
if (packages != null) {
for (String aPackage : packages) {
packageList.add(convertPackage(aPackage));
}
}
this.processPackages = packageList.toArray(new String[packageList.size()]);
}
/**
* Convert dots/periods to slashes in the package name.
*/
private String convertPackage(String pkg) {
pkg = pkg.trim().replace('.', '/');
if (pkg.endsWith("**")) {
// wild card, remove the **
return pkg.substring(0, pkg.length() - 2);
} else if (pkg.endsWith("*")) {
// wild card, remove the *
return pkg.substring(0, pkg.length() - 1);
} else if (pkg.endsWith("/")) {
// already ends in "/"
return pkg;
} else {
// add "/" so we don't pick up another
// package with a similar starting name
return pkg + "/";
}
}
/**
* Use specific positive matching to determine if the class needs to be
* processed.
* <p>
* Any class at any depth under the package can be processed and all others
* ignored.
* </p>
*
* @return true if the class can be ignored
*/
private boolean specificMatching(String className) {
for (String processPackage : processPackages) {
if (className.startsWith(processPackage)) {
// a positive match
return false;
}
}
// we can ignore this class
return true;
}
/**
* Try to exclude JDK classes and known JDBC Drivers and Libraries.
* <p>
* We want to do this for performance reasons - that is skip checking for
* enhancement on classes that we know are not part of the application code
* and should not be enhanced.
* </p>
*
* @param className
* the className of the class being defined.
* @return true if this class should not be processed.
*/
boolean isIgnoreClass(String className) {
if (className == null || "bsh/Interpreter".equals(className)) {
return true;
}
className = className.replace('.', '/');
if (processPackages.length > 0) {
// use specific positive matching
return specificMatching(className);
}
// we don't have specific packages to process so instead
// we will ignore packages that we know we don't want to
// process (they won't contain entity beans etc).
// ignore $Proxy classes
if (className.startsWith("$")) {
return true;
}
int firstSlash = className.indexOf('/');
if (firstSlash == -1) {
return true;
}
String firstPackage = className.substring(0, firstSlash);
if (ignoreOneLevel.contains(firstPackage)) {
return true;
}
int secondSlash = className.indexOf('/', firstSlash + 1);
if (secondSlash == -1) {
return false;
}
String secondPackage = className.substring(0, secondSlash);
return ignoreTwoLevel.contains(secondPackage);
}
} |
package tictactoeGame;
import java.awt.Point;
import exceptions.InvalidMoveException;
import players.Player;
import players.PlayerID;
import playingField.FieldPosition;
import playingField.PlayingField;
import playingField.Positions;
public final class Move {
private PlayingField field;
private PlayerID id;
private boolean moveMade;
public Move(PlayingField field, Player turn) {
this.field = field;
this.id = turn.getPlayerID();
moveMade = false;
}
public void makeMove(int x, int y) throws InvalidMoveException {
this.makeMove(new Point(x,y));
}
public void makeMove(FieldPosition position) throws InvalidMoveException {
makeMove(Positions.fromTypeToPoint(position), position);
}
public void makeMove(Point position) throws InvalidMoveException {
makeMove(position, Positions.fromPointToType(position));
}
private void makeMove(Point ppos, FieldPosition fpos) throws InvalidMoveException {
if(moveMade) {
throw new InvalidMoveException();
}
field.makeMove(ppos, fpos, id);
moveMade = true;
}
} |
package com.sun.star.wizards.report;
import com.sun.star.container.XIndexAccess;
import com.sun.star.container.XNameAccess;
import com.sun.star.container.XNamed;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.table.XCellRange;
import com.sun.star.table.XTableColumns;
import com.sun.star.table.XTableRows;
import com.sun.star.text.XTextTable;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.wizards.text.TextTableHandler;
import com.sun.star.wizards.text.ViewHandler;
public class RecordTable{
String CurFieldName;
String LabelDescription;
public XNamed xTableName;
public XCellRange xCellRange;
public XTextTable xTextTable;
private TextTableHandler oTextTableHandler;
public XTableColumns xTableColumns;
public XTableRows xTableRows;
public RecordTable(TextTableHandler _oTextTableHandler){
try{
this.oTextTableHandler = _oTextTableHandler;
String[] TableNames = oTextTableHandler.xTextTablesSupplier.getTextTables().getElementNames();
XNameAccess xAllTextTables = oTextTableHandler.xTextTablesSupplier.getTextTables();
if ((xAllTextTables.hasByName(ReportDocument.TBLRECORDSECTION)) || (xAllTextTables.hasByName(ReportDocument.COPYOFTBLRECORDSECTION))){
Object oTable;
if (xAllTextTables.hasByName(ReportDocument.COPYOFTBLRECORDSECTION))
oTable = xAllTextTables.getByName(ReportDocument.COPYOFTBLRECORDSECTION);
else
oTable = xAllTextTables.getByName(ReportDocument.TBLRECORDSECTION);
xTextTable = (XTextTable) UnoRuntime.queryInterface(XTextTable.class, oTable);
xTableName = (XNamed) UnoRuntime.queryInterface(XNamed.class, xTextTable);
}
else{
XIndexAccess xTableIndex = (XIndexAccess) UnoRuntime.queryInterface(XIndexAccess.class, xAllTextTables);
xTextTable = (XTextTable) UnoRuntime.queryInterface(XTextTable.class, xTableIndex.getByIndex(xTableIndex.getCount()-1));
xTableName = (XNamed) UnoRuntime.queryInterface(XNamed.class, xTextTable);
xTableName.setName(ReportDocument.TBLRECORDSECTION);
}
xTableRows = xTextTable.getRows();
xTableColumns = xTextTable.getColumns();
xCellRange = (XCellRange) UnoRuntime.queryInterface(XCellRange.class, xTextTable);
}
catch(Exception exception){
exception.printStackTrace(System.out);
}}
public void adjustOptimalTableWidths(XMultiServiceFactory _xMSF, ViewHandler oViewHandler){ // setTableColumnSeparators(){
oTextTableHandler.adjustOptimalTableWidths(_xMSF, xTextTable);
oViewHandler.collapseViewCursorToStart();
}
} |
import java.util.*;
public class FunctionRoutine
{
public static final int MAX_CHARACTERS = 20;
public static final String ROUTINE_A = "A";
public static final String ROUTINE_B = "B";
public static final String ROUTINE_C = "C";
public static final int ROUTINE_A_INDEX = 0;
public static final int ROUTINE_B_INDEX = 1;
public static final int ROUTINE_C_INDEX = 2;
public FunctionRoutine (Stack<String> pathTaken, boolean debug)
{
_path = pathTaken;
_functions = null;
/*
* Now convert the path into a series of commands
* such as L,4 or R,8.
*/
createCommands();
_debug = debug;
}
public Vector<MovementFunction> createMovementFunctions ()
{
/*
* Now turn the series of commands into functions
* A, B and C based on repeated commands.
*
* There are only 3 possible functions.
*
* This means one function always starts at the beginning.
*
* One function always ends at the ending (!) assuming it's not a repeat
* of the first.
*
* Then using both the first and the last fragment to find the third
* and split the entire sequence into functions.
*/
String fullCommand = getCommandString();
System.out.println("Full command "+fullCommand);
/*
* Find repeated strings. Assume minimum of 2 commands.
*/
_functions = new Vector<MovementFunction>();
System.out.println("fullCommand length "+fullCommand.length());
System.out.println("search string is "+fullCommand);
MovementFunction func = getFirstMovementFunction(fullCommand, 2);
func.setName(ROUTINE_A);
System.out.println("First function is "+func+"\n");
if (func != null)
{
fullCommand = fullCommand.replace(func.getCommand(), ""); // remove repeating commands
recreateCommands(fullCommand);
fullCommand = getCommandString();
System.out.println("fullCommand now "+fullCommand);
func = getLastMovementFunction(fullCommand, 2);
func.setName(ROUTINE_B);
System.out.println("Last function is "+func+"\n");
if (func != null)
{
fullCommand = fullCommand.replace(func.getCommand(), ""); // remove repeating commands
System.out.println("fullCommand now "+fullCommand);
recreateCommands(fullCommand);
func = getFirstMovementFunction(fullCommand, 2);
func.setName(ROUTINE_C);
if (func != null)
{
System.out.println("Second function is "+func+"\n");
fullCommand = fullCommand.replace(func.getCommand(), ""); // remove repeating commands
fullCommand = fullCommand.replace(",,", ""); // remove duplicates
if (fullCommand.length() != 0)
System.out.println("Commands still remaining! "+fullCommand);
}
}
}
return _functions;
}
public final String getCommandString ()
{
String fullCommand = "";
for (int i = _commands.size() -1; i >= 0; i
{
fullCommand += _commands.elementAt(i);
if (i != 0)
fullCommand += ",";
}
return fullCommand;
}
/*
* Return the first repeating function.
*
* fullCommand is the String to search.
* startingCommand is the command from which to begin the search.
* numberOfCommands is the number of commands to pull together.
*/
private MovementFunction getFirstMovementFunction (String commandString, int numberOfCommands)
{
System.out.println("getFirstMovementFunction searching "+commandString+" with "+numberOfCommands+" number of commands");
return getMovementFunction(commandString, 0, _commands.size(), numberOfCommands);
}
private MovementFunction getLastMovementFunction (String commandString, int numberOfCommands)
{
System.out.println("getLastMovementFunction searching "+commandString+" with "+numberOfCommands+" number of commands");
MovementFunction routine = findLastRepeatFunction(commandString, numberOfCommands);
System.out.println("**etLastMovementFunction got back "+routine);
if (routine == null)
{
System.out.println("Error - no repeating function!");
return null;
}
else
{
_functions.add(routine);
return routine;
}
}
private MovementFunction getMovementFunction (String commandString, int startingCommand, int endCommand, int numberOfCommands)
{
System.out.println("getMovementFunction searching "+commandString+" with "+numberOfCommands+" number of commands");
MovementFunction routine = findRepeatFunction(commandString, startingCommand, endCommand, numberOfCommands);
System.out.println("**getMovementFunction got back "+routine);
if (routine == null)
{
System.out.println("Error - no repeating function!");
return null;
}
else
{
_functions.add(routine);
return routine;
}
}
private MovementFunction findRepeatFunction (String commandString, int startingCommand, int endCommand, int numberOfCommands)
{
System.out.println("findRepeatFunction searching "+commandString+" with "+numberOfCommands+" number of commands");
if (numberOfCommands < (startingCommand + endCommand))
{
String repeat = getCommandString(startingCommand, numberOfCommands);
if (repeat.length() <= MAX_CHARACTERS)
{
if (commandString.indexOf(repeat, repeat.length()) != -1) // it repeats so try another command
{
System.out.println("Repeat: "+repeat);
MovementFunction next = findRepeatFunction(commandString, startingCommand, endCommand, numberOfCommands +1);
if (next == null)
return new MovementFunction(repeat, numberOfCommands);
else
return next;
}
else
System.out.println("Does not repeat: "+repeat);
}
else
System.out.println("Command string too long.");
}
return null;
}
private String getCommandString (int start, int numberOfCommands)
{
String str = "";
System.out.println("getCommandString starting command "+start+" and number "+numberOfCommands);
for (int i = start; i < (start + numberOfCommands); i++)
{
int commandNumber = _commands.size() - 1 - i;
System.out.println("Adding command "+commandNumber);
str += _commands.elementAt(commandNumber);
if ((i+1) < (start + numberOfCommands))
str += ",";
}
System.out.println("**Command string created: "+str);
return str;
}
private MovementFunction findLastRepeatFunction (String commandString, int numberOfCommands)
{
System.out.println("findLastRepeatFunction searching "+commandString+" with "+numberOfCommands+" commands");
String repeat = getLastCommandString(numberOfCommands);
System.out.println("Scanning for "+repeat);
if (repeat.length() <= MAX_CHARACTERS)
{
if (commandString.indexOf(repeat, repeat.length()) != -1) // it repeats so try another command
{
System.out.println("Repeat: "+repeat);
MovementFunction next = findLastRepeatFunction(commandString, numberOfCommands +1);
if (next == null)
return new MovementFunction(repeat, numberOfCommands);
else
return next;
}
else
System.out.println("Does not repeat: "+repeat);
}
else
System.out.println("Command string too long.");
return null;
}
private String getLastCommandString (int numberOfCommands)
{
String str = "";
System.out.println("getLastCommandString using "+numberOfCommands+" commands");
for (int i = numberOfCommands -1; i >= 0; i
{
System.out.println("Adding command "+i);
str += _commands.elementAt(i);
if (i != 0)
str += ",";
}
System.out.println("**Last command string created: "+str);
return str;
}
private void recreateCommands (String sequence)
{
System.out.println("Recreating commands from "+sequence);
Stack<String> temp = new Stack<String>();
StringTokenizer tokeniser = new StringTokenizer(sequence, ",");
while (tokeniser.hasMoreTokens())
{
String token1 = tokeniser.nextToken();
String token2 = tokeniser.nextToken();
String str = token1+","+token2;
System.out.println("created "+str);
temp.push(str);
}
_commands = new Vector<String>();
boolean end = false;
while (!end)
{
try
{
String command = temp.pop();
_commands.add(command);
}
catch (Exception ex)
{
end = true;
}
}
}
private void createCommands ()
{
String pathElement = null;
_commands = new Vector<String>(_path.size());
/*
* Pop the track to reverse it and get commands from the
* starting position.
*/
do
{
try
{
pathElement = _path.pop();
String str = pathElement.charAt(0)+","+pathElement.length();
_commands.add(str);
}
catch (Exception ex)
{
pathElement = null;
}
} while (pathElement != null);
if (_debug)
{
for (int i = _commands.size() -1; i >= 0; i
{
System.out.println("Commands: "+_commands.elementAt(i));
}
}
}
private Stack<String> _path;
private Vector<MovementFunction>_functions;
private Vector<String> _commands;
private boolean _debug;
} |
package com.sometrik.framework;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import com.sometrik.framework.NativeCommand.Selector;
import android.app.ActionBar;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class FWActionBar implements NativeCommandHandler {
private int id;
private ActionBar actionBar;
private ArrayList<ActionBarItem> itemList;
private FrameWork frame;
private TextView titleView;
private TextView subtitleView;
private ImageButton drawerButton;
private RelativeLayout mainLayout;
private FWLayout alternativeButtonLayout;
ViewStyleManager normalStyle, activeStyle, currentStyle;
public FWActionBar(final FrameWork frame, String title, int id){
this.frame = frame;
actionBar = frame.getActionBar();
// actionBar.setDisplayShowTitleEnabled(true);
// actionBar.setTitle(title);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
mainLayout = new RelativeLayout(frame);
// mainLayout.setOrientation(LinearLayout.HORIZONTAL);
mainLayout.setBackgroundColor(Color.parseColor("#ffffff"));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.weight = 1;
mainLayout.setLayoutParams(params);
final float scale = frame.getResources().getDisplayMetrics().density;
drawerButton = new ImageButton(frame);
LinearLayout.LayoutParams drawerButtonParams = new LinearLayout.LayoutParams((int)(45 * scale), LayoutParams.MATCH_PARENT);
drawerButton.setLayoutParams(drawerButtonParams);
Bitmap bitmap = frame.bitmapCache.loadBitmap("icons_hamburger-menu.png");
if (bitmap != null) {
Drawable draw = new BitmapDrawable(bitmap);
drawerButton.setImageDrawable(draw);
drawerButton.setScaleType(ScaleType.FIT_CENTER);
drawerButton.setBackgroundColor(Color.parseColor("#ffffff"));
drawerButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("drawerButton click");
NativeCommandHandler handler = frame.views.get(frame.getCurrentDrawerViewId());
System.out.println("handler: " + handler.getElementId());
if (handler instanceof View) {
if (((View) handler).getVisibility() == View.VISIBLE) {
handler.setViewVisibility(false);
} else {
handler.setViewVisibility(true);
}
}
}
});
mainLayout.addView(drawerButton);
}
// titleView = new TextView(frame);
// titleView.setText(title);
// titleView.setLayoutParams(params);
// titleView.setGravity(Gravity.CENTER);
// titleView.setTextSize(14);
// titleView.setTextColor(Color.parseColor("#5d6468"));
// subtitleView = new TextView(frame);
// subtitleView.setText("subtitle");
// subtitleView.setLayoutParams(params);
// subtitleView.setGravity(Gravity.CENTER);
// subtitleView.setVisibility(TextView.GONE);
// subtitleView.setTextSize(10);
// subtitleView.setTextColor(Color.parseColor("#b7c4cd"));
// LinearLayout titleHolderLayout = new LinearLayout(frame);
// titleHolderLayout.setOrientation(LinearLayout.VERTICAL);
// titleHolderLayout.setLayoutParams(params);
// titleHolderLayout.addView(titleView);
// titleHolderLayout.addView(subtitleView);
int pixels = (int) (58 * scale + 0.5f);
// int pixels = drawerButton.getWidth();
// titleView.setPadding(titleView.getPaddingLeft(), titleView.getPaddingRight(), pixels, titleView.getPaddingBottom());
// subtitleView.setPadding(subtitleView.getPaddingLeft(), subtitleView.getPaddingRight(), pixels, subtitleView.getPaddingBottom());
// titleView.setGravity(Gravity.CENTER);
// mainLayout.addView(titleHolderLayout);
actionBar.show();
actionBar.setCustomView(mainLayout);
this.normalStyle = currentStyle = new ViewStyleManager(frame.bitmapCache, scale, true);
this.activeStyle = new ViewStyleManager(frame.bitmapCache, scale, false);
itemList = new ArrayList<ActionBarItem>();
this.id = id;
}
void changeButton(final View view) {
clear();
drawerButton.setVisibility(ImageButton.GONE);
alternativeButtonLayout = new FWLayout(frame);
LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
alternativeButtonLayout.setLayoutParams(params2);
alternativeButtonLayout.addView(view);
alternativeButtonLayout.setGravity(Gravity.CENTER_HORIZONTAL);
mainLayout.addView(alternativeButtonLayout, 0);
alternativeButtonLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
System.out.println("actionbar: view clicked " + view.getId());
frame.intChangedEvent(view.getId(), 1, 1);
}
});
}
public void setTitle(String title) {
// titleView.setText(title);
}
public ArrayList<ActionBarItem> getItemList(){
return itemList;
}
@Override
public void onScreenOrientationChange(boolean isLandscape) {
// TODO Auto-generated method stub
}
@Override
public void addChild(View view) {
// if (view instanceof TextView) {
// ((TextView) view).setGravity(Gravity.CENTER);
// ((TextView) view).setTextAlignment(TextView.TEXT_ALIGNMENT_CENTER);
// } else if (view instanceof LinearLayout) {
// ((LinearLayout) view).setGravity(Gravity.CENTER);
mainLayout.addView(view);
}
@Override
public void addOption(int optionId, String text) {
itemList.add(new ActionBarItem(optionId, text));
}
@Override
public void addData(String text, int row, int column, int sheet) {
System.out.println("Command couldn't be handled by FWActionBar");
}
@Override
public void setValue(String v) {
// setTitle(v);
}
@Override
public void setValue(int v) {
if (v == 0){
actionBar.hide();
} else if (v == 1){
actionBar.show();
}
}
@Override
public void setViewVisibility(boolean visible) {
if (!visible) {
actionBar.hide();
} else {
actionBar.show();
}
}
@Override
public void setStyle(Selector selector, String key, String value) {
if (selector == Selector.NORMAL) {
normalStyle.setStyle(key, value);
// if (normalStyle == currentStyle) normalStyle.apply(this);
} else if (selector == Selector.ACTIVE) {
activeStyle.setStyle(key, value);
// if (activeStyle == currentStyle) activeStyle.apply(this);
}
if (key.equals("drawer-button")) {
if (value.equals("hide")) {
drawerButton.setVisibility(Button.GONE);
} else if (value.equals("show")) {
drawerButton.setVisibility(Button.VISIBLE);
}
}
// if (key.equals("subtitle")) {
// subtitleView.setText(value);
// if (value.isEmpty()) {
// subtitleView.setVisibility(TextView.GONE);
// } else if (subtitleView.getVisibility() == TextView.GONE) {
// subtitleView.setVisibility(TextView.VISIBLE);
// } else
if (key.equals("height")) {
final float scale = frame.getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams params = (LayoutParams) mainLayout.getLayoutParams();
if (value.equals("wrap-content")) {
params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
} else if (value.equals("match-parent")) {
params.height = LinearLayout.LayoutParams.MATCH_PARENT;
} else {
int pixels = (int) (Integer.parseInt(value) * scale + 0.5f);
params.height = pixels;
}
mainLayout.setLayoutParams(params);
}
}
@Override
public void setError(boolean hasError, String errorText) {
System.out.println("Command couldn't be handled by FWActionBar");
}
@Override
public int getElementId() {
return id;
}
public class ActionBarItem {
int id;
String pictureAsset;
BitmapDrawable picture;
public ActionBarItem(int id, String pictureAsset) {
this.id = id;
this.pictureAsset = pictureAsset;
try {
InputStream stream = frame.getAssets().open(pictureAsset);
if (stream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(stream);
picture = new BitmapDrawable(frame.getResources(), bitmap);
stream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void clear() {
if (alternativeButtonLayout != null) {
mainLayout.removeView(alternativeButtonLayout);
drawerButton.setVisibility(ImageButton.VISIBLE);
alternativeButtonLayout = null;
}
mainLayout.removeAllViews();
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
@Override
public void addColumn(String text, int columnType) {
// TODO Auto-generated method stub
}
@Override
public void reshape(int value, int size) {
// TODO Auto-generated method stub
}
@Override
public void setBitmap(Bitmap bitmap) { }
@Override
public void reshape(int size) {
// TODO Auto-generated method stub
}
@Override
public void deinitialize() {
// TODO Auto-generated method stub
}
@Override
public void addImageUrl(String url, int width, int height) {
// TODO Auto-generated method stub
}
} |
package com.sometrik.framework;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import android.app.ActionBar;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class FWActionBar implements NativeCommandHandler {
int id;
ActionBar actionBar;
ArrayList<ActionBarItem> itemList;
FrameWork frame;
TextView titleView;
public FWActionBar(final FrameWork frame, String title, int id){
this.frame = frame;
actionBar = frame.getActionBar();
// actionBar.setDisplayShowTitleEnabled(true);
// actionBar.setTitle(title);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
LinearLayout layout = new LinearLayout(frame);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setBackgroundColor(Color.parseColor("#ffffff"));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
layout.setLayoutParams(params);
try {
InputStream stream = frame.getAssets().open("icons_hamburger-menu.png");
Drawable draw = new BitmapDrawable(stream);
stream.close();
ImageButton drawerButton = new ImageButton(frame);
drawerButton.setImageDrawable(draw);
drawerButton.setBackgroundColor(Color.parseColor("#ffffff"));
drawerButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("drawerButton click");
NativeCommandHandler handler = frame.views.get(frame.getCurrentDrawerViewId());
System.out.println("handler: " + handler.getElementId());
if (handler instanceof View) {
if (((View) handler).getVisibility() == View.VISIBLE) {
handler.setViewVisibility(false);
} else {
handler.setViewVisibility(true);
}
}
}
});
layout.addView(drawerButton);
} catch (IOException e) {
e.printStackTrace();
}
titleView = new TextView(frame);
titleView.setText("STREAM");
titleView.setLayoutParams(params);
titleView.setGravity(Gravity.CENTER);
final float scale = frame.getResources().getDisplayMetrics().density;
int pixels = (int) (56 * scale + 0.5f);
titleView.setPadding(titleView.getPaddingLeft(), titleView.getPaddingRight(), pixels, titleView.getPaddingBottom());
// titleView.setGravity(Gravity.CENTER);
layout.addView(titleView);
actionBar.show();
actionBar.setCustomView(layout);
// actionBar.setDisplayUseLogoEnabled(false);
// ColorDrawable cd = new ColorDrawable();
// cd.setColor(Color.WHITE);
// actionBar.setBackgroundDrawable(cd);
// final float scale = frame.getResources().getDisplayMetrics().density;
// try {
// Field f = actionBar.getClass().getSuperclass().getDeclaredField("mContentHeight");
// f.setAccessible(true);
// f.set(actionBar, (106 * scale + 0.5f));
// } catch (NoSuchFieldException e) {
// e.printStackTrace();
// e.printStackTrace();
itemList = new ArrayList<ActionBarItem>();
this.id = id;
}
public ArrayList<ActionBarItem> getItemList(){
return null;
}
@Override
public void onScreenOrientationChange(boolean isLandscape) {
// TODO Auto-generated method stub
}
@Override
public void addChild(View view) {
System.out.println("Command couldn't be handled by FWActionBar");
}
@Override
public void addOption(int optionId, String text) {
itemList.add(new ActionBarItem(optionId, text, "default"));
}
@Override
public void addData(String text, int row, int column, int sheet) {
System.out.println("Command couldn't be handled by FWActionBar");
}
@Override
public void setValue(String v) {
// actionBar.setTitle(v);
// titleView.setText(v);
}
@Override
public void setValue(int v) {
if (v == 0){
actionBar.hide();
} else if (v == 1){
actionBar.show();
}
}
@Override
public void setViewEnabled(Boolean enabled) {
if (!enabled){
actionBar.hide();
} else {
actionBar.show();
}
}
@Override
public void setViewVisibility(boolean visible) {
if (!visible){
actionBar.hide();
} else {
actionBar.show();
}
}
@Override
public void setStyle(String key, String value) {
// if (key.equals("icon")){
// try {
// InputStream stream = frame.getAssets().open(value);
// Bitmap b = BitmapFactory.decodeStream(stream);
// Drawable d = new BitmapDrawable(b);
// actionBar.setIcon(d);
// } catch (IOException e) {
// e.printStackTrace();
}
@Override
public void setError(boolean hasError, String errorText) {
System.out.println("Command couldn't be handled by FWActionBar");
}
@Override
public int getElementId() {
return id;
}
public class ActionBarItem {
int id;
String name;
String pictureAsset;
public ActionBarItem(int id, String name, String pictureAsset) {
this.id = id;
this.name = name;
this.pictureAsset = pictureAsset;
}
}
@Override
public void clear() {
// TODO Auto-generated method stub
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
@Override
public void addColumn(String text, int columnType) {
// TODO Auto-generated method stub
}
@Override
public void reshape(int value, int size) {
// TODO Auto-generated method stub
}
@Override
public void setImage(byte[] bytes) {
// TODO Auto-generated method stub
}
@Override
public void reshape(int size) {
// TODO Auto-generated method stub
}
} |
package com.sometrik.framework;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class FWImageView extends ImageView implements NativeCommandHandler {
FrameWork frame;
public FWImageView(FrameWork frame) {
super(frame);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
this.setLayoutParams(params);
}
@Override
public void onScreenOrientationChange(boolean isLandscape) {
// TODO Auto-generated method stub
}
@Override
public void addChild(View view) {
// TODO Auto-generated method stub
}
@Override
public void addOption(int optionId, String text) {
// TODO Auto-generated method stub
}
@Override
public void addColumn(String text, int columnType) {
// TODO Auto-generated method stub
}
@Override
public void addData(String text, int row, int column, int sheet) {
// TODO Auto-generated method stub
}
@Override
public void setValue(String v) {
}
@Override
public void setValue(int v) {
// TODO Auto-generated method stub
}
@Override
public void reshape(int value, int size) {
// TODO Auto-generated method stub
}
@Override
public void setViewEnabled(Boolean enabled) {
// TODO Auto-generated method stub
}
@Override
public void setViewVisibility(boolean visible) {
// TODO Auto-generated method stub
}
@Override
public void setStyle(String key, String value) {
if (key.equals("gravity")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("bottom")) {
params.gravity = Gravity.BOTTOM;
} else if (value.equals("top")) {
params.gravity = Gravity.TOP;
} else if (value.equals("left")) {
params.gravity = Gravity.LEFT;
} else if (value.equals("right")) {
params.gravity = Gravity.RIGHT;
}
setLayoutParams(params);
} else if (key.equals("width")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("wrap-content")) {
params.width = LinearLayout.LayoutParams.WRAP_CONTENT;
} else if (value.equals("match-parent")) {
params.width = LinearLayout.LayoutParams.MATCH_PARENT;
}
setLayoutParams(params);
} else if (key.equals("height")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("wrap-content")) {
params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
} else if (value.equals("match-parent")) {
params.height = LinearLayout.LayoutParams.MATCH_PARENT;
}
setLayoutParams(params);
} else if (key.equals("weight")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.weight = Integer.parseInt(value);
setLayoutParams(params);
}
}
@Override
public void setError(boolean hasError, String errorText) {
// TODO Auto-generated method stub
}
@Override
public void clear() {
// TODO Auto-generated method stub
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
@Override
public int getElementId() {
return getId();
}
@Override
public void setImage(byte[] bytes) {
this.setImage(bytes);
}
@Override
public void reshape(int size) {
// TODO Auto-generated method stub
}
} |
package com.artifex.mupdf;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileObserver;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ChoosePDFActivity extends ListActivity {
private File mDirectory;
private File [] mFiles;
private Handler mHandler;
private Runnable mUpdateFiles;
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Resources res = getResources();
String appName = res.getString(R.string.app_name);
String version = res.getString(R.string.version);
String title = res.getString(R.string.picker_title);
setTitle(String.format(title, appName, version));
String storageState = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(storageState)
&& !Environment.MEDIA_MOUNTED_READ_ONLY.equals(storageState))
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.no_media_warning);
builder.setMessage(R.string.no_media_hint);
AlertDialog alert = builder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE,"Dismiss",
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
}
@Override
protected void onResume() {
super.onResume();
mDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
// Create a list adapter...
adapter = new ArrayAdapter<String>(this, R.layout.picker_entry);
setListAdapter(adapter);
// ...that is updated dynamically when files are scanned
mHandler = new Handler();
mUpdateFiles = new Runnable() {
public void run() {
mFiles = mDirectory.listFiles(new FilenameFilter() {
public boolean accept(File file, String name) {
if (name.toLowerCase().endsWith(".pdf"))
return true;
if (name.toLowerCase().endsWith(".xps"))
return true;
if (name.toLowerCase().endsWith(".cbz"))
return true;
return false;
}
});
adapter.clear();
if (mFiles != null)
for (File f : mFiles)
adapter.add(f.getName());
adapter.sort(String.CASE_INSENSITIVE_ORDER);
}
};
// Start initial file scan...
mHandler.post(mUpdateFiles);
// ...and observe the directory and scan files upon changes.
FileObserver observer = new FileObserver(mDirectory.getPath(), FileObserver.CREATE | FileObserver.DELETE) {
public void onEvent(int event, String path) {
mHandler.post(mUpdateFiles);
}
};
observer.startWatching();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Uri uri = Uri.parse(mFiles[position].getAbsolutePath());
Intent intent = new Intent(this,MuPDFActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} |
package mondrian.calc.impl;
import mondrian.calc.TupleIterator;
import mondrian.calc.TupleList;
import mondrian.olap.Member;
import mondrian.olap.Util;
import java.util.*;
/**
* Implementation of {@link mondrian.calc.TupleList} based on a list of
* {@code List<Member>} tuples.
*
* @version $Id$
* @author jhyde
*/
public class DelegatingTupleList extends AbstractTupleList
{
private final List<List<Member>> list;
/**
* Creates a DelegatingTupleList.
*
* @param arity Arity
* @param list Backing list
*/
public DelegatingTupleList(int arity, List<List<Member>> list) {
super(arity);
this.list = list;
assert list.isEmpty()
|| (list.get(0) instanceof List
&& (list.get(0).isEmpty()
|| list.get(0).get(0) == null
|| list.get(0).get(0) instanceof Member))
: "sanity check failed: " + list;
}
@Override
protected TupleIterator tupleIteratorInternal() {
return new AbstractTupleListIterator();
}
@Override
public TupleList subList(int fromIndex, int toIndex) {
return new DelegatingTupleList(arity, list.subList(fromIndex, toIndex));
}
@Override
public List<Member> get(int index) {
return list.get(index);
}
@Override
public int size() {
return list.size();
}
public List<Member> slice(final int column) {
return new AbstractList<Member>() {
@Override
public Member get(int index) {
return list.get(index).get(column);
}
@Override
public int size() {
return list.size();
}
public Member set(int index, Member element) {
return list.get(index).set(column, element);
};
};
}
public TupleList cloneList(int capacity) {
return new DelegatingTupleList(
arity,
capacity < 0
? new ArrayList<List<Member>>(list)
: new ArrayList<List<Member>>(capacity));
}
@Override
public List<Member> set(int index, List<Member> element) {
return list.set(index, element);
}
@Override
public void add(int index, List<Member> element) {
list.add(index, element);
}
public void addTuple(Member... members) {
list.add(Util.flatList(members));
}
public TupleList project(final int[] destIndices) {
return new DelegatingTupleList(
destIndices.length,
new AbstractList<List<Member>>() {
public List<Member> get(final int index) {
return new AbstractList<Member>() {
public Member get(int column) {
return list.get(index).get(destIndices[column]);
}
public int size() {
return destIndices.length;
}
public Member set(int column, Member element) {
return list.get(index).set(index, element);
};
};
}
public List<Member> set(int index, List<Member> element) {
return list.set(index, element);
};
public int size() {
return list.size();
}
}
);
}
public TupleList withPositionCallback(
final PositionCallback positionCallback)
{
return new DelegatingTupleList(
arity,
new AbstractList<List<Member>>() {
@Override
public List<Member> get(int index) {
positionCallback.onPosition(index);
return list.get(index);
}
@Override
public int size() {
return list.size();
}
@Override
public List<Member> set(int index, List<Member> element) {
positionCallback.onPosition(index);
return list.set(index, element);
}
@Override
public void add(int index, List<Member> element) {
positionCallback.onPosition(index);
list.add(index, element);
}
@Override
public List<Member> remove(int index) {
positionCallback.onPosition(index);
return list.remove(index);
}
}
);
}
}
// End DelegatingTupleList.java |
package me.panavtec.katas.bowling;
import java.util.Arrays;
public class Bowling {
private char[] rolls = new char[21];
private int currentIndex = 0;
public Bowling() {
Arrays.fill(rolls, '-');
}
public void roll(char roll) {
rolls[currentIndex++] = roll;
}
public void roll(char roll, char roll2) {
roll(roll);
roll(roll2);
}
public int calculateScore() {
int finalScore = 0;
for (int index = 0; index < rolls.length; index++) {
if (isScoringRoll(index)) {
if (isStrike(index)) {
finalScore += strike(index);
if (isLastBall(index + 1)) index++;
} else if (isSpare(index)) {
finalScore += spare(index);
index++;
if (isLastBall(index + 1)) index++;
} else {
finalScore += numericValue(index);
}
}
}
return finalScore;
}
private int spare(int index) {
int finalScore = 10;
if (isStrike(index + 2)) {
finalScore += 10;
} else if (isScoringRoll(index + 2)) {
finalScore += numericValue(index + 2);
}
return finalScore;
}
private int strike(int index) {
int finalScore = 10;
if (!isLastBall(index + 1)) {
if (isStrike(index + 2)) {
finalScore += 10;
if (!isLastBall(index + 2)) {
if (isStrike(index + 4)) {
finalScore += 10;
} else if (isNumeric(index + 4)) {
finalScore += numericValue(index + 4);
}
}
} else if (isSpare(index + 2)) {
finalScore += 10;
} else if (isNumeric(index + 2)) {
finalScore += numericValue(index + 2);
}
}
return finalScore;
}
private int numericValue(int index) {
return Character.getNumericValue(rolls[index]);
}
private boolean isSpare(int index) {
return !isLastBall(index) && rolls[index + 1] == '/';
}
private boolean isStrike(int index) {
return rolls[index] == 'X';
}
private boolean isLastBall(int index) {
return index == rolls.length - 1;
}
private boolean isScoringRoll(int index) {
return rolls[index] != '-' && rolls[index] != '/';
}
private boolean isNumeric(int index) {
return isScoringRoll(index) && rolls[index] != '/' && !isStrike(index);
}
} |
package me.chanjar.weixin.common.util.http;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.common.util.fs.FileUtils;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* String, File
*
* @author Daniel Qian
*/
public class MediaDownloadRequestExecutor implements RequestExecutor<File, String> {
private File tmpDirFile;
public MediaDownloadRequestExecutor() {
}
public MediaDownloadRequestExecutor(File tmpDirFile) {
this.tmpDirFile = tmpDirFile;
}
@Override
public File execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, IOException {
if (queryParam != null) {
if (uri.indexOf('?') == -1) {
uri += '?';
}
uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
}
HttpGet httpGet = new HttpGet(uri);
if (httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
httpGet.setConfig(config);
}
try (CloseableHttpResponse response = httpclient.execute(httpGet);
InputStream inputStream = InputStreamResponseHandler.INSTANCE
.handleResponse(response)) {
Header[] contentTypeHeader = response.getHeaders("Content-Type");
if (contentTypeHeader != null && contentTypeHeader.length > 0) {
if (contentTypeHeader[0].getValue().startsWith(ContentType.APPLICATION_JSON.getMimeType())) {
// application/json; encoding=utf-8
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
throw new WxErrorException(WxError.fromJson(responseContent));
}
}
String fileName = getFileName(response);
if (StringUtils.isBlank(fileName)) {
return null;
}
String[] nameAndExt = fileName.split("\\.");
return FileUtils.createTmpFile(inputStream, nameAndExt[0], nameAndExt[1], this.tmpDirFile);
} finally {
httpGet.releaseConnection();
}
}
private String getFileName(CloseableHttpResponse response) throws WxErrorException {
Header[] contentDispositionHeader = response.getHeaders("Content-disposition");
if(contentDispositionHeader == null || contentDispositionHeader.length == 0){
throw new WxErrorException(WxError.newBuilder().setErrorMsg("").build());
}
Pattern p = Pattern.compile(".*filename=\"(.*)\"");
Matcher m = p.matcher(contentDispositionHeader[0].getValue());
if(m.matches()){
return m.group(1);
}
throw new WxErrorException(WxError.newBuilder().setErrorMsg("").build());
}
} |
package com.heavyplayer.audioplayerrecorder.util;
import android.media.MediaPlayer;
public class SafeMediaPlayer extends MediaPlayer implements
MediaPlayer.OnPreparedListener,
MediaPlayer.OnCompletionListener,
MediaPlayer.OnBufferingUpdateListener,
MediaPlayer.OnErrorListener {
private final static int CURRENT_POSITION_MIN_PROGRESS = 128;
private OnPreparedListener mOnPreparedListener;
private OnStartListener mOnStartListener;
private OnCompletionListener mOnCompletionListener;
private OnBufferingUpdateListener mOnBufferingUpdateListener;
private OnErrorListener mOnErrorListener;
private State mState;
private boolean mIsGoingToPlay;
private Integer mFixedCurrentPosition;
private CurrentPositionManager mCurrentPositionManager;
private Integer mDuration;
private enum State {
CREATED, PREPARING, PREPARED, STARTED
}
public SafeMediaPlayer() {
mState = State.CREATED;
mIsGoingToPlay = false;
mFixedCurrentPosition = 0;
mCurrentPositionManager = new CurrentPositionManager();
mDuration = 100;
super.setOnPreparedListener(this);
super.setOnCompletionListener(this);
super.setOnBufferingUpdateListener(this);
super.setOnErrorListener(this);
}
@Override
public void setOnPreparedListener(OnPreparedListener listener) {
mOnPreparedListener = listener;
}
public void setOnStartListener(OnStartListener listener) {
mOnStartListener = listener;
}
@Override
public void setOnCompletionListener(OnCompletionListener listener) {
mOnCompletionListener = listener;
}
@Override
public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener) {
mOnBufferingUpdateListener = listener;
}
@Override
public void setOnErrorListener(OnErrorListener listener) {
mOnErrorListener = listener;
}
public boolean isGoingToPlay() {
return mIsGoingToPlay;
}
public boolean isPrepared() {
return mState != State.CREATED;
}
protected boolean isPreparedInner() {
return mState == State.PREPARED || mState == State.STARTED;
}
@Override
public void prepare() throws IllegalStateException {
prepareAsync();
}
@Override
public void prepareAsync() throws IllegalStateException {
mIsGoingToPlay = false;
super.prepareAsync();
mState = State.PREPARING;
}
@Override
public void start() throws IllegalStateException {
mIsGoingToPlay = true;
if(isPreparedInner()) {
final boolean isStarting = !isPlaying();
super.start();
mState = State.STARTED;
mFixedCurrentPosition = null;
mCurrentPositionManager.clear();
if(isStarting && mOnStartListener != null)
mOnStartListener.onStart(this);
}
}
@Override
public void pause() throws IllegalStateException {
mIsGoingToPlay = false;
if(mState == State.STARTED)
super.pause();
}
@Override
public void seekTo(int msec) throws IllegalStateException {
if(isPreparedInner()) {
super.seekTo(msec);
mFixedCurrentPosition = null;
mCurrentPositionManager.set(ensureValidPosition(msec));
}
else {
mFixedCurrentPosition = ensureValidPosition(msec);
mCurrentPositionManager.clear();
}
}
private int ensureValidPosition(int msec) {
return msec < 0 ? 0 : (msec > mDuration ? mDuration : msec);
}
@Override
public void stop() throws IllegalStateException {
mIsGoingToPlay = false;
if(isPreparedInner()) {
super.stop();
mState = State.PREPARED;
}
}
@Override
public void reset() {
super.reset();
mFixedCurrentPosition = 0;
mCurrentPositionManager.clear();
mDuration = 100;
mState = State.CREATED;
if(mOnBufferingUpdateListener != null)
mOnBufferingUpdateListener.onBufferingUpdate(this, 0);
}
@Override
public void onPrepared(MediaPlayer mp) {
mState = State.PREPARED;
adjustCurrentPositionAndDuration();
if(mOnPreparedListener != null)
mOnPreparedListener.onPrepared(mp);
if(mIsGoingToPlay)
start();
}
@Override
public void onCompletion(MediaPlayer mp) {
mIsGoingToPlay = false;
mFixedCurrentPosition = getDuration();
mCurrentPositionManager.clear();
if(mOnCompletionListener != null)
mOnCompletionListener.onCompletion(mp);
}
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
if(mOnBufferingUpdateListener != null)
mOnBufferingUpdateListener.onBufferingUpdate(mp, percent);
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// After an error, we'll need to prepare the media player again.
reset();
return mOnErrorListener != null && mOnErrorListener.onError(mp, what, extra);
}
@Override
public int getCurrentPosition() {
if(mFixedCurrentPosition != null)
return mFixedCurrentPosition;
else
return mCurrentPositionManager != null ? mCurrentPositionManager.get() : super.getCurrentPosition();
}
@Override
public int getDuration() {
return mDuration != null ? mDuration : super.getDuration();
}
private void adjustCurrentPositionAndDuration() {
final float percent = getCurrentPosition() / (float)getDuration();
final int duration = super.getDuration();
if(mDuration != duration) {
mDuration = duration;
seekTo((int)(mDuration * percent));
}
}
public static interface OnStartListener {
public void onStart(MediaPlayer mp);
}
private class CurrentPositionManager {
private Integer mLastCurrentPosition;
private Integer mStepBackPosition;
public void clear() {
mLastCurrentPosition = null;
mStepBackPosition = null;
}
public void set(int msec) {
mLastCurrentPosition = msec;
mStepBackPosition = null;
}
public int get() {
final int currentPosition = SafeMediaPlayer.super.getCurrentPosition();
final int result;
if((mLastCurrentPosition == null || mLastCurrentPosition <= currentPosition) ||
(mStepBackPosition != null && mStepBackPosition < currentPosition)) {
result = currentPosition;
mLastCurrentPosition = currentPosition;
mStepBackPosition = null;
}
else {
result = Math.min(mLastCurrentPosition + CURRENT_POSITION_MIN_PROGRESS, getDuration());
mStepBackPosition = currentPosition;
}
return result;
}
}
} |
package org.sonatype.aether.extension.concurrency;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.codehaus.plexus.component.annotations.Component;
import org.sonatype.aether.extension.concurrency.FileLockManager.AetherFileLock;
/**
* A lock manager using {@link AetherFileLock}s for inter-process locking.
*
* @author Benjamin Hanzelmann
*/
@Component( role = FileLockManager.class )
public class DefaultFileLockManager
implements FileLockManager
{
private Map<File, FileLock> filelocks = new HashMap<File, FileLock>();
private Map<File, AtomicInteger> count = new HashMap<File, AtomicInteger>();
public AetherFileLock readLock( File file )
{
return new DefaultFileLock( this, file, false );
}
public AetherFileLock writeLock( File file )
{
return new DefaultFileLock( this, file, true );
}
private FileLock lookup( File file, boolean write )
throws LockingException
{
FileLock fileLock = null;
synchronized ( filelocks )
{
if ( ( fileLock = filelocks.get( file ) ) == null )
{
fileLock = newFileLock( file, write );
filelocks.put( file, fileLock );
}
else if ( write && fileLock.isShared() )
{
try
{
filelocks.remove( file ).release();
fileLock.channel().close();
}
catch ( IOException e )
{
throw new LockingException( "Could not unlock " + file.getAbsolutePath(), e );
}
filelocks.put( file, fileLock );
}
AtomicInteger c = count.get( file );
if ( c == null )
{
c = new AtomicInteger( 1 );
count.put( file, c );
}
else
{
c.incrementAndGet();
}
}
return fileLock;
}
public FileLock newFileLock( File file, boolean write )
throws LockingException
{
RandomAccessFile raf;
try
{
String mode;
FileChannel channel;
if ( write )
{
file.getParentFile().mkdirs();
mode = "rw";
}
else
{
mode = "r";
}
raf = new RandomAccessFile( file, mode );
channel = raf.getChannel();
try
{
return channel.lock( 0, Math.max( 1, channel.size() ), !write );
}
catch ( IOException e )
{
throw new LockingException( "Could not lock " + channel.toString(), e );
}
}
catch ( LockingException e )
{
Throwable t = e;
if ( t.getCause() instanceof IOException )
{
t = t.getCause();
}
throw new LockingException( "Could not lock " + file.getAbsolutePath(), e );
}
catch ( IOException e )
{
throw new LockingException( "Could not lock " + file.getAbsolutePath(), e );
}
}
private void remove( File file )
throws LockingException
{
synchronized ( filelocks )
{
AtomicInteger c = count.get( file );
if ( c != null && c.decrementAndGet() == 0 )
{
count.remove( file );
try
{
FileLock lock = filelocks.remove( file );
if ( lock.channel().isOpen() )
{
lock.release();
lock.channel().close();
}
}
catch ( IOException e )
{
throw new LockingException( "Could not unlock " + file.getAbsolutePath(), e );
}
}
}
}
public static class DefaultFileLock
implements AetherFileLock
{
private DefaultFileLockManager manager;
private File file;
private boolean write;
private FileLock lock;
private DefaultFileLock( DefaultFileLockManager manager, File file, boolean write )
{
this.manager = manager;
this.file = file;
this.write = write;
}
public void lock()
throws LockingException
{
lookup();
}
private void lookup()
throws LockingException
{
lock = manager.lookup( file, write );
}
public void unlock()
throws LockingException
{
manager.remove( file );
}
public FileChannel channel()
{
return lock.channel();
}
}
} |
package org.python.ReL;
import java.util.*;
import java.io.*;
import com.thinkaurelius.titan.core.schema.SchemaStatus;
import com.thinkaurelius.titan.core.schema.TitanGraphIndex;
import com.thinkaurelius.titan.core.schema.TitanManagement;
import com.thinkaurelius.titan.graphdb.database.management.GraphIndexStatusReport;
import com.thinkaurelius.titan.graphdb.database.management.ManagementSystem;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.python.ReL.WDB.database.wdb.metadata.*;
import com.thinkaurelius.titan.core.*;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.*;
import org.python.ReL.WDB.database.wdb.metadata.ClassDef;
import org.python.ReL.WDB.database.wdb.metadata.IndexDef;
import org.python.ReL.WDB.database.wdb.metadata.Query;
import org.python.ReL.WDB.database.wdb.metadata.WDBObject;
/**
* @author Alvin Deng
* @author Raymond Chee
* @date 05/26/2016
*
* TitanDB Adapter for CarnotKE
*/
public class TitanNoSQLDatabase extends DatabaseInterface {
private static TitanGraph graph = null;
private static File INSTALLATION_ROOT;
private static String PROPERTIES_PATH;
/**
* Initialize TitanDB with defined configurations and populate the database with root node.
*/
private void initTitanDB() {
validateInstallationRoot();
graph = TitanFactory.open(PROPERTIES_PATH);
List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
loggers.add(LogManager.getRootLogger());
for (Logger logger : loggers) {
logger.setLevel(Level.OFF);
}
TitanManagement mgmt = graph.openManagement();
boolean initGraph = mgmt.containsPropertyKey("classDefName");
if(!initGraph) {
initGraph = true;
PropertyKey classDefName = mgmt.makePropertyKey("classDefName").dataType(String.class).make();
VertexLabel classDefLabel = mgmt.makeVertexLabel("classDef").make();
TitanGraphIndex classDefIndex = mgmt.buildIndex("byClassDefName", Vertex.class).addKey(classDefName).
indexOnly(classDefLabel).buildCompositeIndex();
mgmt.commit();
try {
GraphIndexStatusReport classDefReport = ManagementSystem.awaitGraphIndexStatus(graph, "byClassDefName").
status(SchemaStatus.REGISTERED).call();
} catch (Exception e) {
System.out.println("e = " + e.toString());
}
mgmt = graph.openManagement();
PropertyKey WDBObjectName = mgmt.makePropertyKey("WDBObjectName").dataType(String.class).make();
VertexLabel WDBObjectLabel = mgmt.makeVertexLabel("WDBObject").make();
TitanGraphIndex WDBObjectIndex = mgmt.buildIndex("byWDBObjectName", Vertex.class).addKey(WDBObjectName).
indexOnly(WDBObjectLabel).buildCompositeIndex();
mgmt.commit();
try {
GraphIndexStatusReport WDBObjectReport = ManagementSystem.awaitGraphIndexStatus(graph, "byWDBObjectName").
status(SchemaStatus.REGISTERED).call();
} catch (Exception e) {
System.out.println("e = " + e.toString());
}
}
}
/**
* Initialize the INSTALLATION_ROOT path
*/
public void validateInstallationRoot() {
final String serverRoot = System.getenv("INSTALLATION_ROOT");
if (serverRoot == null) {
}
INSTALLATION_ROOT = new File(serverRoot);
if (!INSTALLATION_ROOT.isDirectory()) {
}
PROPERTIES_PATH = new File(serverRoot, "CarnotKE.properties").getAbsolutePath();
}
/**
* Default constructor to support TitanNoSQLAdapter.
*/
public TitanNoSQLDatabase() {
this.adapter = new TitanNoSQLAdapter(this);
initTitanDB();
}
/* Using Bo's implementation logic for WDBObjects */
/**
* Search through the graph and return a proper ClassDef Vertex
* @param classDefName Name of the ClassDef
* @return A ClassDef Vertex
*/
private Vertex getClassDefVertex(String classDefName) {
GraphTraversalSource g = graph.traversal();
GraphTraversal<Vertex, Vertex> graphTraversal = g.V().has("classDefName", classDefName);
while (graphTraversal.hasNext()) {
Vertex currentVertex = graphTraversal.next();
if(currentVertex.property("classDefName").isPresent()) {
if (currentVertex.property("classDefName").value().equals(classDefName)) {
return currentVertex;
}
}
}
return null;
}
/**
* Inserting a ClassDef into the graph
* @param classDef ClassDef object
*/
private void putClassDef(ClassDef classDef) {
Vertex classDefVertex = getClassDefVertex(classDef.name);
if(classDefVertex == null) {
classDefVertex = graph.addVertex(T.label, "classDef", "classDefName", classDef.name);
}
final byte[] data = SerializationUtils.serialize(classDef);
classDefVertex.property("classDefData", data);
graph.tx().commit();
System.out.println("Inserting classDef " + classDef.name + " complete");
}
/**
* Returning a ClassDef object from the graph given the name
* @param classDefName The name of the ClassDef
* @return A ClassDef object with an appropriate name
*/
private ClassDef getClassDef(String classDefName) {
GraphTraversalSource g = graph.traversal();
GraphTraversal<Vertex, Vertex> graphTraversal = g.V().has("classDefName", classDefName);
while (graphTraversal.hasNext()) {
Vertex currentVertex = graphTraversal.next();
if(currentVertex.property("classDefName").isPresent()) {
if (currentVertex.property("classDefName").value().equals(classDefName)) {
return (ClassDef) SerializationUtils.deserialize((byte[]) currentVertex.property("classDefData").value());
}
}
}
return null;
}
/**
* Return a WDBObject Vertex given its WDBObject UID
* @param Uid UID from WDBObject
* @return A WDBObject Vertex from the graph
*/
private Vertex getWDBObjectVertex(Integer Uid) {
GraphTraversalSource g = graph.traversal();
GraphTraversal<Vertex, Vertex> graphTraversal = g.V().has("WDBObjectName", "" + Uid);
while (graphTraversal.hasNext()) {
Vertex currentVertex = graphTraversal.next();
if(currentVertex.property("WDBObjectName").isPresent()) {
if (currentVertex.property("WDBObjectName").value().equals("" + Uid)) {
return currentVertex;
}
}
}
return null;
}
/**
* Inserting a WDBObject into the graph
* @param wdbObject The WDBObject
*/
private void putWDBObject(WDBObject wdbObject) {
Vertex WDBObjectVertex = getWDBObjectVertex(wdbObject.getUid());
if(WDBObjectVertex == null) {
WDBObjectVertex = graph.addVertex(T.label, "WDBObject", "WDBObjectName", "" + wdbObject.getUid());
}
final byte[] data = SerializationUtils.serialize(wdbObject);
WDBObjectVertex.property("WDBObjectData", data);
graph.tx().commit();
System.out.println("Inserting WDBObject " + wdbObject.getUid() + " complete");
}
/**
* Returning a WDBObject in the graph
* @param className Name of the ClassDef
* @param Uid UID of the WDBObject
* @return The WDBObject from the graph
*/
private WDBObject getWDBObject(String className, Integer Uid) {
GraphTraversalSource g = graph.traversal();
GraphTraversal<Vertex, Vertex> graphTraversal = g.V().has("WDBObjectName", "" + Uid);
while (graphTraversal.hasNext()) {
Vertex currentVertex = graphTraversal.next();
if(currentVertex.property("WDBObjectName").isPresent()) {
if (currentVertex.property("WDBObjectName").value().equals("" + Uid)) {
return (WDBObject) SerializationUtils.deserialize((byte[]) currentVertex.property("WDBObjectData").value());
}
}
}
return null;
}
private class TitanNoSQLAdapter implements Adapter {
private TitanNoSQLDatabase db;
/**
* Constructor of TitanNoSQLDatabase.
*
* @param db TitanNoSQLDatabase Object
*/
private TitanNoSQLAdapter(TitanNoSQLDatabase db) {
this.db = db;
}
/**
* Inserting a new ClassDef into the graph.
*
* @param cd ClassDef that needs to be inserted
*/
@Override
public void putClass(ClassDef cd) {
db.putClassDef(cd);
}
/**
* Searches for a ClassDef that matches the query in the graph.
*
* @param query Query that searches for the ClassDef
* @return ClassDef that the query searches for
* @throws ClassNotFoundException When the ClassDef does not exist in the graph
*/
@Override
public ClassDef getClass(Query query) throws ClassNotFoundException {
return getClass(query.queryName);
}
/**
* Searches for a ClassDef that matches to the string name in the graph.
*
* @param s Name of the ClassDef
* @return ClassDef with the name of s
* @throws ClassNotFoundException
*/
@Override
public ClassDef getClass(String s) throws ClassNotFoundException {
ClassDef classDef = db.getClassDef(s);
if (classDef == null) {
throw new ClassNotFoundException("Key is not present in table");
}
return classDef;
}
/**
* Inserting the WDBObject into the graph
* @param wdbObject The WDBObject
*/
@Override
public void putObject(WDBObject wdbObject) {
db.putWDBObject(wdbObject);
}
/**
* Return the WDBObject from the graph with specific requirements
* @param className Name of the ClassDef
* @param Uid UID of the WDBObject
* @return WDBObject from the graph
*/
@Override
public WDBObject getObject(String className, Integer Uid) {
return db.getWDBObject(className, Uid);
}
@Override
public ArrayList<WDBObject> getObjects(IndexDef indexDef, String s) {
throw new UnsupportedOperationException();
}
@Override
public void commit() {
graph.tx().commit();
}
@Override
public void abort() {
}
}
} |
package com.esotericsoftware.kryonet;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.util.IntMap;
import com.esotericsoftware.kryonet.FrameworkMessage.DiscoverHost;
import com.esotericsoftware.kryonet.FrameworkMessage.RegisterTCP;
import com.esotericsoftware.kryonet.FrameworkMessage.RegisterUDP;
import static com.esotericsoftware.minlog.Log.*;
/** Manages TCP and optionally UDP connections from many {@link Client Clients}.
* @author Nathan Sweet <misc@n4te.com> */
public class Server implements EndPoint {
private final Serialization serialization;
private final int writeBufferSize, objectBufferSize;
private final Selector selector;
private ServerSocketChannel serverChannel;
private UdpConnection udp;
private Connection[] connections = {};
private IntMap<Connection> pendingConnections = new IntMap();
Listener[] listeners = {};
private Object listenerLock = new Object();
private int nextConnectionID = 1;
private volatile boolean shutdown;
private Object updateLock = new Object();
private Thread updateThread;
private ByteBuffer emptyBuffer = ByteBuffer.allocate(0);
private Listener dispatchListener = new Listener() {
public void connected (Connection connection) {
Listener[] listeners = Server.this.listeners;
for (int i = 0, n = listeners.length; i < n; i++)
listeners[i].connected(connection);
}
public void disconnected (Connection connection) {
removeConnection(connection);
Listener[] listeners = Server.this.listeners;
for (int i = 0, n = listeners.length; i < n; i++)
listeners[i].disconnected(connection);
}
public void received (Connection connection, Object object) {
Listener[] listeners = Server.this.listeners;
for (int i = 0, n = listeners.length; i < n; i++)
listeners[i].received(connection, object);
}
public void idle (Connection connection) {
Listener[] listeners = Server.this.listeners;
for (int i = 0, n = listeners.length; i < n; i++)
listeners[i].idle(connection);
}
};
/** Creates a Server with a write buffer size of 16384 and an object buffer size of 2048. */
public Server () {
this(16384, 2048);
}
/** @param writeBufferSize One buffer of this size is allocated for each connected client. Objects are serialized to the write
* buffer where the bytes are queued until they can be written to the socket.
* <p>
* Normally the socket is writable and the bytes are written immediately. If the socket cannot be written to and
* enough serialized objects are queued to overflow the buffer, then the connection will be closed.
* <p>
* The write buffer should be sized at least as large as the largest object that will be sent, plus some head room to
* allow for some serialized objects to be queued in case the buffer is temporarily not writable. The amount of head
* room needed is dependent upon the size of objects being sent and how often they are sent.
* @param objectBufferSize Two (using only TCP) or four (using both TCP and UDP) buffers of this size are allocated. These
* buffers are used to hold the bytes for a single object graph until it can be sent over the network or
* deserialized.
* <p>
* The object buffers should be sized at least as large as the largest object that will be sent or received. */
public Server (int writeBufferSize, int objectBufferSize) {
this(writeBufferSize, objectBufferSize, new KryoSerialization());
}
public Server (int writeBufferSize, int objectBufferSize, Serialization serialization) {
this.writeBufferSize = writeBufferSize;
this.objectBufferSize = objectBufferSize;
this.serialization = serialization;
try {
selector = Selector.open();
} catch (IOException ex) {
throw new RuntimeException("Error opening selector.", ex);
}
}
public Serialization getSerialization () {
return serialization;
}
public Kryo getKryo () {
return ((KryoSerialization)serialization).getKryo();
}
/** Opens a TCP only server.
* @throws IOException if the server could not be opened. */
public void bind (int tcpPort) throws IOException {
bind(new InetSocketAddress(tcpPort), null);
}
/** Opens a TCP and UDP server.
* @throws IOException if the server could not be opened. */
public void bind (int tcpPort, int udpPort) throws IOException {
bind(new InetSocketAddress(tcpPort), new InetSocketAddress(udpPort));
}
/** @param udpPort May be null. */
public void bind (InetSocketAddress tcpPort, InetSocketAddress udpPort) throws IOException {
close();
synchronized (updateLock) {
selector.wakeup();
try {
serverChannel = selector.provider().openServerSocketChannel();
serverChannel.socket().bind(tcpPort);
serverChannel.configureBlocking(false);
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
if (DEBUG) debug("kryonet", "Accepting connections on port: " + tcpPort + "/TCP");
if (udpPort != null) {
udp = new UdpConnection(serialization, objectBufferSize);
udp.bind(selector, udpPort);
if (DEBUG) debug("kryonet", "Accepting connections on port: " + udpPort + "/UDP");
}
} catch (IOException ex) {
close();
throw ex;
}
}
if (INFO) info("kryonet", "Server opened.");
}
/** Accepts any new connections and reads or writes any pending data for the current connections.
* @param timeout Wait for up to the specified milliseconds for a connection to be ready to process. May be zero to return
* immediately if there are no connections to process. */
public void update (int timeout) throws IOException {
updateThread = Thread.currentThread();
synchronized (updateLock) { // Blocks to avoid a select while the selector is used to bind the server connection.
}
long startTime = System.currentTimeMillis();
int select = 0;
if (timeout > 0) {
select = selector.select(timeout);
} else {
select = selector.selectNow();
}
System.out.println(select);
if (select == 0) {
// NIO freaks and returns immediately with 0 sometimes, so try to keep from hogging the CPU.
long elapsedTime = System.currentTimeMillis() - startTime;
try {
if (elapsedTime < 25) Thread.sleep(25 - elapsedTime);
} catch (InterruptedException ex) {
}
} else {
Set<SelectionKey> keys = selector.selectedKeys();
synchronized (keys) {
UdpConnection udp = this.udp;
outer:
for (Iterator<SelectionKey> iter = keys.iterator(); iter.hasNext();) {
SelectionKey selectionKey = iter.next();
iter.remove();
Connection fromConnection = (Connection)selectionKey.attachment();
try {
int ops = selectionKey.readyOps();
if (fromConnection != null) { // Must be a TCP read or write operation.
if (udp != null && fromConnection.udpRemoteAddress == null) {
fromConnection.close();
continue;
}
if ((ops & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
try {
while (true) {
Object object = fromConnection.tcp.readObject(fromConnection);
if (object == null) break;
if (DEBUG) {
String objectString = object == null ? "null" : object.getClass().getSimpleName();
if (!(object instanceof FrameworkMessage)) {
debug("kryonet", fromConnection + " received TCP: " + objectString);
} else if (TRACE) {
trace("kryonet", fromConnection + " received TCP: " + objectString);
}
}
fromConnection.notifyReceived(object);
}
} catch (IOException ex) {
if (TRACE) {
trace("kryonet", "Unable to read TCP from: " + fromConnection, ex);
} else if (DEBUG) {
debug("kryonet", fromConnection + " update: " + ex.getMessage());
}
fromConnection.close();
} catch (KryoNetException ex) {
if (ERROR) error("kryonet", "Error reading TCP from connection: " + fromConnection, ex);
fromConnection.close();
}
}
if ((ops & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
try {
fromConnection.tcp.writeOperation();
} catch (IOException ex) {
if (TRACE) {
trace("kryonet", "Unable to write TCP to connection: " + fromConnection, ex);
} else if (DEBUG) {
debug("kryonet", fromConnection + " update: " + ex.getMessage());
}
fromConnection.close();
}
}
continue;
}
if ((ops & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
ServerSocketChannel serverChannel = this.serverChannel;
if (serverChannel == null) continue;
try {
SocketChannel socketChannel = serverChannel.accept();
if (socketChannel != null) acceptOperation(socketChannel);
} catch (IOException ex) {
if (DEBUG) debug("kryonet", "Unable to accept new connection.", ex);
}
continue;
}
// Must be a UDP read operation.
if (udp == null) {
selectionKey.channel().close();
continue;
}
InetSocketAddress fromAddress;
try {
fromAddress = udp.readFromAddress();
} catch (IOException ex) {
if (WARN) warn("kryonet", "Error reading UDP data.", ex);
continue;
}
if (fromAddress == null) continue;
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (fromAddress.equals(connection.udpRemoteAddress)) {
fromConnection = connection;
break;
}
}
Object object;
try {
object = udp.readObject(fromConnection);
} catch (KryoNetException ex) {
if (WARN) {
if (fromConnection != null) {
if (ERROR) error("kryonet", "Error reading UDP from connection: " + fromConnection, ex);
} else
warn("kryonet", "Error reading UDP from unregistered address: " + fromAddress, ex);
}
continue;
}
if (object instanceof FrameworkMessage) {
if (object instanceof RegisterUDP) {
// Store the fromAddress on the connection and reply over TCP with a RegisterUDP to indicate success.
int fromConnectionID = ((RegisterUDP)object).connectionID;
Connection connection = pendingConnections.remove(fromConnectionID);
if (connection != null) {
if (connection.udpRemoteAddress != null) continue outer;
connection.udpRemoteAddress = fromAddress;
addConnection(connection);
connection.sendTCP(new RegisterUDP());
if (DEBUG)
debug("kryonet", "Port " + udp.datagramChannel.socket().getLocalPort() + "/UDP connected to: "
+ fromAddress);
connection.notifyConnected();
continue;
}
if (DEBUG)
debug("kryonet", "Ignoring incoming RegisterUDP with invalid connection ID: " + fromConnectionID);
continue;
}
if (object instanceof DiscoverHost) {
try {
udp.datagramChannel.send(emptyBuffer, fromAddress);
if (DEBUG) debug("kryonet", "Responded to host discovery from: " + fromAddress);
} catch (IOException ex) {
if (WARN) warn("kryonet", "Error replying to host discovery from: " + fromAddress, ex);
}
continue;
}
}
if (fromConnection != null) {
if (DEBUG) {
String objectString = object == null ? "null" : object.getClass().getSimpleName();
if (object instanceof FrameworkMessage) {
if (TRACE) trace("kryonet", fromConnection + " received UDP: " + objectString);
} else
debug("kryonet", fromConnection + " received UDP: " + objectString);
}
fromConnection.notifyReceived(object);
continue;
}
if (DEBUG) debug("kryonet", "Ignoring UDP from unregistered address: " + fromAddress);
} catch (CancelledKeyException ex) {
if (fromConnection != null)
fromConnection.close();
else
selectionKey.channel().close();
}
}
}
}
long time = System.currentTimeMillis();
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (connection.tcp.isTimedOut(time)) {
if (DEBUG) debug("kryonet", connection + " timed out.");
connection.close();
} else {
if (connection.tcp.needsKeepAlive(time)) connection.sendTCP(FrameworkMessage.keepAlive);
}
if (connection.isIdle()) connection.notifyIdle();
}
}
public void run () {
if (TRACE) trace("kryonet", "Server thread started.");
shutdown = false;
while (!shutdown) {
try {
update(250);
} catch (IOException ex) {
if (ERROR) error("kryonet", "Error updating server connections.", ex);
close();
}
}
if (TRACE) trace("kryonet", "Server thread stopped.");
}
public void start () {
new Thread(this, "Server").start();
}
public void stop () {
if (shutdown) return;
close();
if (TRACE) trace("kryonet", "Server thread stopping.");
shutdown = true;
}
private void acceptOperation (SocketChannel socketChannel) {
Connection connection = newConnection();
connection.initialize(serialization, writeBufferSize, objectBufferSize);
connection.endPoint = this;
UdpConnection udp = this.udp;
if (udp != null) connection.udp = udp;
try {
SelectionKey selectionKey = connection.tcp.accept(selector, socketChannel);
selectionKey.attach(connection);
int id = nextConnectionID++;
if (nextConnectionID == -1) nextConnectionID = 1;
connection.id = id;
connection.setConnected(true);
connection.addListener(dispatchListener);
if (udp == null)
addConnection(connection);
else
pendingConnections.put(id, connection);
RegisterTCP registerConnection = new RegisterTCP();
registerConnection.connectionID = id;
connection.sendTCP(registerConnection);
if (udp == null) connection.notifyConnected();
} catch (IOException ex) {
connection.close();
if (DEBUG) debug("kryonet", "Unable to accept TCP connection.", ex);
}
}
/** Allows the connections used by the server to be subclassed. This can be useful for storage per connection without an
* additional lookup. */
protected Connection newConnection () {
return new Connection();
}
private void addConnection (Connection connection) {
Connection[] newConnections = new Connection[connections.length + 1];
newConnections[0] = connection;
System.arraycopy(connections, 0, newConnections, 1, connections.length);
connections = newConnections;
}
void removeConnection (Connection connection) {
ArrayList<Connection> temp = new ArrayList(Arrays.asList(connections));
temp.remove(connection);
connections = temp.toArray(new Connection[temp.size()]);
pendingConnections.remove(connection.id);
}
// BOZO - Provide mechanism for sending to multiple clients without serializing multiple times.
public void sendToAllTCP (Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
connection.sendTCP(object);
}
}
public void sendToAllExceptTCP (int connectionID, Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (connection.id != connectionID) connection.sendTCP(object);
}
}
public void sendToTCP (int connectionID, Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (connection.id == connectionID) {
connection.sendTCP(object);
break;
}
}
}
public void sendToAllUDP (Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
connection.sendUDP(object);
}
}
public void sendToAllExceptUDP (int connectionID, Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (connection.id != connectionID) connection.sendUDP(object);
}
}
public void sendToUDP (int connectionID, Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (connection.id == connectionID) {
connection.sendUDP(object);
break;
}
}
}
public void addListener (Listener listener) {
if (listener == null) throw new IllegalArgumentException("listener cannot be null.");
synchronized (listenerLock) {
Listener[] listeners = this.listeners;
int n = listeners.length;
for (int i = 0; i < n; i++)
if (listener == listeners[i]) return;
Listener[] newListeners = new Listener[n + 1];
newListeners[0] = listener;
System.arraycopy(listeners, 0, newListeners, 1, n);
this.listeners = newListeners;
}
if (TRACE) trace("kryonet", "Server listener added: " + listener.getClass().getName());
}
public void removeListener (Listener listener) {
if (listener == null) throw new IllegalArgumentException("listener cannot be null.");
synchronized (listenerLock) {
Listener[] listeners = this.listeners;
int n = listeners.length;
Listener[] newListeners = new Listener[n - 1];
for (int i = 0, ii = 0; i < n; i++) {
Listener copyListener = listeners[i];
if (listener == copyListener) continue;
if (ii == n - 1) return;
newListeners[ii++] = copyListener;
}
this.listeners = newListeners;
}
if (TRACE) trace("kryonet", "Server listener removed: " + listener.getClass().getName());
}
/** Closes all open connections and the server port(s). */
public void close () {
Connection[] connections = this.connections;
if (INFO && connections.length > 0) info("kryonet", "Closing server connections...");
for (int i = 0, n = connections.length; i < n; i++)
connections[i].close();
connections = new Connection[0];
ServerSocketChannel serverChannel = this.serverChannel;
if (serverChannel != null) {
try {
serverChannel.close();
if (INFO) info("kryonet", "Server closed.");
} catch (IOException ex) {
if (DEBUG) debug("kryonet", "Unable to close server.", ex);
}
this.serverChannel = null;
}
UdpConnection udp = this.udp;
if (udp != null) {
udp.close();
this.udp = null;
}
// Select one last time to complete closing the socket.
synchronized (updateLock) {
selector.wakeup();
try {
selector.selectNow();
} catch (IOException ignored) {
}
}
}
public Thread getUpdateThread () {
return updateThread;
}
/** Returns the current connections. The array returned should not be modified. */
public Connection[] getConnections () {
return connections;
}
} |
package ru.yandex.qatools.allure.aspects;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import ru.yandex.qatools.allure.Allure;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.allure.events.StepFailureEvent;
import ru.yandex.qatools.allure.events.StepFinishedEvent;
import ru.yandex.qatools.allure.events.StepStartedEvent;
import static ru.yandex.qatools.allure.aspects.AllureAspectUtils.getTitle;
@SuppressWarnings("unused")
@Aspect
public class AllureStepsAspects {
@Pointcut("@annotation(ru.yandex.qatools.allure.annotations.Step)")
public void withStepAnnotation() {
//pointcut body, should be empty
}
@Pointcut("execution(* *(..))")
public void anyMethod() {
//pointcut body, should be empty
}
@Before("anyMethod() && withStepAnnotation()")
public void stepStart(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Step step = methodSignature.getMethod().getAnnotation(Step.class);
String stepTitle = getTitle(step.value(), methodSignature.getName(), joinPoint.getArgs());
Allure.LIFECYCLE.fire(new StepStartedEvent(methodSignature.getName()).withTitle(stepTitle));
}
@AfterThrowing(pointcut = "anyMethod() && withStepAnnotation()", throwing = "e")
public void stepFailed(JoinPoint joinPoint, Throwable e) {
Allure.LIFECYCLE.fire(new StepFailureEvent().withThrowable(e));
Allure.LIFECYCLE.fire(new StepFinishedEvent());
}
@AfterReturning(pointcut = "anyMethod() && withStepAnnotation()", returning = "result")
public void stepStop(JoinPoint joinPoint, Object result) {
Allure.LIFECYCLE.fire(new StepFinishedEvent());
}
} |
package org.sagebionetworks.bridge.android.manager.dao;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.AnyThread;
import com.google.common.base.Function;
import com.google.gson.reflect.TypeToken;
import org.sagebionetworks.bridge.rest.RestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Persists objects in SharedPreferences via JSON serialization/deserialization. Transforms can be
* applied to the JSON string, with the transform being applied to the JSON before saving to shared
* prefs, or applied to the string after retrieving from saved prefs. Encryption/decryption are an
* example of useful transforms to apply.
*/
@AnyThread
public class SharedPreferencesJsonDAO {
private static final Logger logger = LoggerFactory.getLogger(SharedPreferencesJsonDAO.class);
protected final SharedPreferences sharedPreferences;
protected SharedPreferencesJsonDAO(Context applicationContext, String preferencesFile) {
sharedPreferences = applicationContext
.getSharedPreferences(preferencesFile, Context.MODE_PRIVATE);
}
protected void removeValue(String key) {
logger.debug("removing key: " + key);
sharedPreferences.edit().remove(key).apply();
}
protected <T> void setValue(String key, T value, Class<? super T> klass) {
String json = RestUtils.GSON.toJson(value, klass);
logger.debug("setting key: " + key + ", value: " + json);
sharedPreferences.edit().putString(key, json).apply();
}
protected <T> T getValue(String key, Class<? extends T> klass) {
String json = sharedPreferences.getString(key, null);
logger.debug("getting key: " + key + ", value: " + json);
return RestUtils.GSON.fromJson(json, klass);
}
protected <T> void setValue(String key, T value, TypeToken<? super T> type) {
String json = RestUtils.GSON.toJson(value, type.getType());
logger.debug("setting key: " + key + ", value: " + json);
sharedPreferences.edit().putString(key, json).apply();
}
protected <T> T getValue(String key, TypeToken<? extends T> type) {
String json = sharedPreferences.getString(key, null);
logger.debug("getting key: " + key + ", value: " + json);
return RestUtils.GSON.fromJson(json, type.getType());
}
protected <T> void setValue(String key, T value, TypeToken<? super T> type,
Function<String, String> transform) {
String json = RestUtils.GSON.toJson(value, type.getType());
logger.debug("setting key: " + key + ", value: " + json);
json = transform.apply(json);
sharedPreferences.edit().putString(key, json).apply();
}
protected <T> T getValue(String key, TypeToken<? extends T> type,
Function<String, String> transform) {
String json = sharedPreferences.getString(key, null);
json = transform.apply(json);
logger.debug("getting key: " + key + ", value: " + json);
return RestUtils.GSON.fromJson(json, type.getType());
}
protected <T> void setValue(String key, T value, Class<? super T> klass,
Function<String, String> transform) {
String json = RestUtils.GSON.toJson(value, klass);
logger.debug("setting key: " + key + ", value: " + json);
json = transform.apply(json);
sharedPreferences.edit().putString(key, json).apply();
}
protected <T> T getValue(String key, Class<? extends T> klass,
Function<String, String> transform) {
String json = sharedPreferences.getString(key, null);
json = transform.apply(json);
logger.debug("getting key: " + key + ", value: " + json);
return RestUtils.GSON.fromJson(json, klass);
}
} |
package versioned.host.exp.exponent.modules.api.sensors;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.view.Surface;
import android.view.WindowManager;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.ChoreographerCompat;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.modules.core.ReactChoreographer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import host.exp.exponent.kernel.ExperienceId;
import host.exp.exponent.kernel.services.sensors.SensorEventListener;
import host.exp.exponent.kernel.services.sensors.SubscribableSensorKernelService;
import host.exp.exponent.kernel.services.sensors.SensorKernelServiceSubscription;
import versioned.host.exp.exponent.modules.ExpoKernelServiceConsumerBaseModule;
public class DeviceMotionModule extends ExpoKernelServiceConsumerBaseModule implements SensorEventListener {
private long mLastUpdate = 0;
private int mUpdateInterval = 100;
private float[] mRotationMatrix = new float[9];
private float[] mRotationResult = new float[3];
private SensorEvent mAccelerationEvent;
private SensorEvent mAccelerationIncludingGravityEvent;
private SensorEvent mRotationEvent;
private SensorEvent mRotationRateEvent;
private SensorEvent mGravityEvent;
private List<SensorKernelServiceSubscription> mServiceSubscriptions = null;
public DeviceMotionModule(ReactApplicationContext reactContext, ExperienceId experienceId) {
super(reactContext, experienceId);
}
@Override
public String getName() {
return "ExponentDeviceMotion";
}
@Nullable
@Override
public Map<String, Object> getConstants() {
return Collections.unmodifiableMap(new HashMap<String, Object>() {
{
put("Gravity", 9.81);
}
});
}
@ReactMethod
public void setUpdateInterval(int updateInterval) {
mUpdateInterval = updateInterval;
}
@ReactMethod
public void startObserving() {
if (mServiceSubscriptions == null) {
mServiceSubscriptions = new ArrayList<>();
for (SubscribableSensorKernelService kernelService : getSensorKernelServices()) {
SensorKernelServiceSubscription subscription = kernelService.createSubscriptionForListener(experienceId, this);
// We want handle update interval on our own,
// because we need to coordinate updates from multiple sensor services.
subscription.setUpdateInterval(0);
mServiceSubscriptions.add(subscription);
}
}
for (SensorKernelServiceSubscription subscription : mServiceSubscriptions) {
subscription.start();
}
}
@ReactMethod
public void stopObserving() {
getReactApplicationContext().runOnUiQueueThread(new Runnable() {
@Override
public void run() {
for (SensorKernelServiceSubscription subscription : mServiceSubscriptions) {
subscription.stop();
}
UiThreadUtil.assertOnUiThread();
mCurrentFrameCallback.stop();
}
});
}
@Override
public void initialize() {
ReactApplicationContext reactContext = getReactApplicationContext();
mDeviceEventEmitter = reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class);
}
private List<SubscribableSensorKernelService> getSensorKernelServices() {
return Arrays.asList(
mKernelServiceRegistry.getGyroscopeKernelService(),
mKernelServiceRegistry.getLinearAccelerationSensorKernelService(),
mKernelServiceRegistry.getAccelerometerKernelService(),
mKernelServiceRegistry.getRotationVectorSensorKernelService(),
mKernelServiceRegistry.getGravitySensorKernelService()
);
}
@Override
public void onSensorDataChanged(SensorEvent sensorEvent) {
Sensor sensor = sensorEvent.sensor;
if (sensor.getType() == Sensor.TYPE_GYROSCOPE) {
mRotationRateEvent = sensorEvent;
} else if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mAccelerationIncludingGravityEvent = sensorEvent;
} else if (sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
mAccelerationEvent = sensorEvent;
} else if (sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
mRotationEvent = sensorEvent;
} else if (sensor.getType() == Sensor.TYPE_GRAVITY) {
mGravityEvent = sensorEvent;
}
mCurrentFrameCallback.maybePostFromNonUI();
}
private ScheduleDispatchFrameCallback mCurrentFrameCallback = new ScheduleDispatchFrameCallback();
private DispatchEventRunnable mDispatchEventRunnable = new DispatchEventRunnable();
private DeviceEventManagerModule.RCTDeviceEventEmitter mDeviceEventEmitter;
private class ScheduleDispatchFrameCallback extends ChoreographerCompat.FrameCallback {
private volatile boolean mIsPosted = false;
private boolean mShouldStop = false;
@Override
public void doFrame(long frameTimeNanos) {
UiThreadUtil.assertOnUiThread();
if (mShouldStop) {
mIsPosted = false;
} else {
post();
}
long curTime = System.currentTimeMillis();
if ((curTime - mLastUpdate) > mUpdateInterval) {
getReactApplicationContext().runOnJSQueueThread(mDispatchEventRunnable);
mLastUpdate = curTime;
}
}
public void stop() {
mShouldStop = true;
}
public void maybePost() {
if (!mIsPosted) {
mIsPosted = true;
post();
}
}
private void post() {
ReactChoreographer.getInstance()
.postFrameCallback(ReactChoreographer.CallbackType.TIMERS_EVENTS, mCurrentFrameCallback);
}
public void maybePostFromNonUI() {
if (mIsPosted) {
return;
}
if (getReactApplicationContext().isOnUiQueueThread()) {
maybePost();
} else {
getReactApplicationContext().runOnUiQueueThread(new Runnable() {
@Override
public void run() {
maybePost();
}
});
}
}
}
private class DispatchEventRunnable implements Runnable {
@Override
public void run() {
Assertions.assertNotNull(mDeviceEventEmitter);
mDeviceEventEmitter.emit("deviceMotionDidUpdate", eventsToMap());
}
}
private WritableMap eventsToMap() {
WritableMap map = Arguments.createMap();
WritableMap acceleration = Arguments.createMap();
WritableMap accelerationIncludingGravity = Arguments.createMap();
WritableMap rotation = Arguments.createMap();
WritableMap rotationRate = Arguments.createMap();
if (mAccelerationEvent != null) {
acceleration.putDouble("x", mAccelerationEvent.values[0]);
acceleration.putDouble("y", mAccelerationEvent.values[1]);
acceleration.putDouble("z", mAccelerationEvent.values[2]);
map.putMap("acceleration", acceleration);
}
if (mAccelerationIncludingGravityEvent != null && mGravityEvent != null) {
accelerationIncludingGravity.putDouble("x", mAccelerationIncludingGravityEvent.values[0] - 2 * mGravityEvent.values[0]);
accelerationIncludingGravity.putDouble("y", mAccelerationIncludingGravityEvent.values[1] - 2 * mGravityEvent.values[1]);
accelerationIncludingGravity.putDouble("z", mAccelerationIncludingGravityEvent.values[2] - 2 * mGravityEvent.values[2]);
map.putMap("accelerationIncludingGravity", accelerationIncludingGravity);
}
if (mRotationRateEvent != null) {
rotationRate.putDouble("alpha", mRotationRateEvent.values[2]);
rotationRate.putDouble("beta", mRotationRateEvent.values[0]);
rotationRate.putDouble("gamma", mRotationRateEvent.values[1]);
map.putMap("rotationRate", rotationRate);
}
if (mRotationEvent != null) {
SensorManager.getRotationMatrixFromVector(mRotationMatrix, mRotationEvent.values);
SensorManager.getOrientation(mRotationMatrix, mRotationResult);
rotation.putDouble("alpha", -mRotationResult[0]);
rotation.putDouble("beta", -mRotationResult[1]);
rotation.putDouble("gamma", mRotationResult[2]);
map.putMap("rotation", rotation);
}
map.putInt("orientation", getOrientation());
return map;
}
private int getOrientation() {
switch(((WindowManager) getReactApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation()) {
case Surface.ROTATION_0:
return 0;
case Surface.ROTATION_90:
return 90;
case Surface.ROTATION_180:
return 180;
case Surface.ROTATION_270:
return -90;
default:
return 0;
}
}
} |
package net.minecraft.src.CraftGuide.ui;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.lwjgl.opengl.GL11;
import net.minecraft.client.Minecraft;
import net.minecraft.src.ItemStack;
import net.minecraft.src.RenderHelper;
import net.minecraft.src.RenderItem;
import net.minecraft.src.Tessellator;
import net.minecraft.src.CraftGuide.Gui;
import net.minecraft.src.CraftGuide.ui.Rendering.GuiTexture;
import net.minecraft.src.CraftGuide.ui.Rendering.IRenderable;
import net.minecraft.src.CraftGuide.ui.Rendering.ITexture;
import net.minecraft.src.CraftGuide.ui.Rendering.Overlay;
import net.minecraft.src.CraftGuide.ui.Rendering.TexturedRect;
public class GuiRenderer
{
private RenderItem itemRenderer = new RenderItem();
private Minecraft minecraft;
private int currentTexture = -1;
private int u, v;
private int colour, alpha;
private float textureWidth = 256, textureHeight = 256;
private List<Overlay> overlays = new LinkedList<Overlay>();
private Gui gui;
private boolean subtexEnabled = false;
private int subtex_x, subtex_y, subtex_width, subtex_height;
private IRenderable itemError = new TexturedRect(-1, -1, 18, 18, GuiTexture.getInstance("/gui/CraftGuide.png"), 238, 200);
public void startFrame(Minecraft mc, Gui gui)
{
GuiTexture.refreshTextures(mc.renderEngine);
currentTexture = -1;
minecraft = mc;
this.gui = gui;
u = 0;
v = 0;
setColour(0xFFFFFF, 0xFF);
}
public void endFrame()
{
for(Overlay overlay: overlays)
{
overlay.renderOverlay(this);
}
overlays.clear();
}
public void setColour(int colour)
{
this.colour = colour;
}
public void setAlpha(int alpha)
{
this.alpha = alpha;
}
public void setColour(int colour, int alpha)
{
setColour(colour);
setAlpha(alpha);
}
public void setTexture(ITexture texture)
{
texture.setActive(this);
}
public void setTextureID(int textureID)
{
clearSubTexture();
if(textureID != currentTexture && textureID != -1 && minecraft != null)
{
minecraft.renderEngine.bindTexture(textureID);
}
}
public void setSubTexture(int x, int y, int width, int height)
{
subtexEnabled = true;
subtex_x = x;
subtex_y = y;
subtex_width = width;
subtex_height = height;
}
public void clearSubTexture()
{
subtexEnabled = false;
}
public void setTextureCoords(int u, int v)
{
this.u = u;
this.v = v;
}
public void drawTexturedRect(int x, int y, int width, int height)
{
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(770, 771);
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.setColorRGBA_I(colour, alpha);
if(subtexEnabled)
{
drawSubTexRect(tessellator, x, y, width, height);
}
else
{
drawTexturedRect(tessellator, x, y, width, height, 0, 0);
}
tessellator.draw();
GL11.glDisable(GL11.GL_BLEND);
}
private void drawSubTexRect(Tessellator tessellator, int x, int y, int width, int height)
{
if(subtex_width < 1 || subtex_height < 1)
{
return;
}
int texX = u % subtex_width;
int texY = v % subtex_height;
int rectX = x;
int rectY = y;
while(rectX < x + width)
{
int subWidth = subtex_width - texX;
if(rectX + subWidth > x + width)
{
subWidth = x + width - rectX;
}
while(rectY < y + height)
{
int subHeight = subtex_height - texY;
if(rectY + subHeight > y + height)
{
subHeight = y + height - rectY;
}
drawTexturedRect(tessellator, rectX, rectY, subWidth, subHeight, texX + subtex_x, texY + subtex_y);
rectY += subtex_height - texY;
texY = 0;
}
texY = v % subtex_height;
rectY = y;
rectX += subtex_width - texX;
texX = 0;
}
}
private void drawTexturedRect(Tessellator tessellator, int x, int y, int width, int height, int u, int v)
{
u += this.u;
v += this.v;
tessellator.addVertexWithUV(x , y + height, 0, (u) / textureWidth , (v + height) / textureHeight);
tessellator.addVertexWithUV(x + width, y + height, 0, (u + width) / textureWidth, (v + height) / textureHeight);
tessellator.addVertexWithUV(x + width, y , 0, (u + width) / textureWidth, (v) / textureHeight);
tessellator.addVertexWithUV(x , y , 0, (u) / textureWidth , (v) / textureHeight);
}
public void drawRect(int x, int y, int width, int height)
{
GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glBlendFunc(770, 771);
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.setColorRGBA_I(colour, alpha);
tessellator.addVertex(x , y + height, 0);
tessellator.addVertex(x + width, y + height, 0);
tessellator.addVertex(x + width, y , 0);
tessellator.addVertex(x , y , 0);
tessellator.draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_BLEND);
}
public void drawGradient(int x, int y, int width, int height, int topColour, int bottomColour)
{
GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glBlendFunc(770, 771);
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glShadeModel(GL11.GL_SMOOTH);
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.setColorRGBA_I(bottomColour & 0xffffff, bottomColour >> 24 & 0xff);
tessellator.addVertex(x , y + height, 0);
tessellator.addVertex(x + width, y + height, 0);
tessellator.setColorRGBA_I(topColour & 0xffffff, topColour >> 24 & 0xff);
tessellator.addVertex(x + width, y , 0);
tessellator.addVertex(x , y , 0);
tessellator.draw();
GL11.glShadeModel(GL11.GL_FLAT);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_BLEND);
}
public void render(IRenderable renderable, int xOffset, int yOffset)
{
renderable.render(this, xOffset, yOffset);
}
public void overlay(Overlay overlay)
{
overlays.add(overlay);
}
public void drawShadowedText(int x, int y, String text)
{
minecraft.fontRenderer.drawStringWithShadow(text, x, y, 0xffffffff);
}
public void drawText(int x, int y, String text)
{
minecraft.fontRenderer.drawString(text, x, y, 0xffffffff);
}
public void drawText(int x, int y, String text, int color)
{
minecraft.fontRenderer.drawString(text, x, y, color);
}
public void drawRightAlignedText(int x, int y, String text, int color)
{
drawText(x - minecraft.fontRenderer.getStringWidth(text), y, text, color);
}
public void drawFloatingText(int x, int y, String text)
{
List<String> list = new ArrayList<String>(1);
list.add(text);
drawFloatingText(x, y, list);
}
public void drawFloatingText(int x, int y, List<String> text)
{
int textWidth = 0;
int textHeight = (text.size() > 1)? text.size() * 10: 8;
for(String s: text)
{
int w = minecraft.fontRenderer.getStringWidth(s);
if(w > textWidth)
{
textWidth = w;
}
}
int xMax = gui.width - textWidth - 4;
if(x > xMax)
{
x = xMax;
}
if(x < 3)
{
x = 3;
}
if(y < 4)
{
y = 4;
}
setColour(0x100010, 0xf0);
drawRect(x - 3, y - 4, textWidth + 6, 1);
drawRect(x - 3, y + textHeight + 3, textWidth + 6, 1);
drawRect(x - 3, y - 3, textWidth + 6, textHeight + 6);
drawRect(x - 4, y - 3, 1, textHeight + 6);
drawRect(x + textWidth + 3, y - 3, 1, textHeight + 6);
setColour(0x5000ff, 0x50);
drawRect(x - 3, y - 3, textWidth + 6, 1);
setColour(0x28007f, 0x50);
drawRect(x - 3, y + textHeight + 2, textWidth + 6, 1);
drawGradient(x - 3, y - 2, 1, textHeight + 4, 0x505000ff, 0x5028007f);
drawGradient(x + textWidth + 2, y - 2, 1, textHeight + 4, 0x505000ff, 0x5028007f);
setColour(0xFFFFFF, 0xFF);
int textY = y;
boolean first = true;
for(String s: text)
{
drawShadowedText(x, textY, s);
if(first)
{
textY += 2;
}
textY += 10;
}
}
public void drawItemStack(ItemStack itemStack, int x, int y)
{
drawItemStack(itemStack, x, y, true);
}
public void drawItemStack(ItemStack itemStack, int x, int y, boolean renderOverlay)
{
boolean error = false;
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glPushMatrix();
GL11.glRotatef(120F, 1.0F, 0.0F, 0.0F);
RenderHelper.enableStandardItemLighting();
GL11.glPopMatrix();
GL11.glPushMatrix();
GL11.glTranslatef(x, y, 0.0F);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(32826 /*GL_RESCALE_NORMAL_EXT*/);
itemRenderer.zLevel = 100.0F;
try
{
itemRenderer.renderItemIntoGUI(minecraft.fontRenderer, minecraft.renderEngine, itemStack, 0, 0);
if(renderOverlay)
{
itemRenderer.renderItemOverlayIntoGUI(minecraft.fontRenderer, minecraft.renderEngine, itemStack, 0, 0);
}
}
catch (Exception e)
{
error = true;
}
itemRenderer.zLevel = 0.0F;
GL11.glDisable(32826 /*GL_RESCALE_NORMAL_EXT*/);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glPopMatrix();
if(error)
{
drawItemStackError(x, y);
}
}
private void drawItemStackError(int x, int y)
{
itemError.render(this, x, y);
}
public void setClippingRegion(int x, int y, int width, int height)
{
GL11.glEnable(GL11.GL_SCISSOR_TEST);
x *= minecraft.displayHeight / (float)gui.height;
y *= minecraft.displayWidth / (float)gui.width;
height *= minecraft.displayHeight / (float)gui.height;
width *= minecraft.displayWidth / (float)gui.width;
GL11.glScissor(x, minecraft.displayHeight - y - height, width, height);
}
public void clearClippingRegion()
{
GL11.glDisable(GL11.GL_SCISSOR_TEST);
}
public int guiXFromMouseX(int x)
{
return (x * gui.width) / minecraft.displayWidth;
}
public int guiYFromMouseY(int y)
{
return gui.height - (y * gui.height) / minecraft.displayHeight - 1;
}
} |
package net.wurstclient.features.mods;
import net.wurstclient.compatibility.WMinecraft;
import net.wurstclient.events.listeners.UpdateListener;
@Mod.Info(description = "Allows you to climb up ladders twice as fast.",
name = "FastLadder",
tags = "FastClimb, fast ladder, fast climb",
help = "Mods/FastLadder")
@Mod.Bypasses(ghostMode = false)
public final class FastLadderMod extends Mod implements UpdateListener
{
@Override
public void onEnable()
{
wurst.events.add(UpdateListener.class, this);
}
@Override
public void onDisable()
{
wurst.events.remove(UpdateListener.class, this);
}
@Override
public void onUpdate()
{
if(WMinecraft.getPlayer().isOnLadder()
&& WMinecraft.getPlayer().isCollidedHorizontally)
WMinecraft.getPlayer().motionY = 0.2872;
}
} |
package nl.mpi.arbil.templates;
import nl.mpi.arbil.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Hashtable;
import javax.swing.ImageIcon;
import nl.mpi.arbil.clarin.CmdiProfileReader;
import nl.mpi.arbil.clarin.CmdiProfileReader.CmdiProfile;
import nl.mpi.arbil.MetadataFile.MetadataReader;
public class ArbilTemplateManager {
//private String defaultArbilTemplateName;
static private ArbilTemplateManager singleInstance = null;
private Hashtable<String, ArbilTemplate> templatesHashTable;
private String[] builtInTemplates2 = {"Default", "Sign Language"}; // the first item in this list is the default template
// private ArbilTemplate defaultArbilTemplate;
//public String[] builtInTemplates = {"Corpus Branch (internal)", "Session (internal)", "Catalogue (internal)", "Sign Language (internal)"};
static synchronized public ArbilTemplateManager getSingleInstance() {
if (singleInstance == null) {
singleInstance = new ArbilTemplateManager();
}
return singleInstance;
}
public File createTemplate(String selectedTemplate) {
if (selectedTemplate.length() == 0) {
return null;
} else if (Arrays.binarySearch(builtInTemplates2, selectedTemplate) > -1) {
return null;
} else {
File selectedTemplateFile = getTemplateFile(selectedTemplate);
selectedTemplateFile.getParentFile().mkdir();
LinorgSessionStorage.getSingleInstance().saveRemoteResource(MetadataReader.class.getResource("/nl/mpi/arbil/resources/templates/template.xml"), selectedTemplateFile, null, true, new DownloadAbortFlag());
new File(selectedTemplateFile.getParentFile(), "components").mkdir(); // create the components directory
File examplesDirectory = new File(selectedTemplateFile.getParentFile(), "example-components");
examplesDirectory.mkdir(); // create the example components directory
// copy example components from the jar file
for (String[] pathString : ArbilTemplateManager.getSingleInstance().getTemplate(builtInTemplates2[0]).templatesArray) {
LinorgSessionStorage.getSingleInstance().saveRemoteResource(MetadataReader.class.getResource("/nl/mpi/arbil/resources/templates/" + pathString[0]), new File(examplesDirectory, pathString[0]), null, true, new DownloadAbortFlag());
}
// copy example "format.xsl" from the jar file which is used in the imdi to html conversion
LinorgSessionStorage.getSingleInstance().saveRemoteResource(MetadataReader.class.getResource("/nl/mpi/arbil/resources/xsl/imdi-viewer.xsl"), new File(selectedTemplateFile.getParentFile(), "example-format.xsl"), null, true, new DownloadAbortFlag());
return selectedTemplateFile;
}
}
public File getTemplateFile(String currentTemplate) {
File currentTemplateFile = new File(getTemplateDirectory().getAbsolutePath() + File.separatorChar + currentTemplate + File.separatorChar + "template.xml");
// if (!currentTemplateFile.getParentFile().exists()) {
// currentTemplateFile.getParentFile().mkdir();
return currentTemplateFile;
}
// public boolean defaultTemplateIsCurrentTemplate() {
// return defaultArbilTemplateName.equals(builtInTemplates2[0]);
// public String getCurrentTemplateName() {
// return defaultArbilTemplateName;
// public void setCurrentTemplate(String currentTemplateLocal) {
// defaultArbilTemplateName = currentTemplateLocal;
// try {
// LinorgSessionStorage.getSingleInstance().saveString("CurrentTemplate", currentTemplateLocal);
// } catch (Exception ex) {
// GuiHelper.linorgBugCatcher.logError(ex);
public File getTemplateDirectory() {
return new File(LinorgSessionStorage.getSingleInstance().storageDirectory, "templates");
}
public void addSelectedTemplates(String templateString) {
ArrayList<String> selectedTamplates = new ArrayList<String>();
try {
selectedTamplates.addAll(Arrays.asList(LinorgSessionStorage.getSingleInstance().loadStringArray("selectedTemplates")));
} catch (Exception e) {
GuiHelper.linorgBugCatcher.logError("No selectedTemplates file, will create one now.", e);
}
selectedTamplates.add(templateString);
LinorgSessionStorage.getSingleInstance().saveStringArray("selectedTemplates", selectedTamplates.toArray(new String[]{}));
}
public void removeSelectedTemplates(String templateString) {
ArrayList<String> selectedTamplates = new ArrayList<String>();
selectedTamplates.addAll(Arrays.asList(LinorgSessionStorage.getSingleInstance().loadStringArray("selectedTemplates")));
while (selectedTamplates.contains(templateString)) {
selectedTamplates.remove(templateString);
}
LinorgSessionStorage.getSingleInstance().saveStringArray("selectedTemplates", selectedTamplates.toArray(new String[]{}));
}
public ArrayList<String> getSelectedTemplateArrayList() {
ArrayList<String> selectedTamplates = new ArrayList<String>();
try {
selectedTamplates.addAll(Arrays.asList(LinorgSessionStorage.getSingleInstance().loadStringArray("selectedTemplates")));
} catch (Exception e) {
GuiHelper.linorgBugCatcher.logError("No selectedTemplates file, will create one now.", e);
addDefaultTemplates();
}
return selectedTamplates;
}
public class MenuItemData {
public String menuText;
public String menuAction;
public String menuToolTip;
public ImageIcon menuIcon;
}
private void addDefaultTemplates() {
addSelectedTemplates("builtin:METATRANSCRIPT.Corpus.xml");
addSelectedTemplates("builtin:METATRANSCRIPT.Catalogue.xml");
addSelectedTemplates("builtin:METATRANSCRIPT.Session.xml");
}
public MenuItemData[] getSelectedTemplates() {
ImdiIcons imdiIcons = ImdiIcons.getSingleInstance();
String[] locationsArray = LinorgSessionStorage.getSingleInstance().loadStringArray("selectedTemplates");
if (locationsArray == null || locationsArray.length == 0) {
addDefaultTemplates();
locationsArray = LinorgSessionStorage.getSingleInstance().loadStringArray("selectedTemplates");
}
MenuItemData[] returnArray = new MenuItemData[locationsArray.length];
for (int insertableCounter = 0; insertableCounter < locationsArray.length; insertableCounter++) {
returnArray[insertableCounter] = new MenuItemData();
if (locationsArray[insertableCounter].startsWith("builtin:")) {
String currentString = locationsArray[insertableCounter].substring("builtin:".length());
for (String currentTemplateName[] : ArbilTemplateManager.getSingleInstance().getTemplate(null).rootTemplatesArray) {
if (currentString.equals(currentTemplateName[0])) {
returnArray[insertableCounter].menuText = currentTemplateName[1];
returnArray[insertableCounter].menuAction = "." + currentTemplateName[0].replaceFirst("\\.xml$", "");
returnArray[insertableCounter].menuToolTip = currentTemplateName[1];
if (returnArray[insertableCounter].menuText.contains("Corpus")) {
returnArray[insertableCounter].menuIcon = imdiIcons.corpusnodeColorIcon;
} else if (returnArray[insertableCounter].menuText.contains("Catalogue")) {
returnArray[insertableCounter].menuIcon = imdiIcons.catalogueColorIcon;
} else {
returnArray[insertableCounter].menuIcon = imdiIcons.sessionColorIcon;
}
}
}
} else if (locationsArray[insertableCounter].startsWith("custom:")) {
String currentString = locationsArray[insertableCounter].substring("custom:".length());
returnArray[insertableCounter].menuText = currentString.substring(currentString.lastIndexOf("/") + 1);
returnArray[insertableCounter].menuAction = currentString;
returnArray[insertableCounter].menuToolTip = currentString;
returnArray[insertableCounter].menuIcon = imdiIcons.clarinIcon;
} else if (locationsArray[insertableCounter].startsWith("template:")) {
// todo:
String currentString = locationsArray[insertableCounter].substring("template:".length());
returnArray[insertableCounter].menuText = currentString + " (not available)";
returnArray[insertableCounter].menuAction = currentString;
returnArray[insertableCounter].menuToolTip = currentString;
returnArray[insertableCounter].menuIcon = imdiIcons.sessionColorIcon;
} else if (locationsArray[insertableCounter].startsWith("clarin:")) {
String currentString = locationsArray[insertableCounter].substring("clarin:".length());
CmdiProfile cmdiProfile = CmdiProfileReader.getSingleInstance().getProfile(currentString);
returnArray[insertableCounter].menuText = cmdiProfile.name;
returnArray[insertableCounter].menuAction = cmdiProfile.getXsdHref();
returnArray[insertableCounter].menuToolTip = cmdiProfile.description;
returnArray[insertableCounter].menuIcon = imdiIcons.clarinIcon;
}
}
Arrays.sort(returnArray, new Comparator() {
public int compare(Object firstItem, Object secondItem) {
return (((MenuItemData) firstItem).menuText.compareToIgnoreCase(((MenuItemData) secondItem).menuText));
}
});
return returnArray;
// Vector childTypes = new Vector();
// if (targetNodeUserObject instanceof ImdiTreeObject) {
// String xpath = MetadataReader.getNodePath((ImdiTreeObject) targetNodeUserObject);
// childTypes = getSubnodesFromTemplatesDir(xpath); // add the main entries based on the node path of the target
// if (((ImdiTreeObject) targetNodeUserObject).isCorpus()) { // add any corpus node entries
// for (String[] currentTemplate : rootTemplatesArray) {
// boolean suppressEntry = false;
// if (currentTemplate[1].equals("Catalogue")) {
// if (((ImdiTreeObject) targetNodeUserObject).hasCatalogue()) {
// // make sure the catalogue can only be added once
// suppressEntry = true;
// if (!suppressEntry) {
// childTypes.add(new String[]{currentTemplate[1], "." + currentTemplate[0].replaceFirst("\\.xml$", "")});
//// System.out.println("childTypes: " + childTypes);
// } else {
// // add the the root node items
// for (String[] currentTemplate : rootTemplatesArray) {
// if (!currentTemplate[1].equals("Catalogue")) {// make sure the catalogue can not be added at the root level
// childTypes.add(new String[]{"Unattached " + currentTemplate[1], "." + currentTemplate[0].replaceFirst("\\.xml$", "")});
// Collections.sort(childTypes, new Comparator() {
// public int compare(Object o1, Object o2) {
// String value1 = ((String[]) o1)[0];
// String value2 = ((String[]) o2)[0];
// return value1.compareTo(value2);
// return childTypes.elements();
// HashSet<String> locationsSet = new HashSet<String>();
// for (ImdiTreeObject[] currentTreeArray : new ImdiTreeObject[][]{remoteCorpusNodes, localCorpusNodes, localFileNodes, favouriteNodes}) {
// for (ImdiTreeObject currentLocation : currentTreeArray) {
// locationsSet.add(currentLocation.getUrlString());
// if (nodesToAdd != null) {
// for (ImdiTreeObject currentAddable : nodesToAdd) {
// locationsSet.add(currentAddable.getUrlString());
// if (nodesToRemove != null) {
// for (ImdiTreeObject currentRemoveable : nodesToRemove) {
// locationsSet.remove(currentRemoveable.getUrlString());
// Vector<String> locationsList = new Vector<String>(); // this vector is kept for backwards compatability
// for (String currentLocation : locationsSet) {
// locationsList.add(URLDecoder.decode(currentLocation, "UTF-8"));
// //LinorgSessionStorage.getSingleInstance().saveObject(locationsList, "locationsList");
// LinorgSessionStorage.getSingleInstance().saveStringArray("locationsList", locationsList.toArray(new String[]{}));
}
public String[] getAvailableTemplates() {
File templatesDir = getTemplateDirectory();
if (!templatesDir.exists()) {
templatesDir.mkdir();
}
ArrayList<String> templateList = new ArrayList<String>();
String[] templatesList = templatesDir.list();
for (String currentTemplateName : templatesList) {
// if the template file does not exist then remove from the array
if (getTemplateFile(currentTemplateName).exists()) {
templateList.add(currentTemplateName);
}
}
// for (String currentTemplateName : builtInTemplates) {
// // add the Default and SignLanguage built in templates
// templateList.add(currentTemplateName);
templatesList = templateList.toArray(new String[]{});
Arrays.sort(templatesList);
return templatesList;
}
private ArbilTemplateManager() {
templatesHashTable = new Hashtable<String, ArbilTemplate>();
// defaultArbilTemplateName = LinorgSessionStorage.getSingleInstance().loadString("CurrentTemplate");
// if (defaultArbilTemplateName == null) {
// defaultArbilTemplateName = builtInTemplates2[0];
// LinorgSessionStorage.getSingleInstance().saveString("CurrentTemplate", defaultArbilTemplateName);
}
public ArbilTemplate getDefaultTemplate() {
return getTemplate(builtInTemplates2[0]);
}
public ArbilTemplate getCmdiTemplate(String nameSpaceString) {
if (nameSpaceString != null) {
CmdiTemplate cmdiTemplate = (CmdiTemplate) templatesHashTable.get(nameSpaceString);
if (cmdiTemplate == null) {
cmdiTemplate = new CmdiTemplate();
cmdiTemplate.loadTemplate(nameSpaceString);
templatesHashTable.put(nameSpaceString, cmdiTemplate);
}
return cmdiTemplate;
} else {
GuiHelper.linorgBugCatcher.logError(new Exception("Name space URL not provided, cannot load the CMDI template, please check the XML file and ensure that the name space is specified."));
return null;
}
}
public ArbilTemplate getTemplate(String templateName) {
ArbilTemplate returnTemplate = new ArbilTemplate();
if (templateName == null) {
templateName = builtInTemplates2[0]; // if the template does not exist the default values will be loaded
}
if (!templatesHashTable.containsKey(templateName)) {
// LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Template Not Found: " + templateName, "Arbil Template Manager");
returnTemplate.readTemplate(getTemplateFile(templateName), templateName);
templatesHashTable.put(templateName, returnTemplate);
} else {
returnTemplate = templatesHashTable.get(templateName);
}
return returnTemplate;
}
} |
package com.dafrito.lua.script;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Iterator;
import lua.LuaLibrary;
import org.junit.Before;
import org.junit.Test;
public class LuaTableTest {
private static final String V = "No time";
LuaLibrary lua = LuaLibrary.INSTANCE;
private LuaBindings b;
private LuaScriptContext ctx;
@Before
public void setup() {
ctx = new LuaScriptContext();
b = ctx.getGlobals();
}
@Test
public void getAndPutAValueIntoATable() throws Exception {
LuaTable t = new LuaTable(b);
t.set(1, V);
assertEquals(V, t.get(1));
}
@Test
public void sizeOfOneElementTableIsOne() throws Exception {
LuaTable t = new LuaTable(b);
t.add(V);
assertEquals(1, t.size());
}
@Test
public void testRemovingAnElementMakesTheTableEmpty() throws Exception {
LuaTable t = new LuaTable(b);
t.add(V);
t.remove(0);
assertTrue(t.isEmpty());
}
@Test
public void iterateOverAnEmptyTable() throws Exception {
LuaTable t = new LuaTable(b);
assertFalse(t.iterator().hasNext());
}
@Test
public void iterateOverAnOneElementTable() throws Exception {
LuaTable t = new LuaTable(b);
t.add(V);
t.add(42.0d);
Iterator<Object> i = t.iterator();
assertTrue(i.hasNext());
assertEquals(V, i.next());
assertEquals(42.0d, i.next());
assertFalse(i.hasNext());
}
@Test
public void removeAnElementUsingAnIterator() throws Exception {
LuaTable t = new LuaTable(b);
t.add("A");
t.add("B");
t.add("C");
int counter=0;
for(Iterator<Object> i = t.iterator(); i.hasNext();) {
counter++;
Object v = i.next();
if(v.equals("B")) {
i.remove();
}
}
assertEquals(3, counter);
assertEquals(2, t.size());
}
} |
package nodomain.freeyourgadget.gadgetbridge.service.devices.waspos;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.net.Uri;
import android.text.format.DateFormat;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.UUID;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventCallControl;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventFindPhone;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventMusicControl;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventNotificationControl;
import nodomain.freeyourgadget.gadgetbridge.devices.waspos.WaspOSConstants;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.Alarm;
import nodomain.freeyourgadget.gadgetbridge.model.BatteryState;
import nodomain.freeyourgadget.gadgetbridge.model.CalendarEventSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CallSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CannedMessagesSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec;
import nodomain.freeyourgadget.gadgetbridge.model.WeatherSpec;
import nodomain.freeyourgadget.gadgetbridge.service.btle.AbstractBTLEDeviceSupport;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.util.AlarmUtils;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
import nodomain.freeyourgadget.gadgetbridge.util.Prefs;
public class WaspOSDeviceSupport extends AbstractBTLEDeviceSupport {
private static final Logger LOG = LoggerFactory.getLogger(WaspOSDeviceSupport.class);
private BluetoothGattCharacteristic rxCharacteristic = null;
private BluetoothGattCharacteristic txCharacteristic = null;
private String receivedLine = "";
public WaspOSDeviceSupport() {
super(LOG);
addSupportedService(WaspOSConstants.UUID_SERVICE_NORDIC_UART);
}
@Override
protected TransactionBuilder initializeDevice(TransactionBuilder builder) {
LOG.info("Initializing");
gbDevice.setState(GBDevice.State.INITIALIZING);
gbDevice.sendDeviceUpdateIntent(getContext());
rxCharacteristic = getCharacteristic(WaspOSConstants.UUID_CHARACTERISTIC_NORDIC_UART_RX);
txCharacteristic = getCharacteristic(WaspOSConstants.UUID_CHARACTERISTIC_NORDIC_UART_TX);
builder.setGattCallback(this);
builder.notify(rxCharacteristic, true);
uartTx(builder, " \u0003"); // clear active line
Prefs prefs = GBApplication.getPrefs();
if (prefs.getBoolean("datetime_synconconnect", true))
setTime(builder);
//sendSettings(builder);
// get version
gbDevice.setState(GBDevice.State.INITIALIZED);
gbDevice.sendDeviceUpdateIntent(getContext());
LOG.info("Initialization Done");
return builder;
}
/// Write a string of data, and chunk it up
private void uartTx(TransactionBuilder builder, String str) {
LOG.info("UART TX: " + str);
byte[] bytes;
bytes = str.getBytes(StandardCharsets.ISO_8859_1);
for (int i=0;i<bytes.length;i+=8) {
int l = bytes.length-i;
if (l>8) l=8;
byte[] packet = new byte[l];
System.arraycopy(bytes, i, packet, 0, l);
builder.write(txCharacteristic, packet);
}
}
/// Write a string of data, and chunk it up
private void uartTxJSON(String taskName, JSONObject json) {
try {
TransactionBuilder builder = performInitialized(taskName);
uartTx(builder, "\u0010GB("+json.toString()+")\n");
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error in "+taskName+": " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
private void handleUartRxLine(String line) {
LOG.info("UART RX LINE: " + line);
if (">Uncaught ReferenceError: \"gb\" is not defined".equals(line))
GB.toast(getContext(), "Gadgetbridge plugin not installed on Bangle.js", Toast.LENGTH_LONG, GB.ERROR);
else if (line.charAt(0)=='{') {
// JSON - we hope!
try {
JSONObject json = new JSONObject(line);
handleUartRxJSON(json);
} catch (JSONException e) {
GB.toast(getContext(), "Malformed JSON from Bangle.js: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
private void handleUartRxJSON(JSONObject json) throws JSONException {
switch (json.getString("t")) {
case "info":
GB.toast(getContext(), "Bangle.js: " + json.getString("msg"), Toast.LENGTH_LONG, GB.INFO);
break;
case "warn":
GB.toast(getContext(), "Bangle.js: " + json.getString("msg"), Toast.LENGTH_LONG, GB.WARN);
break;
case "error":
GB.toast(getContext(), "Bangle.js: " + json.getString("msg"), Toast.LENGTH_LONG, GB.ERROR);
break;
case "status": {
Context context = getContext();
if (json.has("bat")) {
int b = json.getInt("bat");
if (b<0) b=0;
if (b>100) b=100;
gbDevice.setBatteryLevel((short)b);
if (b < 30) {
gbDevice.setBatteryState(BatteryState.BATTERY_LOW);
GB.updateBatteryNotification(context.getString(R.string.notif_battery_low_percent, gbDevice.getName(), String.valueOf(b)), "", context);
} else {
gbDevice.setBatteryState(BatteryState.BATTERY_NORMAL);
GB.removeBatteryNotification(context);
}
}
if (json.has("volt"))
gbDevice.setBatteryVoltage((float)json.getDouble("volt"));
gbDevice.sendDeviceUpdateIntent(context);
} break;
case "findPhone": {
boolean start = json.has("n") && json.getBoolean("n");
GBDeviceEventFindPhone deviceEventFindPhone = new GBDeviceEventFindPhone();
deviceEventFindPhone.event = start ? GBDeviceEventFindPhone.Event.START : GBDeviceEventFindPhone.Event.STOP;
evaluateGBDeviceEvent(deviceEventFindPhone);
} break;
case "music": {
GBDeviceEventMusicControl deviceEventMusicControl = new GBDeviceEventMusicControl();
deviceEventMusicControl.event = GBDeviceEventMusicControl.Event.valueOf(json.getString("n").toUpperCase());
evaluateGBDeviceEvent(deviceEventMusicControl);
} break;
case "call": {
GBDeviceEventCallControl deviceEventCallControl = new GBDeviceEventCallControl();
deviceEventCallControl.event = GBDeviceEventCallControl.Event.valueOf(json.getString("n").toUpperCase());
evaluateGBDeviceEvent(deviceEventCallControl);
} break;
case "notify" : {
GBDeviceEventNotificationControl deviceEvtNotificationControl = new GBDeviceEventNotificationControl();
// .title appears unused
deviceEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.valueOf(json.getString("n").toUpperCase());
if (json.has("id"))
deviceEvtNotificationControl.handle = json.getInt("id");
if (json.has("tel"))
deviceEvtNotificationControl.phoneNumber = json.getString("tel");
if (json.has("msg"))
deviceEvtNotificationControl.reply = json.getString("msg");
evaluateGBDeviceEvent(deviceEvtNotificationControl);
} break;
/*case "activity": {
WaspOSActivitySample sample = new WaspOSActivitySample();
sample.setTimestamp((int) (GregorianCalendar.getInstance().getTimeInMillis() / 1000L));
sample.setHeartRate(json.getInteger("hrm"));
try (DBHandler dbHandler = GBApplication.acquireDB()) {
Long userId = DBHelper.getUser(dbHandler.getDaoSession()).getId();
Long deviceId = DBHelper.getDevice(getDevice(), dbHandler.getDaoSession()).getId();
WaspOSSampleProvider provider = new WaspOSSampleProvider(getDevice(), dbHandler.getDaoSession());
sample.setDeviceId(deviceId);
sample.setUserId(userId);
provider.addGBActivitySample(sample);
} catch (Exception ex) {
LOG.warn("Error saving current heart rate: " + ex.getLocalizedMessage());
}
} break;*/
}
}
@Override
public boolean onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
if (super.onCharacteristicChanged(gatt, characteristic)) {
return true;
}
if (WaspOSConstants.UUID_CHARACTERISTIC_NORDIC_UART_RX.equals(characteristic.getUuid())) {
byte[] chars = characteristic.getValue();
String packetStr = new String(chars);
LOG.info("RX: " + packetStr);
receivedLine += packetStr;
while (receivedLine.contains("\n")) {
int p = receivedLine.indexOf("\n");
String line = receivedLine.substring(0,p-1);
receivedLine = receivedLine.substring(p+1);
handleUartRxLine(line);
}
}
return false;
}
void setTime(TransactionBuilder builder) {
CharSequence formattedDate = DateFormat.format("(yyyy, MM, dd, HH, mm, ss)", new java.util.Date());
String cmd = "\u0010watch.rtc.set_localtime(" + formattedDate + ")\n";
uartTx(builder, cmd + "\n");
}
@Override
public boolean useAutoConnect() {
return true;
}
@Override
public void onNotification(NotificationSpec notificationSpec) {
try {
JSONObject o = new JSONObject();
o.put("t", "notify");
o.put("id", notificationSpec.getId());
o.put("src", notificationSpec.sourceName);
o.put("title", notificationSpec.title);
o.put("subject", notificationSpec.subject);
o.put("body", notificationSpec.body);
o.put("sender", notificationSpec.sender);
o.put("tel", notificationSpec.phoneNumber);
uartTxJSON("onNotification", o);
} catch (JSONException e) {
LOG.info("JSONException: " + e.getLocalizedMessage());
}
}
@Override
public void onDeleteNotification(int id) {
try {
JSONObject o = new JSONObject();
o.put("t", "notify-");
o.put("id", id);
uartTxJSON("onDeleteNotification", o);
} catch (JSONException e) {
LOG.info("JSONException: " + e.getLocalizedMessage());
}
}
@Override
public void onSetTime() {
try {
TransactionBuilder builder = performInitialized("setTime");
setTime(builder);
builder.queue(getQueue());
} catch (Exception e) {
GB.toast(getContext(), "Error setting time: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
@Override
public void onSetAlarms(ArrayList<? extends Alarm> alarms) {
try {
JSONObject o = new JSONObject();
o.put("t", "alarm");
JSONArray jsonalarms = new JSONArray();
o.put("d", jsonalarms);
for (Alarm alarm : alarms) {
if (!alarm.getEnabled()) continue;
JSONObject jsonalarm = new JSONObject();
jsonalarms.put(jsonalarm);
Calendar calendar = AlarmUtils.toCalendar(alarm);
// TODO: getRepetition to ensure it only happens on correct day?
jsonalarm.put("h", alarm.getHour());
jsonalarm.put("m", alarm.getMinute());
}
uartTxJSON("onSetAlarms", o);
} catch (JSONException e) {
LOG.info("JSONException: " + e.getLocalizedMessage());
}
}
@Override
public void onSetCallState(CallSpec callSpec) {
try {
JSONObject o = new JSONObject();
o.put("t", "call");
String[] cmdString = {"", "undefined", "accept", "incoming", "outgoing", "reject", "start", "end"};
o.put("cmd", cmdString[callSpec.command]);
o.put("name", callSpec.name);
o.put("number", callSpec.number);
uartTxJSON("onSetCallState", o);
} catch (JSONException e) {
LOG.info("JSONException: " + e.getLocalizedMessage());
}
}
@Override
public void onSetCannedMessages(CannedMessagesSpec cannedMessagesSpec) {
}
@Override
public void onSetMusicState(MusicStateSpec stateSpec) {
try {
JSONObject o = new JSONObject();
o.put("t", "musicstate");
String[] musicStates = {"play", "pause", "stop", ""};
o.put("state", musicStates[stateSpec.state]);
o.put("position", stateSpec.position);
o.put("shuffle", stateSpec.shuffle);
o.put("repeat", stateSpec.repeat);
uartTxJSON("onSetMusicState", o);
} catch (JSONException e) {
LOG.info("JSONException: " + e.getLocalizedMessage());
}
}
@Override
public void onSetMusicInfo(MusicSpec musicSpec) {
try {
JSONObject o = new JSONObject();
o.put("t", "musicinfo");
o.put("artist", musicSpec.artist);
o.put("album", musicSpec.album);
o.put("track", musicSpec.track);
o.put("dur", musicSpec.duration);
o.put("c", musicSpec.trackCount);
o.put("n", musicSpec.trackNr);
uartTxJSON("onSetMusicInfo", o);
} catch (JSONException e) {
LOG.info("JSONException: " + e.getLocalizedMessage());
}
}
@Override
public void onEnableRealtimeSteps(boolean enable) {
}
@Override
public void onInstallApp(Uri uri) {
}
@Override
public void onAppInfoReq() {
}
@Override
public void onAppStart(UUID uuid, boolean start) {
}
@Override
public void onAppDelete(UUID uuid) {
}
@Override
public void onAppConfiguration(UUID appUuid, String config, Integer id) {
}
@Override
public void onAppReorder(UUID[] uuids) {
}
@Override
public void onFetchRecordedData(int dataTypes) {
}
@Override
public void onReset(int flags) {
}
@Override
public void onHeartRateTest() {
}
@Override
public void onEnableRealtimeHeartRateMeasurement(boolean enable) {
}
@Override
public void onFindDevice(boolean start) {
try {
JSONObject o = new JSONObject();
o.put("t", "find");
o.put("n", start);
uartTxJSON("onFindDevice", o);
} catch (JSONException e) {
LOG.info("JSONException: " + e.getLocalizedMessage());
}
}
@Override
public void onSetConstantVibration(int integer) {
try {
JSONObject o = new JSONObject();
o.put("t", "vibrate");
o.put("n", integer);
uartTxJSON("onSetConstantVibration", o);
} catch (JSONException e) {
LOG.info("JSONException: " + e.getLocalizedMessage());
}
}
@Override
public void onScreenshotReq() {
}
@Override
public void onEnableHeartRateSleepSupport(boolean enable) {
}
@Override
public void onSetHeartRateMeasurementInterval(int seconds) {
}
@Override
public void onAddCalendarEvent(CalendarEventSpec calendarEventSpec) {
}
@Override
public void onDeleteCalendarEvent(byte type, long id) {
}
@Override
public void onSendConfiguration(String config) {
}
@Override
public void onReadConfiguration(String config) {
}
@Override
public void onTestNewFunction() {
}
@Override
public void onSendWeather(WeatherSpec weatherSpec) {
try {
JSONObject o = new JSONObject();
o.put("t", "weather");
o.put("temp", weatherSpec.currentTemp);
o.put("hum", weatherSpec.currentHumidity);
o.put("txt", weatherSpec.currentCondition);
o.put("wind", weatherSpec.windSpeed);
o.put("loc", weatherSpec.location);
uartTxJSON("onSendWeather", o);
} catch (JSONException e) {
LOG.info("JSONException: " + e.getLocalizedMessage());
}
}
} |
package com.atlassian.pageobjects.elements;
import com.atlassian.pageobjects.elements.query.AbstractTimedQuery;
import com.atlassian.pageobjects.elements.query.ExpirationHandler;
import com.atlassian.pageobjects.elements.query.PollingQuery;
import com.atlassian.pageobjects.elements.query.TimedQuery;
import com.atlassian.webdriver.AtlassianWebDriver;
import com.atlassian.webdriver.utils.element.ElementLocated;
import org.hamcrest.StringDescription;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.TimeoutException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.atlassian.pageobjects.elements.query.Poller.waitUntil;
import static org.hamcrest.Matchers.notNullValue;
/**
* Creates WebDriveLocatables for different search strategies
*/
public class WebDriverLocators
{
/**
* Creates the root of a WebDriverLocatable list, usually the instance of WebDriver
* @return WebDriverLocatable
*/
public static WebDriverLocatable root()
{
return new WebDriverRootLocator();
}
/**
* Creates a WebDriverLocatable for a single element
* @param locator The locator strategy within the parent
* @param parent The locatable for the parent
* @return WebDriverLocatable
*/
public static WebDriverLocatable single(By locator, WebDriverLocatable parent)
{
return new WebDriverSingleLocator(locator, parent);
}
/**
* Creates a WebDriverLocatable for an element included in a list initialized with given element
* @param element WebElement
* @param locator The locator strategy within the parent that will produce a list of matches
* @param locatorIndex The index within the list of matches to find this element
* @param parent The locatable for the parent
* @return WebDriverLocatable
*/
public static WebDriverLocatable list(WebElement element, By locator, int locatorIndex, WebDriverLocatable parent)
{
return new WebDriverListLocator(element,locator, locatorIndex, parent);
}
/**
* Whether the given WebElement is stale (needs to be relocated)
* @param webElement WebElement
* @return True if element reference is stale, false otherwise
*/
public static boolean isStale(final WebElement webElement)
{
try
{
webElement.getTagName();
return false;
}
catch (StaleElementReferenceException ignored)
{
return true;
}
}
private static class WebDriverRootLocator implements WebDriverLocatable
{
public By getLocator()
{
return null;
}
public WebDriverLocatable getParent()
{
return null;
}
public SearchContext waitUntilLocated(AtlassianWebDriver driver, int timeoutInSeconds)
{
return driver;
}
public boolean isPresent(AtlassianWebDriver driver, int timeoutForParentInSeconds)
{
return true;
}
}
private static class WebDriverSingleLocator implements WebDriverLocatable
{
private WebElement webElement = null;
private boolean webElementLocated = false;
private final By locator;
private final WebDriverLocatable parent;
public WebDriverSingleLocator(By locator, WebDriverLocatable parent)
{
this.locator = locator;
this.parent = parent;
}
public By getLocator()
{
return locator;
}
public WebDriverLocatable getParent()
{
return parent;
}
public SearchContext waitUntilLocated(AtlassianWebDriver driver, int timeoutInSeconds)
{
if(!webElementLocated || WebDriverLocators.isStale(webElement))
{
SearchContext searchContext = parent.waitUntilLocated(driver, timeoutInSeconds);
if(!driver.elementExistsAt(locator, searchContext) && timeoutInSeconds > 0)
{
try
{
driver.waitUntil(new ElementLocated(locator, searchContext), timeoutInSeconds);
}
catch(TimeoutException e)
{
throw new org.openqa.selenium.NoSuchElementException(new StringDescription()
.appendText("Unable to locate element after timeout.")
.appendText("\nLocator: ").appendValue(locator)
.appendText("\nTimeout: ").appendValue(timeoutInSeconds).appendText(" seconds.")
.toString(), e);
}
}
webElement = searchContext.findElement(locator);
webElementLocated = true;
}
return webElement;
}
public boolean isPresent(AtlassianWebDriver driver, int timeoutForParentInSeconds)
{
return driver.elementExistsAt(this.locator, parent.waitUntilLocated(driver, timeoutForParentInSeconds));
}
}
private static class WebDriverListLocator implements WebDriverLocatable
{
private WebElement webElement = null;
private final By locator;
private final int locatorIndex;
private final WebDriverLocatable parent;
public WebDriverListLocator(WebElement element, By locator, int locatorIndex, WebDriverLocatable parent)
{
this.webElement = element;
this.locatorIndex = locatorIndex;
this.locator = locator;
this.parent = parent;
}
public By getLocator()
{
return null;
}
public WebDriverLocatable getParent()
{
return parent;
}
public SearchContext waitUntilLocated(final AtlassianWebDriver driver, int timeoutInSeconds)
{
if(WebDriverLocators.isStale(webElement))
{
try
{
webElement = waitUntil(queryForElement(driver, TimeUnit.SECONDS.toMillis(timeoutInSeconds)),
notNullValue(WebElement.class));
}
catch (AssertionError notLocated)
{
throw new NoSuchElementException(new StringDescription()
.appendText("Unable to locate element in collection.")
.appendText("\nLocator: ").appendValue(locator)
.appendText("\nLocator Index: ").appendValue(locatorIndex)
.toString());
}
}
return webElement;
}
private TimedQuery<WebElement> queryForElement(final AtlassianWebDriver driver, long timeout) {
return new AbstractTimedQuery<WebElement>(timeout, PollingQuery.DEFAULT_INTERVAL, ExpirationHandler.RETURN_NULL)
{
@Override
protected boolean shouldReturn(WebElement currentEval) {
return true;
}
@Override
protected WebElement currentValue() {
// we want the parent to be located and then the child list to be long enough to contain our index!
if (parent.isPresent(driver, 0)) {
List<WebElement> webElements = parent.waitUntilLocated(driver, 0).findElements(locator);
return locatorIndex < webElements.size() ? webElements.get(locatorIndex) : null;
}
return null;
}
};
}
public boolean isPresent(AtlassianWebDriver driver, int timeoutForParentInSeconds)
{
SearchContext searchContext = parent.waitUntilLocated(driver, timeoutForParentInSeconds);
List<WebElement> webElements = searchContext.findElements(this.locator);
return locatorIndex <= webElements.size() - 1;
}
}
} |
package org.biojava.bio.structure.align.ce;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.biojava.bio.structure.Atom;
import org.biojava.bio.structure.Structure;
import org.biojava.bio.structure.StructureTools;
import org.biojava.bio.structure.align.MultiThreadedDBSearch;
import org.biojava.bio.structure.align.StructureAlignment;
import org.biojava.bio.structure.align.model.AFPChain;
import org.biojava.bio.structure.align.util.AFPAlignmentDisplay;
import org.biojava.bio.structure.align.util.AtomCache;
import org.biojava.bio.structure.align.util.CliTools;
import org.biojava.bio.structure.align.util.ConfigurationException;
import org.biojava.bio.structure.align.util.ResourceManager;
import org.biojava.bio.structure.align.util.UserConfiguration;
import org.biojava.bio.structure.align.xml.AFPChainXMLConverter;
import org.biojava.bio.structure.io.PDBFileReader;
public abstract class AbstractUserArgumentProcessor implements UserArgumentProcessor {
public static String newline = System.getProperty("line.separator");
protected StartupParameters params ;
public static final List<String> mandatoryArgs= new ArrayList<String>();
/** the system property PDB_DIR can be used to configure the
* default location for PDB files.
*/
public static final String PDB_DIR = "PDB_DIR";
protected AbstractUserArgumentProcessor(){
params = new StartupParameters();
}
public abstract StructureAlignment getAlgorithm();
public abstract Object getParameters();
public abstract String getDbSearchLegend();
public void process(String[] argv){
printAboutMe();
List<String> mandatoryArgs = getMandatoryArgs();
for (int i = 0 ; i < argv.length; i++){
String arg = argv[i];
String value = null;
if ( i < argv.length -1)
value = argv[i+1];
// if value starts with - then the arg does not have a value.
if (value != null && value.startsWith("-"))
value = null;
else
i++;
String[] tmp = {arg,value};
//System.out.println(arg + " " + value);
try {
CliTools.configureBean(params, tmp);
} catch (ConfigurationException e){
e.printStackTrace();
if ( mandatoryArgs.contains(arg) ) {
// there must not be a ConfigurationException with mandatory arguments.
return;
} else {
// but there can be with optional ...
}
}
}
if ( params.getPdbFilePath() != null){
System.setProperty(PDB_DIR,params.getPdbFilePath());
}
if ( params.isShowMenu()){
System.err.println("showing menu...");
try {
GuiWrapper.showAlignmentGUI();
} catch (Exception e){
System.err.println(e.getMessage());
e.printStackTrace();
}
}
if ( params.getShowDBresult() != null){
// user wants to view DB search results:
System.err.println("showing DB results...");
try {
GuiWrapper.showDBResults(params);
} catch (Exception e){
System.err.println(e.getMessage());
e.printStackTrace();
}
}
String pdb1 = params.getPdb1();
String file1 = params.getFile1();
if (pdb1 != null || file1 != null){
runPairwise();
}
if ( params.getAlignPairs() != null){
runDBSearch();
}
if ( params.getSearchFile() != null){
runDBSearch();
}
}
public static void printAboutMe() {
try {
ResourceManager about = ResourceManager.getResourceManager("about");
String version = about.getString("project_version");
String build = about.getString("build");
System.out.println("Protein Comparison Tool " + version + " " + build);
} catch (Exception e){
e.printStackTrace();
}
}
private void runDBSearch(){
String pdbFilePath = params.getPdbFilePath();
if ( pdbFilePath == null || pdbFilePath.equals("")){
System.err.println("You did not specify the -pdbFilePath. Can not find PDB files in file system and will assume a temporary location.");
UserConfiguration c = new UserConfiguration();
pdbFilePath = c.getPdbFilePath();
}
AtomCache cache = new AtomCache(pdbFilePath, params.isPdbDirSplit());
String alignPairs = params.getAlignPairs();
String searchFile = params.getSearchFile();
if ( alignPairs == null || alignPairs.equals("")) {
if ( searchFile == null || searchFile.equals("")){
System.err.println("Please specify -alignPairs or -searchFile !");
return;
}
}
String outputFile = params.getOutFile();
if ( outputFile == null || outputFile.equals("")){
System.err.println("Please specify the mandatory argument -outFile!");
return;
}
System.out.println("running DB search with parameters:" + params);
if ( alignPairs != null && ! alignPairs.equals("")) {
runAlignPairs(cache, alignPairs, outputFile);
} else {
// must be a searchFile request...
int useNrCPUs = params.getNrCPU();
runDbSearch(cache,searchFile, outputFile, useNrCPUs, params);
}
}
/** Do a DB search with the input file against representative PDB domains
*
* @param cache
* @param searchFile
* @param outputFile
*/
private void runDbSearch(AtomCache cache, String searchFile,
String outputFile,int useNrCPUs, StartupParameters params) {
System.out.println("will use " + useNrCPUs + " CPUs.");
PDBFileReader reader = new PDBFileReader();
Structure structure1 = null ;
try {
structure1 = reader.getStructure(searchFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.err.println("could not parse as PDB file: " + searchFile);
return;
}
File searchF = new File(searchFile);
String name1 = searchF.getName();
StructureAlignment algorithm = getAlgorithm();
MultiThreadedDBSearch dbSearch = new MultiThreadedDBSearch(name1,
structure1,
outputFile,
algorithm,
useNrCPUs,
true);
dbSearch.run();
}
private void runAlignPairs(AtomCache cache, String alignPairs,
String outputFile) {
try {
File f = new File(alignPairs);
BufferedReader is = new BufferedReader (new InputStreamReader(new FileInputStream(f)));
BufferedWriter out = new BufferedWriter(new FileWriter(outputFile, true));
StructureAlignment algorithm = getAlgorithm();
String header = "# algorithm:" + algorithm.getAlgorithmName();
out.write(header);
out.write(newline);
out.write("#Legend: " + newline );
String legend = getDbSearchLegend();
out.write(legend + newline );
System.out.println(legend);
String line = null;
while ( (line = is.readLine()) != null){
if ( line.startsWith("
continue;
String[] spl = line.split(" ");
if ( spl.length != 2) {
System.err.println("wrongly formattted line. Expected format: 4hhb.A 4hhb.B but found " + line);
continue;
}
String pdb1 = spl[0];
String pdb2 = spl[1];
Structure structure1 = cache.getStructure(pdb1);
Structure structure2 = cache.getStructure(pdb2);
Atom[] ca1;
Atom[] ca2;
ca1 = StructureTools.getAtomCAArray(structure1);
ca2 = StructureTools.getAtomCAArray(structure2);
Object jparams = getParameters();
AFPChain afpChain;
afpChain = algorithm.align(ca1, ca2, jparams);
afpChain.setName1(pdb1);
afpChain.setName2(pdb2);
String result = getDbSearchResult(afpChain);
out.write(result);
System.out.print(result);
checkWriteFile(afpChain,ca1,ca2,true);
}
out.close();
is.close();
} catch(Exception e){
e.printStackTrace();
}
}
private void runPairwise(){
String name1 = params.getPdb1();
String file1 = params.getFile1();
if ( name1 == null && file1 == null){
throw new RuntimeException("You did not specify the -pdb1 or -file1 parameter. Can not find query PDB id for alignment.");
}
if ( file1 == null) {
if ( name1.length() < 4) {
throw new RuntimeException("-pdb1 does not look like a PDB ID. Please specify PDB code or PDB.chainId.");
}
}
String name2 = params.getPdb2();
String file2 = params.getFile2();
if ( name2 == null && file2 == null ){
throw new RuntimeException("You did not specify the -pdb2 or -file2 parameter. Can not find target PDB id for alignment.");
}
if ( file2 == null ){
if ( name2.length() < 4) {
throw new RuntimeException("-pdb2 does not look like a PDB ID. Please specify PDB code or PDB.chainId.");
}
}
// first load two example structures
Structure structure1 = null;
Structure structure2 = null;
String path = params.getPdbFilePath();
if ( file1 == null || file2 == null) {
if ( path == null){
System.err.println("You did not specify the -pdbFilePath parameter. Can not find the PDB files in your file system and assuming a temporary location.");
UserConfiguration c = new UserConfiguration();
path = c.getPdbFilePath();
}
AtomCache cache = new AtomCache(path, params.isPdbDirSplit());
cache.setAutoFetch(params.isAutoFetch());
structure1 = getStructure(cache, name1, file1);
structure2 = getStructure(cache, name2, file2);
} else {
structure1 = getStructure(null, name1, file1);
structure2 = getStructure(null, name2, file2);
}
if ( structure1 == null){
System.err.println("structure 1 is null, can't run alignment.");
return;
}
if ( structure2 == null){
System.err.println("structure 2 is null, can't run alignment.");
return;
}
if ( name1 == null) {
name1 = structure1.getName();
}
if ( name2 == null) {
name2 = structure2.getName();
}
// default: new:
// 1buz - 1ali : time: 8.3s eqr 68 rmsd 3.1 score 161 | time 6.4 eqr 58 rmsd 3.0 scre 168
// 5pti - 1tap : time: 6.2s eqr 48 rmsd 2.67 score 164 | time 5.2 eqr 49 rmsd 2.9 score 151
// 1cdg - 8tim
// 1jbe - 1ord
// 1nbw.A - 1kid
// 1t4y - 1rp5
try {
Atom[] ca1;
Atom[] ca2;
ca1 = StructureTools.getAtomCAArray(structure1);
ca2 = StructureTools.getAtomCAArray(structure2);
StructureAlignment algorithm = getAlgorithm();
Object jparams = getParameters();
AFPChain afpChain;
afpChain = algorithm.align(ca1, ca2, jparams);
afpChain.setName1(name1);
afpChain.setName2(name2);
if ( params.isShow3d()){
if (! GuiWrapper.isGuiModuleInstalled()) {
System.err.println("The biojava-structure-gui module is not installed. Please install!");
} else {
try {
Object jmol = GuiWrapper.display(afpChain,ca1,ca2);
GuiWrapper.showAlignmentImage(afpChain, ca1,ca2,jmol);
} catch (Exception e){
System.err.println(e.getMessage());
e.printStackTrace();
}
//StructureAlignmentJmol jmol = algorithm.display(afpChain,ca1,ca2,hetatms1, nucs1, hetatms2, nucs2);
//String result = afpChain.toFatcat(ca1, ca2);
//String rot = afpChain.toRotMat();
//DisplayAFP.showAlignmentImage(afpChain, ca1,ca2,jmol);
}
}
checkWriteFile(afpChain,ca1, ca2, false);
if ( params.isPrintXML()){
String fatcatXML = AFPChainXMLConverter.toXML(afpChain,ca1,ca2);
System.out.println(fatcatXML);
}
if ( params.isPrintFatCat()) {
// default output is to XML on sysout...
System.out.println(afpChain.toFatcat(ca1, ca2));
}
if ( params. isPrintCE()){
System.out.println(afpChain.toCE(ca1, ca2));
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
/** check if the result should be written to the local file system
*
* @param params2
* @param afpChain
* @param ca1
* @param ca2
*/
private void checkWriteFile( AFPChain afpChain, Atom[] ca1, Atom[] ca2, boolean dbsearch)
throws Exception
{
String output = null;
if ( params.isOutputPDB()){
if (! GuiWrapper.isGuiModuleInstalled()) {
System.err.println("The biojava-structure-gui module is not installed. Please install!");
output = AFPChainXMLConverter.toXML(afpChain,ca1,ca2);
} else {
Structure tmp = AFPAlignmentDisplay.createArtificalStructure(afpChain, ca1, ca2);
output = "TITLE " + afpChain.getAlgorithmName() + " " + afpChain.getVersion() + " ";
output += afpChain.getName1() + " vs. " + afpChain.getName2();
output += newline;
output += tmp.toPDB();
}
} else if ( params.getOutFile() != null) {
// output by default is XML
// write the XML to a file...
output = AFPChainXMLConverter.toXML(afpChain,ca1,ca2);
} else if ( params.getSaveOutputDir() != null){
output = AFPChainXMLConverter.toXML(afpChain,ca1,ca2);
}
// no output requested.
if ( output == null)
return;
String fileName = null;
if ( dbsearch ){
if ( params.getSaveOutputDir() != null) {
fileName = params.getSaveOutputDir();
fileName += getAutoFileName(afpChain);
} else {
fileName = getAutoFileName(afpChain);
}
} else
if ( params.getOutFile() != null) {
fileName = params.getOutFile();
}
if (fileName == null) {
System.err.println("Can't write outputfile. Either provide a filename using -outFile or set -autoOutputFile to true .");
return;
}
//System.out.println("writing results to " + fileName);
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try
{
// Create a new file output stream
out = new FileOutputStream(fileName);
// Connect print stream to the output stream
p = new PrintStream( out );
p.println (output);
p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file " + params.getOutFile());
}
}
private String getAutoFileName(AFPChain afpChain){
String fileName =afpChain.getName1()+"_" + afpChain.getName2()+"_"+afpChain.getAlgorithmName();
if (params.isOutputPDB() )
fileName += ".pdb";
else
fileName += ".xml";
return fileName;
}
private Structure getStructure(AtomCache cache, String name1, String file)
{
PDBFileReader reader = new PDBFileReader();
if ( file != null ){
try {
// check if it is a URL:
try {
URL url = new URL(file);
System.out.println(url);
Structure s = reader.getStructure(url);
return fixStructureName(s,file);
} catch ( Exception e){
System.err.println(e.getMessage());
}
File f= new File(file);
System.out.println("file from local " + f.getAbsolutePath());
Structure s= reader.getStructure(f);
return fixStructureName(s, file);
} catch (Exception e){
System.err.println("general exception:" + e.getMessage());
System.err.println("unable to load structure from " + file);
return null;
}
}
try {
Structure s = cache.getStructure(name1);
return s;
} catch ( Exception e){
System.err.println(e.getMessage());
System.err.println("unable to load structure from dir: " + cache.getPath() + "/"+ name1);
return null;
}
}
/** apply a number of rules to fix the name of the structure if it did not get set during loading.
*
* @param s
* @param file
* @return
*/
private Structure fixStructureName(Structure s, String file) {
if ( s.getName() != null && (! s.getName().equals("")))
return s;
s.setName(s.getPDBCode());
if ( s.getName() == null || s.getName().equals("")){
File f = new File(file);
s.setName(f.getName());
}
return s;
}
public List<String> getMandatoryArgs() {
return mandatoryArgs;
}
public String getDbSearchResult(AFPChain afpChain){
return afpChain.toDBSearchResult();
}
} |
package gov.nih.nci.cabig.caaers.security;
import junit.framework.TestCase;
public class SecurityObjectTranslatorTest extends TestCase {
SecurityObjectTranslator t = new SecurityObjectTranslator();
public void testFromCaAERSToCSM() {
assertEquals("HealthcareSite", t.fromCaAERSToCSM("gov.nih.nci.cabig.caaers.domain.Organization"));
assertEquals("HealthcareSite", t.fromCaAERSToCSM("gov.nih.nci.cabig.caaers.domain.LocalOrganization"));
assertEquals("HealthcareSite", t.fromCaAERSToCSM("gov.nih.nci.cabig.caaers.domain.RemoteOrganization"));
assertEquals("Study", t.fromCaAERSToCSM("gov.nih.nci.cabig.caaers.domain.Study"));
assertEquals("Study", t.fromCaAERSToCSM("gov.nih.nci.cabig.caaers.domain.LocalStudy"));
assertEquals("Study", t.fromCaAERSToCSM("gov.nih.nci.cabig.caaers.domain.RemoteStudy"));
assertEquals("anion", t.fromCaAERSToCSM("anion"));
}
public void testFromCSMToCaAERS() {
assertEquals("gov.nih.nci.cabig.caaers.domain.Organization", t.fromCSMToCaAERS("HealthcareSite"));
assertEquals("gov.nih.nci.cabig.caaers.domain.Study", t.fromCSMToCaAERS("Study"));
assertEquals("cation", t.fromCSMToCaAERS("cation"));
}
} |
package io.jxcore.node;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
import org.thaliproject.p2p.btconnectorlib.PeerProperties;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
/**
* A thread for outgoing Bluetooth connections.
*/
class OutgoingSocketThread extends SocketThreadBase {
private ServerSocket mServerSocket = null;
private int mListeningOnPortNumber = ConnectionHelper.NO_PORT_NUMBER;
//TODO remove it. Just for logging and test purposes
private ConnectionData connectionData = new ConnectionData(new PeerProperties(), false);
/**
* Constructor for test purposes.
*
* @param bluetoothSocket The Bluetooth socket.
* @param listener The listener.
* @throws IOException Thrown, if the constructor of the base class, SocketThreadBase, fails.
*/
public OutgoingSocketThread(BluetoothSocket bluetoothSocket, ConnectionData connectionData, Listener listener)
throws IOException {
super(bluetoothSocket, listener);
this.connectionData = connectionData;
mTag = OutgoingSocketThread.class.getName();
}
/**
* Constructor.
*
* @param bluetoothSocket The Bluetooth socket.
* @param listener The listener.
* @param inputStream The InputStream.
* @param outputStream The OutputStream.
* @throws IOException Thrown, if the constructor of the base class, SocketThreadBase, fails.
*/
public OutgoingSocketThread(BluetoothSocket bluetoothSocket, Listener listener,
InputStream inputStream, OutputStream outputStream)
throws IOException {
super(bluetoothSocket, listener, inputStream, outputStream);
mTag = OutgoingSocketThread.class.getName();
}
public int getListeningOnPortNumber() {
return mListeningOnPortNumber;
}
/**
* From Thread.
*/
@Override
public void run() {
Log.d(mTag, "Entering thread (ID: " + getId() + "). Connection data = " + connectionData.toString());
mIsClosing = false;
try {
mServerSocket = new ServerSocket(0);
Log.d(mTag, "Server socket local port: " + mServerSocket.getLocalPort());
} catch (IOException e) {
Log.e(mTag, "Failed to create a server socket instance: " + e.getMessage(), e);
mServerSocket = null;
mListener.onDisconnected(this, "Failed to create a server socket instance: " + e.getMessage());
}
if (mServerSocket != null) {
InputStream tempInputStream = null;
OutputStream tempOutputStream = null;
boolean localStreamsCreatedSuccessfully = false;
try {
Log.i(mTag, "Now accepting connections...");
if (mListener != null) {
mListeningOnPortNumber = mServerSocket.getLocalPort();
mListener.onListeningForIncomingConnections(mListeningOnPortNumber);
}
mLocalhostSocket = mServerSocket.accept(); // Blocking call
configureSocket();
Log.i(mTag, "Incoming data from address: " + getLocalHostAddressAsString()
+ ", port: " + mServerSocket.getLocalPort());
tempInputStream = mLocalhostSocket.getInputStream();
tempOutputStream = mLocalhostSocket.getOutputStream();
localStreamsCreatedSuccessfully = true;
} catch (IOException e) {
if (!mIsClosing) {
String errorMessage = "Failed to create local streams: " + e.getMessage();
Log.e(mTag, errorMessage, e);
mListener.onDisconnected(this, errorMessage);
}
}
if (localStreamsCreatedSuccessfully) {
Log.d(mTag, "Setting local streams and starting stream copying threads...");
mLocalInputStream = tempInputStream;
mLocalOutputStream = tempOutputStream;
startStreamCopyingThreads(connectionData);
}
}
if (mServerSocket != null) {
try {
mServerSocket.close();
} catch (IOException e) {
Log.e(mTag, "Failed to close the server socket: " + e.getMessage(), e);
}
mServerSocket = null;
}
Log.d(mTag, "Exiting thread (ID: " + getId() + "). Connection data = " + connectionData.toString());
}
/**
* Closes all the streams and sockets.
*/
public synchronized void close() {
Log.i(mTag, "close (thread ID: " + getId() + ")");
super.close();
if (mServerSocket != null) {
try {
mServerSocket.close();
} catch (IOException e) {
Log.e(mTag, "Failed to close the server socket: " + e.getMessage(), e);
}
mServerSocket = null;
}
}
} |
package be.kuleuven.cs.distrinet.jnome.core.type;
import java.util.Collections;
import java.util.List;
import org.aikodi.chameleon.core.element.Element;
import org.aikodi.chameleon.core.factory.Factory;
import org.aikodi.chameleon.core.lookup.DeclarationSelector;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.lookup.SelectionResult;
import org.aikodi.chameleon.core.reference.NameReference;
import org.aikodi.chameleon.core.tag.TagImpl;
import org.aikodi.chameleon.exception.ChameleonProgrammerException;
import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage;
import org.aikodi.chameleon.oo.member.Member;
import org.aikodi.chameleon.oo.method.Method;
import org.aikodi.chameleon.oo.type.ClassWithBody;
import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.chameleon.oo.type.TypeElement;
import org.aikodi.chameleon.oo.type.TypeFixer;
import org.aikodi.chameleon.oo.type.TypeReference;
import org.aikodi.chameleon.oo.type.generics.EqualityTypeArgument;
import org.aikodi.chameleon.oo.type.generics.FormalTypeParameter;
import org.aikodi.chameleon.oo.type.generics.TypeParameter;
import org.aikodi.chameleon.oo.type.inheritance.InheritanceRelation;
import org.aikodi.chameleon.oo.type.inheritance.SubtypeRelation;
import org.aikodi.chameleon.oo.variable.FormalParameter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import be.kuleuven.cs.distrinet.jnome.core.language.Java7;
import be.kuleuven.cs.distrinet.rejuse.association.SingleAssociation;
import be.kuleuven.cs.distrinet.rejuse.logic.ternary.Ternary;
public class RawType extends ClassWithBody implements JavaType {
private ImmutableList<Member> _implicitMembers;
@Override
public List<Member> implicitMembers() {
return _implicitMembers;
}
@Override
public <D extends Member> List<? extends SelectionResult> implicitMembers(DeclarationSelector<D> selector) throws LookupException {
return selector.selection(_implicitMembers);
}
/**
* Create a new raw type. The type parameters, super class and interface references,
* and all members will be erased according to the definitions in the JLS.
*/
public RawType(Type original) {
// first copy everything
super(original.name());
copyContents(original, true);
// copyImplicitInheritanceRelations(original);
copyImplicitMembers(original);
_baseType = original;
setUniParent(original.parent());
setOrigin(original);
// then erase everything.
// 1) inheritance relations
eraseInheritanceRelations();
// 2) type parameters
eraseTypeParameters(parameters(TypeParameter.class));
// 3) members
eraseMethods();
// 4) member types
makeDescendantTypesRaw();
}
/**
* @{inheritDoc}
*/
@Override
public void setUniParent(Element parent) {
super.setUniParent(parent);
}
@Override
public List<InheritanceRelation> implicitNonMemberInheritanceRelations() {
if(explicitNonMemberInheritanceRelations().isEmpty() && (! "Object".equals(name())) && (! getFullyQualifiedName().equals("java.lang.Object"))) {
TypeReference objectTypeReference = language(ObjectOrientedLanguage.class).createTypeReference("java.lang.Object");
InheritanceRelation relation = new SubtypeRelation(objectTypeReference);
relation.setUniParent(this);
relation.setMetadata(new TagImpl(), IMPLICIT_CHILD);
List<InheritanceRelation> result = ImmutableList.of(relation);
return result;
} else {
return Collections.EMPTY_LIST;
}
}
@Override
public boolean hasInheritanceRelation(InheritanceRelation relation) throws LookupException {
return super.hasInheritanceRelation(relation) || relation.hasMetadata(IMPLICIT_CHILD);
}
public final static String IMPLICIT_CHILD = "IMPLICIT CHILD";
// private void copyImplicitInheritanceRelations(Type original) {
// for(InheritanceRelation i: original.implicitNonMemberInheritanceRelations()) {
// InheritanceRelation clone = i.clone();
// addInheritanceRelation(clone);
private RawType(Type original, boolean useless) {
super(original.name());
copyContents(original, true);
copyImplicitMembers(original);
_baseType = original;
setOrigin(original);
setUniParent(original.parent());
// 1) inheritance relations
eraseInheritanceRelations();
// 2) type parameters
eraseTypeParameters(parameters(TypeParameter.class));
// 3) members
eraseMethods();
// 4) member types
setUniParent(null);
}
private void copyImplicitMembers(Type original) {
Builder<Member> builder = ImmutableList.<Member>builder();
List<Member> implicits = original.implicitMembers();
for(Member m: implicits) {
Member clone = clone(m);
clone.setUniParent(body());
builder.add(clone);
}
_implicitMembers = builder.build();
}
private void makeDescendantTypesRaw() {
List<Type> childTypes = directlyDeclaredElements(Type.class);
Java7 language = language(Java7.class);
for(Type type:childTypes) {
if(type.is(language.INSTANCE) == Ternary.TRUE) {
// create raw type that does not erase anything
RawType raw = new RawType((Type) type.origin(),false);
SingleAssociation parentLink = type.parentLink();
parentLink.getOtherRelation().replace(parentLink, raw.parentLink());
raw.makeDescendantTypesRaw();
}
}
}
private Type _baseType;
@Override
public Type baseType() {
return _baseType;
}
private void eraseMethods() {
for(TypeElement element: directlyDeclaredElements()) {
if(element instanceof Method) {
Method method = (Method)element;
eraseTypeParameters(method.typeParameters());
for(FormalParameter param: method.formalParameters()) {
JavaTypeReference typeReference = (JavaTypeReference) param.getTypeReference();
JavaTypeReference erasedReference = typeReference.erasedReference();
param.setTypeReference(erasedReference);
}
// erase return type reference
method.setReturnTypeReference(((JavaTypeReference)method.returnTypeReference()).erasedReference());
}
}
}
protected void eraseInheritanceRelations() {
//FIXME Why aren't member inheritance relations such as subobjects erased?
// It probably has a reason but I was so stupid not to document it.
for(SubtypeRelation relation: nonMemberInheritanceRelations(SubtypeRelation.class)) {
JavaTypeReference superClassReference = (JavaTypeReference) relation.superClassReference();
JavaTypeReference erasedReference = superClassReference.erasedReference();
relation.setSuperClassReference(erasedReference);
}
}
protected void eraseTypeParameters(List<TypeParameter> parameters) {
Java7 language = language(Java7.class);
for(TypeParameter typeParameter: parameters) {
FormalTypeParameter param = (FormalTypeParameter) typeParameter;
JavaTypeReference upperBoundReference = (JavaTypeReference) param.upperBoundReference();
JavaTypeReference erased = upperBoundReference.erasedReference();
EqualityTypeArgument argument = language.createEqualityTypeArgument(erased);
ErasedTypeParameter newParameter = new ErasedTypeParameter(typeParameter.name(),argument);
argument.setUniParent(newParameter);
SingleAssociation parentLink = typeParameter.parentLink();
parentLink.getOtherRelation().replace(parentLink, newParameter.parentLink());
}
}
@Override
protected RawType cloneSelf() {
return new RawType(baseType());
}
public boolean uniSameAs(Element otherType) throws LookupException {
return (otherType instanceof RawType) && uniSameAs(((RawType)otherType).baseType(), new TypeFixer());
}
@Override
public int hashCode() {
return 87937+baseType().hashCode();
}
public boolean convertibleThroughUncheckedConversionAndSubtyping(Type second) throws LookupException {
return superTypeJudge().get(second) != null;
}
/**
* The erasure of a raw type is the raw type itself.
*/
/*@
@ public behavior
@
@ post \result == this;
@*/
public Type erasure() {
return this;
}
@Override
public boolean uniSameAs(Type otherType, TypeFixer trace) throws LookupException {
return (otherType instanceof RawType) && (baseType().sameAs(((RawType)otherType).baseType(), trace));
}
@Override
public boolean uniSupertypeOf(Type other, TypeFixer trace) throws LookupException {
return other.superTypeJudge().get(this) != null;
}
} |
package ch.unizh.ini.jaer.projects.minliu;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.util.Arrays;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GL2ES3;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.util.awt.TextRenderer;
import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow;
import com.jogamp.opengl.GLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.stream.IntStream;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventio.AEInputStream;
import net.sf.jaer.eventprocessing.TimeLimiter;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.graphics.ImageDisplay;
import net.sf.jaer.graphics.ImageDisplay.Legend;
import net.sf.jaer.util.DrawGL;
import net.sf.jaer.util.EngineeringFormat;
import net.sf.jaer.util.TobiLogger;
import net.sf.jaer.util.filter.LowpassFilter;
/**
* Uses patch matching to measureTT local optical flow. <b>Not</b> gradient
* based, but rather matches local features backwards in time.
*
* @author Tobi and Min, Jan 2016
*/
@Description("Computes optical flow with vector direction using block matching")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class PatchMatchFlow extends AbstractMotionFlow implements Observer, FrameAnnotater {
/* LDSP is Large Diamond Search Pattern, and SDSP mens Small Diamond Search Pattern.
LDSP has 9 points and SDSP consists of 5 points.
*/
private static final int LDSP[][] = {{0, -2}, {-1, -1}, {1, -1}, {-2, 0}, {0, 0},
{2, 0}, {-1, 1}, {1, 1}, {0, 2}};
private static final int SDSP[][] = {{0, -1}, {-1, 0}, {0, 0}, {1, 0}, {0, 1}};
// private int[][][] histograms = null;
private int numSlices = 3; //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d
volatile private int numScales = getInt("numScales", 3); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d
private String scalesToCompute = getString("scalesToCompute", ""); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d
private Integer[] scalesToComputeArray = null; // holds array of scales to actually compute, for debugging
private int[] scaleResultCounts = new int[numScales]; // holds counts at each scale for min SAD results
/**
* The computed average possible match distance from 0 motion
*/
protected float avgPossibleMatchDistance;
private static final int MIN_SLICE_EVENT_COUNT_FULL_FRAME = 1000;
private static final int MAX_SLICE_EVENT_COUNT_FULL_FRAME = 1000000;
// private int sx, sy;
private int currentSliceIdx = 0; // the slice we are currently filling with events
/**
* time slice 2d histograms of (maybe signed) event counts slices = new
* byte[numSlices][numScales][subSizeX][subSizeY] [slice][scale][x][y]
*/
private byte[][][][] slices = null;
private float[] sliceSummedSADValues = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration
private int[] sliceSummedSADCounts = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration
private int[] sliceStartTimeUs; // holds the time interval between reference slice and this slice
private int[] sliceEndTimeUs; // holds the time interval between reference slice and this slice
private byte[][][] currentSlice;
private SADResult lastGoodSadResult = new SADResult(0, 0, 0, 0); // used for consistency check
private int blockDimension = getInt("blockDimension", 23);
// private float cost = getFloat("cost", 0.001f);
private float maxAllowedSadDistance = getFloat("maxAllowedSadDistance", .5f);
private float validPixOccupancy = getFloat("validPixOccupancy", 0.01f); // threshold for valid pixel percent for one block
private float weightDistance = getFloat("weightDistance", 0.95f); // confidence value consists of the distance and the dispersion, this value set the distance value
private static final int MAX_SKIP_COUNT = 1000;
private int skipProcessingEventsCount = getInt("skipProcessingEventsCount", 0); // skip this many events for processing (but not for accumulating to bitmaps)
private int skipCounter = 0;
private boolean adaptiveEventSkipping = getBoolean("adaptiveEventSkipping", true);
private float skipChangeFactor = (float) Math.sqrt(2); // by what factor to change the skip count if too slow or too fast
private boolean outputSearchErrorInfo = false; // make user choose this slow down every time
private boolean adaptiveSliceDuration = getBoolean("adaptiveSliceDuration", true);
private boolean adaptiveSliceDurationLogging = false; // for debugging and analyzing control of slice event number/duration
private TobiLogger adaptiveSliceDurationLogger = null;
private int adaptiveSliceDurationPacketCount = 0;
private boolean useSubsampling = getBoolean("useSubsampling", false);
private int adaptiveSliceDurationMinVectorsToControl = getInt("adaptiveSliceDurationMinVectorsToControl", 10);
private boolean showSliceBitMap = false; // Display the bitmaps
private float adapativeSliceDurationProportionalErrorGain = getFloat("adapativeSliceDurationProportionalErrorGain", 0.05f); // factor by which an error signal on match distance changes slice duration
private boolean adapativeSliceDurationUseProportionalControl = getBoolean("adapativeSliceDurationUseProportionalControl", false);
private int processingTimeLimitMs = getInt("processingTimeLimitMs", 100); // time limit for processing packet in ms to process OF events (events still accumulate). Overrides the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events.
private int sliceMaxValue = getInt("sliceMaxValue", 7);
private boolean rectifyPolarties = getBoolean("rectifyPolarties", false);
private TimeLimiter timeLimiter = new TimeLimiter(); // private instance used to accumulate events to slices even if packet has timed out
// results histogram for each packet
// private int ANGLE_HISTOGRAM_COUNT = 16;
// private int[] resultAngleHistogram = new int[ANGLE_HISTOGRAM_COUNT + 1];
private int[][] resultHistogram = null;
// private int resultAngleHistogramCount = 0, resultAngleHistogramMax = 0;
private int resultHistogramCount;
private volatile float avgMatchDistance = 0; // stores average match distance for rendering it
private float histStdDev = 0, lastHistStdDev = 0;
private float FSCnt = 0, DSCorrectCnt = 0;
float DSAverageNum = 0, DSAveError[] = {0, 0}; // Evaluate DS cost average number and the error.
// private float lastErrSign = Math.signum(1);
// private final String outputFilename;
private int sliceDeltaT; // The time difference between two slices used for velocity caluction. For constantDuration, this one is equal to the duration. For constantEventNumber, this value will change.
private int MIN_SLICE_DURATION_US = 100;
private int MAX_SLICE_DURATION_US = 300000;
private boolean enableImuTimesliceLogging = false;
private TobiLogger imuTimesliceLogger = null;
private volatile boolean resetOFHistogramFlag; // signals to reset the OF histogram after it is rendered
public enum PatchCompareMethod {
/*JaccardDistance,*/ /*HammingDistance*/
SAD/*, EventSqeDistance*/
};
private PatchCompareMethod patchCompareMethod = null;
public enum SearchMethod {
FullSearch, DiamondSearch, CrossDiamondSearch
};
private SearchMethod searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.DiamondSearch.toString()));
private int sliceDurationUs = getInt("sliceDurationUs", 20000);
private int sliceEventCount = getInt("sliceEventCount", 1000);
private boolean rewindFlg = false; // The flag to indicate the rewind event.
private boolean displayResultHistogram = getBoolean("displayResultHistogram", true);
public enum SliceMethod {
ConstantDuration, ConstantEventNumber, AreaEventNumber, ConstantIntegratedFlow
};
private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.AreaEventNumber.toString()));
// counting events into subsampled areas, when count exceeds the threshold in any area, the slices are rotated
private int areaEventNumberSubsampling = getInt("areaEventNumberSubsampling", 5);
private int[][] areaCounts = null;
private int numAreas = 1;
private boolean areaCountExceeded = false;
// nongreedy flow evaluation
// the entire scene is subdivided into regions, and a bitmap of these regions distributed flow computation more fairly
// by only servicing a region when sufficient fraction of other regions have been serviced first
private boolean nonGreedyFlowComputingEnabled = getBoolean("nonGreedyFlowComputingEnabled", false);
private boolean[][] nonGreedyRegions = null;
private int nonGreedyRegionsNumberOfRegions, nonGreedyRegionsCount;
/**
* This fraction of the regions must be serviced for computing flow before
* we reset the nonGreedyRegions map
*/
private float nonGreedyFractionToBeServiced = getFloat("nonGreedyFractionToBeServiced", .5f);
// Print scale count's statics
private boolean printScaleCntStatEnabled = getBoolean("printScaleCntStatEnabled", false);
// timers and flags for showing filter properties temporarily
private final int SHOW_STUFF_DURATION_MS = 4000;
private volatile TimerTask stopShowingStuffTask = null;
private boolean showBlockSizeAndSearchAreaTemporarily = false;
private volatile boolean showAreaCountAreasTemporarily = false;
private int eventCounter = 0;
private int sliceLastTs = Integer.MAX_VALUE;
private ImageDisplay sliceBitmapImageDisplay; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities
private JFrame sliceBitMapFrame = null;
private Legend sliceBitmapLegend;
/**
* A PropertyChangeEvent with this value is fired when the slices has been
* rotated. The oldValue is t-2d slice. The newValue is the t-d slice.
*/
public static final String EVENT_NEW_SLICES = "eventNewSlices";
TobiLogger sadValueLogger = new TobiLogger("sadvalues", "sadvalue,scale"); // TODO debug
public PatchMatchFlow(AEChip chip) {
super(chip);
setSliceDurationUs(getSliceDurationUs()); // 40ms is good for the start of the slice duration adatative since 4ms is too fast and 500ms is too slow.
setDefaultScalesToCompute();
// // Save the result to the file
// Format formatter = new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss");
// // Instantiate a Date object
// Date date = new Date();
// Log file for the OF distribution's statistics
// outputFilename = "PMF_HistStdDev" + formatter.format(date) + ".txt";
String patchTT = "0a: Block matching";
// String eventSqeMatching = "Event squence matching";
// String preProcess = "Denoise";
String metricConfid = "Confidence of current metric";
try {
patchCompareMethod = PatchCompareMethod.valueOf(getString("patchCompareMethod", PatchCompareMethod.SAD.toString()));
} catch (IllegalArgumentException e) {
patchCompareMethod = PatchCompareMethod.SAD;
}
chip.addObserver(this); // to allocate memory once chip size is known
setPropertyTooltip(metricConfid, "maxAllowedSadDistance", "<html>SAD distance threshold for rejecting unresonable block matching result; <br> events with SAD distance larger than this value are rejected. <p>Lower value means it is harder to accept the event.");
setPropertyTooltip(metricConfid, "validPixOccupancy", "<html>Threshold for valid pixel percent for each block; Range from 0 to 1. <p>If either matching block is less occupied than this fraction, no motion vector will be calculated.");
setPropertyTooltip(metricConfid, "weightDistance", "<html>The confidence value consists of the distance and the dispersion; <br>weightDistance sets the weighting of the distance value compared with the dispersion value; Range from 0 to 1. <p>To count only e.g. hamming distance, set weighting to 1. <p> To count only dispersion, set to 0.");
setPropertyTooltip(patchTT, "blockDimension", "linear dimenion of patches to match, in pixels");
setPropertyTooltip(patchTT, "searchDistance", "search distance for matching patches, in pixels");
setPropertyTooltip(patchTT, "patchCompareMethod", "method to compare two patches; SAD=sum of absolute differences, HammingDistance is same as SAD for binary bitmaps");
setPropertyTooltip(patchTT, "searchMethod", "method to search patches");
setPropertyTooltip(patchTT, "sliceDurationUs", "duration of bitmaps in us, also called sample interval, when ConstantDuration method is used");
setPropertyTooltip(patchTT, "sliceEventCount", "number of events collected to fill a slice, when ConstantEventNumber method is used");
setPropertyTooltip(patchTT, "sliceMethod", "<html>Method for determining time slice duration for block matching<ul>"
+ "<li>ConstantDuration: slices are fixed time duration"
+ "<li>ConstantEventNumber: slices are fixed event number"
+ "<li>AreaEventNumber: slices are fixed event number in any subsampled area defined by areaEventNumberSubsampling"
+ "<li>ConstantIntegratedFlow: slices are rotated when average speeds times delta time exceeds half the search distance");
setPropertyTooltip(patchTT, "areaEventNumberSubsampling", "<html>how to subsample total area to count events per unit subsampling blocks for AreaEventNumber method. <p>For example, if areaEventNumberSubsampling=5, <br> then events falling into 32x32 blocks of pixels are counted <br>to determine when they exceed sliceEventCount to make new slice");
setPropertyTooltip(patchTT, "adapativeSliceDurationProportionalErrorGain", "gain for proporportional change of duration or slice event number. typically 0.05f for bang-bang, and 0.5f for proportional control");
setPropertyTooltip(patchTT, "adapativeSliceDurationUseProportionalControl", "If true, then use proportional error control. If false, use bang-bang control with sign of match distance error");
setPropertyTooltip(patchTT, "skipProcessingEventsCount", "skip this many events for processing (but not for accumulating to bitmaps)");
setPropertyTooltip(patchTT, "adaptiveEventSkipping", "enables adaptive event skipping depending on free time left in AEViewer animation loop");
setPropertyTooltip(patchTT, "adaptiveSliceDuration", "<html>Enables adaptive slice duration using feedback control, <br> based on average match search distance compared with total search distance. <p>If the match distance is too small, increaes duration or event count, and if too far, decreases duration or event count.<p>If using <i>AreaEventNumber</i> slice rotation method, don't increase count if actual duration is already longer than <i>sliceDurationUs</i>");
setPropertyTooltip(patchTT, "nonGreedyFlowComputingEnabled", "<html>Enables fairer distribution of computing flow by areas; an area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use <i>processingTimeLimitMs</i> to ensure minimum frame rate");
setPropertyTooltip(patchTT, "nonGreedyFractionToBeServiced", "An area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use the timeLimiter to ensure minimum frame rate");
setPropertyTooltip(patchTT, "useSubsampling", "<html>Enables using both full and subsampled block matching; <p>when using adaptiveSliceDuration, enables adaptive slice duration using feedback controlusing difference between full and subsampled resolution slice matching");
setPropertyTooltip(patchTT, "adaptiveSliceDurationMinVectorsToControl", "<html>Min flow vectors computed in packet to control slice duration, increase to reject control during idle periods");
setPropertyTooltip(patchTT, "processingTimeLimitMs", "<html>time limit for processing packet in ms to process OF events (events still accumulate). <br> Set to 0 to disable. <p>Alternative to the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events");
setPropertyTooltip(patchTT, "outputSearchErrorInfo", "enables displaying the search method error information");
setPropertyTooltip(patchTT, "outlierMotionFilteringEnabled", "(Currently has no effect) discards first optical flow event that points in opposite direction as previous one (dot product is negative)");
setPropertyTooltip(patchTT, "numSlices", "<html>Number of bitmaps to use. <p>At least 3: 1 to collect on, and two more to match on. <br>If >3, then best match is found between last slice reference block and all previous slices.");
setPropertyTooltip(patchTT, "numScales", "<html>Number of scales to search over for minimum SAD value; 1 for single full resolution scale, 2 for full + 2x2 subsampling, etc.");
setPropertyTooltip(patchTT, "sliceMaxValue", "<html> the maximum value used to represent each pixel in the time slice:<br>1 for binary or signed binary slice, (in conjunction with rectifyEventPolarities==true), etc, <br>up to 127 by these byte values");
setPropertyTooltip(patchTT, "rectifyPolarties", "<html> whether to rectify ON and OFF polarities to unsigned counts; true ignores polarity for block matching, false uses polarity with sliceNumBits>1");
setPropertyTooltip(patchTT, "scalesToCompute", "Scales to compute, e.g. 1,2; blank for all scales. 0 is full resolution, 1 is subsampled 2x2, etc");
setPropertyTooltip(patchTT, "showSlice", "Scales to compute, e.g. 1,2; blank for all scales. 0 is full resolution, 1 is subsampled 2x2, etc");
setPropertyTooltip(patchTT, "defaults", "Sets reasonable defaults");
setPropertyTooltip(patchTT, "enableImuTimesliceLogging", "Logs IMU and rate gyro");
String patchDispTT = "0b: Block matching display";
setPropertyTooltip(patchDispTT, "showSliceBitMap", "enables displaying the slices' bitmap");
setPropertyTooltip(patchDispTT, "ppsScale", "scale of pixels per second to draw local motion vectors; global vectors are scaled up by an additional factor of " + GLOBAL_MOTION_DRAWING_SCALE);
setPropertyTooltip(patchDispTT, "displayOutputVectors", "display the output motion vectors or not");
setPropertyTooltip(patchDispTT, "displayResultHistogram", "display the output motion vectors histogram to show disribution of results for each packet. Only implemented for HammingDistance");
setPropertyTooltip(patchDispTT, "printScaleCntStatEnabled", "enables printing the statics of scale counts");
getSupport().addPropertyChangeListener(AEViewer.EVENT_TIMESTAMPS_RESET, this);
getSupport().addPropertyChangeListener(AEViewer.EVENT_FILEOPEN, this);
getSupport().addPropertyChangeListener(AEInputStream.EVENT_REWOUND, this);
getSupport().addPropertyChangeListener(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP, this);
computeAveragePossibleMatchDistance();
}
// TODO debug
public void doStartLogSadValues() {
sadValueLogger.setEnabled(true);
}
// TODO debug
public void doStopLogSadValues() {
sadValueLogger.setEnabled(false);
}
@Override
synchronized public EventPacket filterPacket(EventPacket in) {
if (cameraCalibration != null && cameraCalibration.isFilterEnabled()) {
in = cameraCalibration.filterPacket(in);
}
setupFilter(in);
checkArrays();
if (processingTimeLimitMs > 0) {
timeLimiter.setTimeLimitMs(processingTimeLimitMs);
timeLimiter.restart();
} else {
timeLimiter.setEnabled(false);
}
int minDistScale = 0;
// following awkward block needed to deal with DVS/DAVIS and IMU/APS events
// block STARTS
Iterator i = null;
if (in instanceof ApsDvsEventPacket) {
i = ((ApsDvsEventPacket) in).fullIterator();
} else {
i = ((EventPacket) in).inputIterator();
}
nSkipped = 0;
nProcessed = 0;
while (i.hasNext()) {
Object o = i.next();
if (o == null) {
log.warning("null event passed in, returning input packet");
return in;
}
if ((o instanceof ApsDvsEvent) && ((ApsDvsEvent) o).isApsData()) {
continue;
}
PolarityEvent ein = (PolarityEvent) o;
if (!extractEventInfo(o)) {
continue;
}
if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) {
if (imuFlowEstimator.calculateImuFlow(o)) {
continue;
}
}
// block ENDS
if (xyFilter()) {
continue;
}
countIn++;
// compute flow
SADResult result = null;
float[] sadVals = new float[numScales]; // TODO debug
switch (patchCompareMethod) {
case SAD:
boolean rotated = maybeRotateSlices();
if (rotated) {
adaptSliceDuration();
setResetOFHistogramFlag();
}
// if (ein.x >= subSizeX || ein.y > subSizeY) {
// log.warning("event out of range");
// continue;
if (!accumulateEvent(ein)) { // maybe skip events here
break;
}
SADResult sliceResult;
minDistScale = 0;
// Sorts scalesToComputeArray[] in descending order
Arrays.sort(scalesToComputeArray, Collections.reverseOrder());
for (int scale : scalesToComputeArray) {
if (scale >= numScales) {
log.warning("scale " + scale + " is out of range of " + numScales + "; fix scalesToCompute for example by clearing it");
break;
}
int dx_init = ((result != null ) && !isNotSufficientlyAccurate(result)) ? ( result.dx >> scale ) : 0;
int dy_init = ((result != null ) && !isNotSufficientlyAccurate(result)) ? ( result.dx >> scale ) : 0;
// dx_init = 0;
// dy_init = 0;
// The reason why we inverse dx_init, dy_init i is the offset is pointing from previous slice to current slice.
// The dx_init, dy_init are from the corse scale's result, and it is used as the finer scale's initial guess.
sliceResult = minSADDistance(ein.x, ein.y, -dx_init, -dy_init, slices[sliceIndex(1)], slices[sliceIndex(2)], scale); // from ref slice to past slice k+1, using scale 0,1,....
// sliceSummedSADValues[sliceIndex(scale + 2)] += sliceResult.sadValue; // accumulate SAD for this past slice
// sliceSummedSADCounts[sliceIndex(scale + 2)]++; // accumulate SAD count for this past slice
// sliceSummedSADValues should end up filling 2 values for 4 slices
if ((result == null) || (sliceResult.sadValue < result.sadValue)) {
result = sliceResult; // result holds the overall min sad result
minDistScale = scale;
}
sadVals[scale] = sliceResult.sadValue; // TODO debug
}
float dt = (sliceDeltaTimeUs(2) * 1e-6f);
if (result != null) {
result.vx = result.dx / dt; // hack, convert to pix/second
result.vy = result.dy / dt; // TODO clean up, make time for each slice, since could be different when const num events
}
break;
// case JaccardDistance:
// maybeRotateSlices();
// if (!accumulateEvent(in)) {
// break;
// result = minJaccardDistance(x, y, bitmaps[sliceIndex(2)], bitmaps[sliceIndex(1)]);
// float dtj=(sliceDeltaTimeUs(2) * 1e-6f);
// result.dx = result.dx / dtj;
// result.dy = result.dy / dtj;
// break;
}
if (result == null || result.sadValue == Float.MAX_VALUE) {
continue; // maybe some property change caused this
}
// reject values that are unreasonable
if (isNotSufficientlyAccurate(result)) {
continue;
}
scaleResultCounts[minDistScale]++;
vx = result.vx;
vy = result.vy;
v = (float) Math.sqrt((vx * vx) + (vy * vy));
// TODO debug
StringBuilder sadValsString = new StringBuilder();
for (int k = 0; k < sadVals.length - 1; k++) {
sadValsString.append(String.format("%f,", sadVals[k]));
}
sadValsString.append(String.format("%f", sadVals[sadVals.length - 1])); // very awkward to prevent trailing ,
if (sadValueLogger.isEnabled()) { // TODO debug
sadValueLogger.log(sadValsString.toString());
}
if (showSliceBitMap) {
// TODO danger, drawing outside AWT thread
drawMatching(result, ein, slices); // ein.x >> result.scale, ein.y >> result.scale, (int) result.dx >> result.scale, (int) result.dy >> result.scale, slices[sliceIndex(1)][result.scale], slices[sliceIndex(2)][result.scale], result.scale);
}
// if (filterOutInconsistentEvent(result)) {
// continue;
if (resultHistogram != null) {
resultHistogram[result.xidx][result.yidx]++;
resultHistogramCount++;
}
// if (result.dx != 0 || result.dy != 0) {
// final int bin = (int) Math.round(ANGLE_HISTOGRAM_COUNT * (Math.atan2(result.dy, result.dx) + Math.PI) / (2 * Math.PI));
// int v = ++resultAngleHistogram[bin];
// resultAngleHistogramCount++;
// if (v > resultAngleHistogramMax) {
// resultAngleHistogramMax = v;
processGoodEvent();
lastGoodSadResult.set(result);
}
motionFlowStatistics.updatePacket(countIn, countOut, ts);
adaptEventSkipping();
if (rewindFlg) {
rewindFlg = false;
sliceLastTs = Integer.MAX_VALUE;
}
return isDisplayRawInput() ? in : dirPacket;
}
public void doDefaults() {
setSearchMethod(SearchMethod.DiamondSearch);
setBlockDimension(21);
setNumScales(2);
setSearchDistance(4);
setAdaptiveEventSkipping(true);
setAdaptiveSliceDuration(true);
setMaxAllowedSadDistance(.5f);
setDisplayVectorsEnabled(true);
setPpsScaleDisplayRelativeOFLength(true);
setDisplayGlobalMotion(true);
setPpsScale(.1f);
setSliceMaxValue(7);
setRectifyPolarties(true); // rectify to better handle cases of steadicam where pan/tilt flips event polarities
setValidPixOccupancy(.01f); // at least this fraction of pixels from each block must both have nonzero values
setSliceMethod(SliceMethod.AreaEventNumber);
// compute nearest power of two over block dimension
int ss = (int) (Math.log(blockDimension - 1) / Math.log(2));
setAreaEventNumberSubsampling(ss);
// set event count so that count=block area * sliceMaxValue/4;
// i.e. set count to roll over when slice pixels from most subsampled scale are half full if they are half stimulated
final int eventCount = (((blockDimension * blockDimension) * sliceMaxValue) / 2) >> (numScales - 1);
setSliceEventCount(eventCount);
setSliceDurationUs(50000); // set a bit smaller max duration in us to avoid instability where count gets too high with sparse input
}
private void adaptSliceDuration() {
// measure last hist to get control signal on slice duration
// measures avg match distance. weights the average so that long distances with more pixels in hist are not overcounted, simply
// by having more pixels.
if (rewindFlg) {
return; // don't adapt during rewind or delay before playing again
}
float radiusSum = 0;
int countSum = 0;
// int maxRadius = (int) Math.ceil(Math.sqrt(2 * searchDistance * searchDistance));
// int countSum = 0;
final int totSD = searchDistance << (numScales - 1);
for (int xx = -totSD; xx <= totSD; xx++) {
for (int yy = -totSD; yy <= totSD; yy++) {
int count = resultHistogram[xx + totSD][yy + totSD];
if (count > 0) {
final float radius = (float) Math.sqrt((xx * xx) + (yy * yy));
countSum += count;
radiusSum += radius * count;
}
}
}
if (countSum > 0) {
avgMatchDistance = radiusSum / (countSum); // compute average match distance from reference block
}
if (adaptiveSliceDuration && (countSum > adaptiveSliceDurationMinVectorsToControl)) {
// if (resultHistogramCount > 0) {
// following stats not currently used
// double[] rstHist1D = new double[resultHistogram.length * resultHistogram.length];
// int index = 0;
//// int rstHistMax = 0;
// for (int[] resultHistogram1 : resultHistogram) {
// for (int element : resultHistogram1) {
// rstHist1D[index++] = element;
// Statistics histStats = new Statistics(rstHist1D);
// // double histMax = Collections.max(Arrays.asList(ArrayUtils.toObject(rstHist1D)));
// double histMax = histStats.getMax();
// for (int m = 0; m < rstHist1D.length; m++) {
// rstHist1D[m] = rstHist1D[m] / histMax;
// lastHistStdDev = histStdDev;
// histStdDev = (float) histStats.getStdDev();
// try (FileWriter outFile = new FileWriter(outputFilename,true)) {
// outFile.write(String.format(in.getFirstEvent().getTimestamp() + " " + histStdDev + "\r\n"));
// outFile.close();
// } catch (IOException ex) {
// Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex);
// } catch (Exception e) {
// log.warning("Caught " + e + ". See following stack trace.");
// e.printStackTrace();
// float histMean = (float) histStats.getMean();
// compute error signal.
// If err<0 it means the average match distance is larger than target avg match distance, so we need to reduce slice duration
// If err>0, it means the avg match distance is too short, so increse time slice
final float err = avgMatchDistance / (avgPossibleMatchDistance); // use target that is smaller than average possible to bound excursions to large slices better
// final float err = avgPossibleMatchDistance / 2 - avgMatchDistance; // use target that is smaller than average possible to bound excursions to large slices better
// final float err = ((searchDistance << (numScales - 1)) / 2) - avgMatchDistance;
// final float lastErr = searchDistance / 2 - lastHistStdDev;
// final double err = histMean - 1/ (rstHist1D.length * rstHist1D.length);
float errSign = Math.signum(err - 1);
// float avgSad2 = sliceSummedSADValues[sliceIndex(4)] / sliceSummedSADCounts[sliceIndex(4)];
// float avgSad3 = sliceSummedSADValues[sliceIndex(3)] / sliceSummedSADCounts[sliceIndex(3)];
// float errSign = avgSad2 <= avgSad3 ? 1 : -1;
// if(Math.abs(err) > Math.abs(lastErr)) {
// errSign = -errSign;
// if(histStdDev >= 0.14) {
// if(lastHistStdDev > histStdDev) {
// errSign = -lastErrSign;
// } else {
// errSign = lastErrSign;
// errSign = 1;
// } else {
// errSign = (float) Math.signum(err);
// lastErrSign = errSign;
// problem with following is that if sliceDurationUs gets really big, then of course the avgMatchDistance becomes small because
// of the biased-towards-zero search policy that selects the closest match
switch (sliceMethod) {
case ConstantDuration:
if (adapativeSliceDurationUseProportionalControl) { // proportional
setSliceDurationUs(Math.round((1 / (1 + (err - 1) * adapativeSliceDurationProportionalErrorGain)) * sliceDurationUs));
} else { // bang bang
int durChange = (int) (-errSign * adapativeSliceDurationProportionalErrorGain * sliceDurationUs);
setSliceDurationUs(sliceDurationUs + durChange);
}
break;
case ConstantEventNumber:
case AreaEventNumber:
if (adapativeSliceDurationUseProportionalControl) { // proportional
setSliceEventCount(Math.round((1 / (1 + (err - 1) * adapativeSliceDurationProportionalErrorGain)) * sliceEventCount));
} else {
if (errSign < 0) { // match distance too short, increase duration
// match too short, increase count
setSliceEventCount(Math.round(sliceEventCount * (1 + adapativeSliceDurationProportionalErrorGain)));
} else if (errSign > 0) { // match too long, decrease duration
setSliceEventCount(Math.round(sliceEventCount * (1 - adapativeSliceDurationProportionalErrorGain)));
}
}
break;
case ConstantIntegratedFlow:
setSliceEventCount(eventCounter);
}
if (adaptiveSliceDurationLogger != null && adaptiveSliceDurationLogger.isEnabled()) {
if (!isDisplayGlobalMotion()) {
setDisplayGlobalMotion(true);
}
adaptiveSliceDurationLogger.log(String.format("%d\t%f\t%f\t%f\t%d\t%d", adaptiveSliceDurationPacketCount++, avgMatchDistance, err, motionFlowStatistics.getGlobalMotion().getGlobalSpeed().getMean(), sliceDurationUs, sliceEventCount));
}
}
}
private void setResetOFHistogramFlag() {
resetOFHistogramFlag = true;
}
private void clearResetOFHistogramFlag() {
resetOFHistogramFlag = false;
}
private void resetOFHistogram() {
if (!resetOFHistogramFlag || resultHistogram == null) {
return;
}
for (int[] h : resultHistogram) {
Arrays.fill(h, 0);
}
resultHistogramCount = 0;
// Arrays.fill(resultAngleHistogram, 0);
// resultAngleHistogramCount = 0;
// resultAngleHistogramMax = Integer.MIN_VALUE;
// Print statics of scale count, only for debuuging.
if ( printScaleCntStatEnabled ) {
float sumScaleCounts = 0;
for (int scale : scalesToComputeArray) {
sumScaleCounts += scaleResultCounts[scale];
}
for (int scale : scalesToComputeArray) {
System.out.println("Scale " + scale + " count percentage is: " + scaleResultCounts[scale]/sumScaleCounts);
}
}
Arrays.fill(scaleResultCounts, 0);
clearResetOFHistogramFlag();
}
private EngineeringFormat engFmt = new EngineeringFormat();
private TextRenderer textRenderer = null;
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
super.annotate(drawable);
GL2 gl = drawable.getGL().getGL2();
try {
gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
gl.glBlendEquation(GL.GL_FUNC_ADD);
} catch (GLException e) {
e.printStackTrace();
}
if (displayResultHistogram && (resultHistogram != null)) {
// draw histogram as shaded in 2d hist above color wheel
// normalize hist
int rhDim = resultHistogram.length; // 2*(searchDistance<<numScales)+1
gl.glPushMatrix();
final float scale = 30f / rhDim; // size same as the color wheel
gl.glTranslatef(-35, .65f * chip.getSizeY(), 0); // center above color wheel
gl.glScalef(scale, scale, 1);
gl.glColor3f(0, 0, 1);
gl.glLineWidth(2f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex2f(0, 0);
gl.glVertex2f(rhDim, 0);
gl.glVertex2f(rhDim, rhDim);
gl.glVertex2f(0, rhDim);
gl.glEnd();
if (textRenderer == null) {
textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 64));
}
int max = 0;
for (int[] h : resultHistogram) {
for (int vv : h) {
if (vv > max) {
max = vv;
}
}
}
if (max == 0) {
gl.glTranslatef(0, rhDim / 2, 0); // translate to UL corner of histogram
textRenderer.begin3DRendering();
textRenderer.draw3D("No data", 0, 0, 0, .07f);
textRenderer.end3DRendering();
gl.glPopMatrix();
} else {
final float maxRecip = 2f / max;
gl.glPushMatrix();
// draw hist values
for (int xx = 0; xx < rhDim; xx++) {
for (int yy = 0; yy < rhDim; yy++) {
float g = maxRecip * resultHistogram[xx][yy];
gl.glColor3f(g, g, g);
gl.glBegin(GL2ES3.GL_QUADS);
gl.glVertex2f(xx, yy);
gl.glVertex2f(xx + 1, yy);
gl.glVertex2f(xx + 1, yy + 1);
gl.glVertex2f(xx, yy + 1);
gl.glEnd();
}
}
final int tsd = searchDistance << (numScales - 1);
if (avgMatchDistance > 0) {
gl.glPushMatrix();
gl.glColor4f(1f, 0, 0, .5f);
gl.glLineWidth(5f);
DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgMatchDistance, 16);
gl.glPopMatrix();
}
if (avgPossibleMatchDistance > 0) {
gl.glPushMatrix();
gl.glColor4f(0, 1f, 0, .5f);
gl.glLineWidth(5f);
DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgPossibleMatchDistance / 2, 16); // draw circle at target match distance
gl.glPopMatrix();
}
// a bunch of cryptic crap to draw a string the same width as the histogram...
gl.glPopMatrix();
gl.glPopMatrix(); // back to original chip coordinates
gl.glPushMatrix();
textRenderer.begin3DRendering();
String s = String.format("d=%.1f ms", 1e-3f * sliceDeltaT);
// final float sc = TextRendererScale.draw3dScale(textRenderer, s, chip.getCanvas().getScale(), chip.getWidth(), .1f);
// determine width of string in pixels and scale accordingly
FontRenderContext frc = textRenderer.getFontRenderContext();
Rectangle2D r = textRenderer.getBounds(s); // bounds in java2d coordinates, downwards more positive
Rectangle2D rt = frc.getTransform().createTransformedShape(r).getBounds2D(); // get bounds in textrenderer coordinates
// float ps = chip.getCanvas().getScale();
float w = (float) rt.getWidth(); // width of text in textrenderer, i.e. histogram cell coordinates (1 unit = 1 histogram cell)
float sc = subSizeX / w / 6; // scale to histogram width
gl.glTranslatef(0, .65f * subSizeY, 0); // translate to UL corner of histogram
textRenderer.draw3D(s, 0, 0, 0, sc);
String s2 = String.format("Skip: %d", skipProcessingEventsCount);
textRenderer.draw3D(s2, 0, (float) (rt.getHeight()) * sc, 0, sc);
String s3 = String.format("Slice events: %d", sliceEventCount);
textRenderer.draw3D(s3, 0, 2 * (float) (rt.getHeight()) * sc, 0, sc);
StringBuilder sb = new StringBuilder("Scale counts: ");
for (int c : scaleResultCounts) {
sb.append(String.format("%d ", c));
}
textRenderer.draw3D(sb.toString(), 0, (float) (3 * rt.getHeight()) * sc, 0, sc);
if (timeLimiter.isTimedOut()) {
String s4 = String.format("Timed out: skipped %d events", nSkipped);
textRenderer.draw3D(s4, 0, 4 * (float) (rt.getHeight()) * sc, 0, sc);
}
textRenderer.end3DRendering();
gl.glPopMatrix(); // back to original chip coordinates
// log.info(String.format("processed %.1f%% (%d/%d)", 100 * (float) nProcessed / (nSkipped + nProcessed), nProcessed, (nProcessed + nSkipped)));
// // draw histogram of angles around center of image
// if (resultAngleHistogramCount > 0) {
// gl.glPushMatrix();
// gl.glTranslatef(subSizeX / 2, subSizeY / 2, 0);
// gl.glLineWidth(getMotionVectorLineWidthPixels());
// gl.glColor3f(1, 1, 1);
// gl.glBegin(GL.GL_LINES);
// for (int i = 0; i < ANGLE_HISTOGRAM_COUNT; i++) {
// float l = ((float) resultAngleHistogram[i] / resultAngleHistogramMax) * chip.getMinSize() / 2; // bin 0 is angle -PI
// double angle = ((2 * Math.PI * i) / ANGLE_HISTOGRAM_COUNT) - Math.PI;
// float dx = (float) Math.cos(angle) * l, dy = (float) Math.sin(angle) * l;
// gl.glVertex2f(0, 0);
// gl.glVertex2f(dx, dy);
// gl.glEnd();
// gl.glPopMatrix();
resetOFHistogram(); // clears OF histogram if slices have been rotated
}
} else {
resetOFHistogram(); // clears OF histogram if slices have been rotated and we are not displaying the histogram
}
if (sliceMethod == SliceMethod.AreaEventNumber && showAreaCountAreasTemporarily) {
int d = 1 << areaEventNumberSubsampling;
gl.glLineWidth(2f);
gl.glColor3f(1, 1, 1);
gl.glBegin(GL.GL_LINES);
for (int x = 0; x <= subSizeX; x += d) {
gl.glVertex2f(x, 0);
gl.glVertex2f(x, subSizeY);
}
for (int y = 0; y <= subSizeY; y += d) {
gl.glVertex2f(0, y);
gl.glVertex2f(subSizeX, y);
}
gl.glEnd();
}
if (sliceMethod == SliceMethod.ConstantIntegratedFlow && showAreaCountAreasTemporarily) {
// TODO fill in what to draw
}
if (showBlockSizeAndSearchAreaTemporarily) {
gl.glLineWidth(2f);
gl.glColor3f(1, 0, 0);
// show block size
final int xx = subSizeX / 2, yy = subSizeY / 2, d = blockDimension / 2;
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex2f(xx - d, yy - d);
gl.glVertex2f(xx + d, yy - d);
gl.glVertex2f(xx + d, yy + d);
gl.glVertex2f(xx - d, yy + d);
gl.glEnd();
// show search area
gl.glColor3f(0, 1, 0);
final int sd = d + (searchDistance << (numScales - 1));
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex2f(xx - sd, yy - sd);
gl.glVertex2f(xx + sd, yy - sd);
gl.glVertex2f(xx + sd, yy + sd);
gl.glVertex2f(xx - sd, yy + sd);
gl.glEnd();
}
}
@Override
public synchronized void resetFilter() {
setSubSampleShift(0); // filter breaks with super's bit shift subsampling
super.resetFilter();
eventCounter = 0;
// lastTs = Integer.MIN_VALUE;
checkArrays();
if (slices == null) {
return; // on reset maybe chip is not set yet
}
for (byte[][][] b : slices) {
clearSlice(b);
}
currentSliceIdx = 0; // start by filling slice 0
currentSlice = slices[currentSliceIdx];
sliceLastTs = Integer.MAX_VALUE;
rewindFlg = true;
if (adaptiveEventSkippingUpdateCounterLPFilter != null) {
adaptiveEventSkippingUpdateCounterLPFilter.reset();
}
clearAreaCounts();
clearNonGreedyRegions();
}
@Override
public void update(Observable o, Object arg) {
if (!isFilterEnabled()) {
return;
}
super.update(o, arg);
if ((o instanceof AEChip) && (chip.getNumPixels() > 0)) {
resetFilter();
}
}
private LowpassFilter speedFilter = new LowpassFilter();
/**
* uses the current event to maybe rotate the slices
*
* @return true if slices were rotated
*/
private boolean maybeRotateSlices() {
int dt = ts - sliceLastTs;
if (dt < 0 || rewindFlg) { // handle timestamp wrapping
// System.out.println("rotated slices at ");
// System.out.println("rotated slices with dt= "+dt);
rotateSlices();
eventCounter = 0;
sliceDeltaT = dt;
sliceLastTs = ts;
return true;
}
switch (sliceMethod) {
case ConstantDuration:
if ((dt < sliceDurationUs)) {
return false;
}
break;
case ConstantEventNumber:
if (eventCounter < sliceEventCount) {
return false;
}
break;
case AreaEventNumber:
if (!areaCountExceeded && dt < MAX_SLICE_DURATION_US) {
return false;
}
break;
case ConstantIntegratedFlow:
speedFilter.setTauMs(sliceDeltaTimeUs(2) >> 10);
final float meanGlobalSpeed = motionFlowStatistics.getGlobalMotion().meanGlobalSpeed;
if (!Float.isNaN(meanGlobalSpeed)) {
speedFilter.filter(meanGlobalSpeed, ts);
}
final float filteredMeanGlobalSpeed = speedFilter.getValue();
final float totalMovement = filteredMeanGlobalSpeed * dt * 1e-6f;
if (Float.isNaN(meanGlobalSpeed)) { // we need to rotate slices somwhow even if there is no motion computed yet
if (eventCounter < sliceEventCount) {
return false;
}
if ((dt < sliceDurationUs)) {
return false;
}
break;
}
if (totalMovement < searchDistance / 2 && dt < sliceDurationUs) {
return false;
}
break;
}
rotateSlices();
/* Slices have been rotated */
getSupport().firePropertyChange(PatchMatchFlow.EVENT_NEW_SLICES, slices[sliceIndex(1)], slices[sliceIndex(2)]);
return true;
}
/**
* Rotates slices by incrementing the slice pointer with rollover back to
* zero, and sets currentSliceIdx and currentBitmap. Clears the new
* currentBitmap. Thus the slice pointer increments. 0,1,2,0,1,2
*
*/
private void rotateSlices() {
if (e != null) {
sliceEndTimeUs[currentSliceIdx] = e.timestamp;
}
/*Thus if 0 is current index for current filling slice, then sliceIndex returns 1,2 for pointer =1,2.
* Then if NUM_SLICES=3, after rotateSlices(),
currentSliceIdx=NUM_SLICES-1=2, and sliceIndex(0)=2, sliceIndex(1)=0, sliceIndex(2)=1.
*/
sliceSummedSADValues[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation
sliceSummedSADCounts[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation
currentSliceIdx
if (currentSliceIdx < 0) {
currentSliceIdx = numSlices - 1;
}
currentSlice = slices[currentSliceIdx];
//sliceStartTimeUs[currentSliceIdx] = ts; // current event timestamp; set on first event to slice
clearSlice(currentSlice);
clearAreaCounts();
eventCounter = 0;
sliceDeltaT = ts - sliceLastTs;
sliceLastTs = ts;
if (imuTimesliceLogger != null && imuTimesliceLogger.isEnabled()) {
imuTimesliceLogger.log(String.format("%d %d %.3f", ts, sliceDeltaT, imuFlowEstimator.getPanRateDps()));
}
}
/**
* Returns index to slice given pointer, with zero as current filling slice
* pointer.
*
*
* @param pointer how many slices in the past to index for. I.e.. 0 for
* current slice (one being currently filled), 1 for next oldest, 2 for
* oldest (when using NUM_SLICES=3).
* @return index into bitmaps[]
*/
private int sliceIndex(int pointer) {
return (currentSliceIdx + pointer) % numSlices;
}
/**
* returns slice delta time in us from reference slice
*
* @param pointer how many slices in the past to index for. I.e.. 0 for
* current slice (one being currently filled), 1 for next oldest, 2 for
* oldest (when using NUM_SLICES=3). Only meaningful for pointer>=2,
* currently exactly only pointer==2 since we are using only 3 slices.
*
* Modified to compute the delta time using the average of start and end
* timestamps of each slices, i.e. the slice time "midpoint" where midpoint
* is defined by average of first and last timestamp.
*
*/
protected int sliceDeltaTimeUs(int pointer) {
// System.out.println("dt(" + pointer + ")=" + (sliceStartTimeUs[sliceIndex(1)] - sliceStartTimeUs[sliceIndex(pointer)]));
int idxOlder = sliceIndex(pointer), idxYounger = sliceIndex(1);
int tOlder = (sliceStartTimeUs[idxOlder] + sliceEndTimeUs[idxOlder]) / 2;
int tYounger = (sliceStartTimeUs[idxYounger] + sliceEndTimeUs[idxYounger]) / 2;
int dt = tYounger - tOlder;
return dt;
}
private int nSkipped = 0, nProcessed = 0;
/**
* Accumulates the current event to the current slice
*
* @return true if subsequent processing should done, false if it should be
* skipped for efficiency
*/
synchronized private boolean accumulateEvent(PolarityEvent e) {
if (eventCounter++ == 0) {
sliceStartTimeUs[currentSliceIdx] = e.timestamp; // current event timestamp
}
for (int s = 0; s < numScales; s++) {
final int xx = e.x >> s;
final int yy = e.y >> s;
// if (xx >= currentSlice[s].length || yy > currentSlice[s][xx].length) {
// log.warning("event out of range");
// return false;
int cv = currentSlice[s][xx][yy];
cv += rectifyPolarties ? 1 : (e.polarity == PolarityEvent.Polarity.On ? 1 : -1);
if (cv > sliceMaxValue) {
cv = sliceMaxValue;
} else if (cv < -sliceMaxValue) {
cv = -sliceMaxValue;
}
currentSlice[s][xx][yy] = (byte) cv;
}
if (sliceMethod == SliceMethod.AreaEventNumber) {
if (areaCounts == null) {
clearAreaCounts();
}
int c = ++areaCounts[e.x >> areaEventNumberSubsampling][e.y >> areaEventNumberSubsampling];
if (c >= sliceEventCount) {
areaCountExceeded = true;
// int count=0, sum=0, sum2=0;
// StringBuilder sb=new StringBuilder("Area counts:\n");
// for(int[] i:areaCounts){
// for(int j:i){
// count++;
// sum+=j;
// sum2+=j*j;
// sb.append(String.format("%6d ",j));
// sb.append("\n");
// float m=(float)sum/count;
// float s=(float)Math.sqrt((float)sum2/count-m*m);
// sb.append(String.format("mean=%.1f, std=%.1f",m,s));
// log.info("area count stats "+sb.toString());
}
}
if (timeLimiter.isTimedOut()) {
nSkipped++;
return false;
}
if (nonGreedyFlowComputingEnabled) {
// only process the event for flow if most of the other regions have already been processed
int xx = e.x >> areaEventNumberSubsampling, yy = e.y >> areaEventNumberSubsampling;
boolean didArea = nonGreedyRegions[xx][yy];
if (!didArea) {
nonGreedyRegions[xx][yy] = true;
nonGreedyRegionsCount++;
if (nonGreedyRegionsCount >= (int) (nonGreedyFractionToBeServiced * nonGreedyRegionsNumberOfRegions)) {
clearNonGreedyRegions();
}
nProcessed++;
return true; // skip counter is ignored
} else {
nSkipped++;
return false;
}
}
if (skipProcessingEventsCount == 0) {
nProcessed++;
return true;
}
if (skipCounter++ < skipProcessingEventsCount) {
nSkipped++;
return false;
}
nProcessed++;
skipCounter = 0;
return true;
}
// private void clearSlice(int idx) {
// for (int[] a : histograms[idx]) {
// Arrays.fill(a, 0);
private float sumArray[][] = null;
/**
* Computes block matching image difference best match around point x,y
* using blockDimension and searchDistance and scale
*
* @param x coordinate in subsampled space
* @param y
* @param dx_init initial offset
* @param dy_init
* @param prevSlice the slice over which we search for best match
* @param curSlice the slice from which we get the reference block
* @param subSampleBy the scale to compute this SAD on, 0 for full
* resolution, 1 for 2x2 subsampled block bitmap, etc
* @return SADResult that provides the shift and SAD value
*/
// private SADResult minHammingDistance(int x, int y, BitSet prevSlice, BitSet curSlice) {
private SADResult minSADDistance(int x, int y, int dx_init, int dy_init, byte[][][] curSlice, byte[][][] prevSlice, int subSampleBy) {
SADResult result = new SADResult();
float minSum = Float.MAX_VALUE, sum;
float FSDx = 0, FSDy = 0, DSDx = 0, DSDy = 0; // This is for testing the DS search accuracy.
final int searchRange = (2 * searchDistance) + 1; // The maximum search distance in this subSampleBy slice
if ((sumArray == null) || (sumArray.length != searchRange)) {
sumArray = new float[searchRange][searchRange];
} else {
for (float[] row : sumArray) {
Arrays.fill(row, Float.MAX_VALUE);
}
}
if (outputSearchErrorInfo) {
searchMethod = SearchMethod.FullSearch;
} else {
searchMethod = getSearchMethod();
}
final int xsub = ( x >> subSampleBy ) + dx_init;
final int ysub = ( y >> subSampleBy ) + dy_init;
final int r = ((blockDimension) / 2);
int w = subSizeX >> subSampleBy, h = subSizeY >> subSampleBy;
// Make sure both ref block and past slice block are in bounds on all sides or there'll be arrayIndexOutOfBoundary exception.
// Also we don't want to match ref block only on inner sides or there will be a bias towards motion towards middle
if (xsub - r - searchDistance < 0 || xsub + r + searchDistance >= w
|| ysub - r - searchDistance < 0 || ysub + r + searchDistance >= h) {
result.sadValue = Float.MAX_VALUE; // return very large distance for this match so it is not selected
result.scale = subSampleBy;
return result;
}
switch (searchMethod) {
case DiamondSearch:
// SD = small diamond, LD=large diamond SP=search process
/* The center of the LDSP or SDSP could change in the iteration process,
so we need to use a variable to represent it.
In the first interation, it's the Zero Motion Potion (ZMP).
*/
int xCenter = x,
yCenter = y;
/* x offset of center point relative to ZMP, y offset of center point to ZMP.
x offset of center pointin positive number to ZMP, y offset of center point in positive number to ZMP.
*/
int dx,
dy,
xidx,
yidx; // x and y best match offsets in pixels, indices of these in 2d hist
int minPointIdx = 0; // Store the minimum point index.
boolean SDSPFlg = false; // If this flag is set true, then it means LDSP search is finished and SDSP search could start.
/* If one block has been already calculated, the computedFlg will be set so we don't to do
the calculation again.
*/
boolean computedFlg[][] = new boolean[searchRange][searchRange];
for (boolean[] row : computedFlg) {
Arrays.fill(row, false);
}
if (searchDistance == 1) { // LDSP search can only be applied for search distance >= 2.
SDSPFlg = true;
}
int iterationsLeft = searchRange * searchRange;
while (!SDSPFlg) {
/* 1. LDSP search */
for (int pointIdx = 0; pointIdx < LDSP.length; pointIdx++) {
dx = (LDSP[pointIdx][0] + xCenter) - x;
dy = (LDSP[pointIdx][1] + yCenter) - y;
xidx = dx + searchDistance;
yidx = dy + searchDistance;
// Point to be searched is out of search area, skip it.
if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) {
continue;
}
/* We just calculate the blocks that haven't been calculated before */
if (computedFlg[xidx][yidx] == false) {
sumArray[xidx][yidx] = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy);
computedFlg[xidx][yidx] = true;
if (outputSearchErrorInfo) {
DSAverageNum++;
}
if (outputSearchErrorInfo) {
if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) { // TODO huh? this is never true, compares to itself
log.warning("It seems that there're some bugs in the DS algorithm.");
}
}
}
if (sumArray[xidx][yidx] <= minSum) {
minSum = sumArray[xidx][yidx];
minPointIdx = pointIdx;
}
}
/* 2. Check the minimum value position is in the center or not. */
xCenter = xCenter + LDSP[minPointIdx][0];
yCenter = yCenter + LDSP[minPointIdx][1];
if (minPointIdx == 4) { // It means it's in the center, so we should break the loop and go to SDSP search.
SDSPFlg = true;
}
if (--iterationsLeft < 0) {
log.warning("something is wrong with diamond search; did not find min in SDSP search");
SDSPFlg = true;
}
}
/* 3. SDSP Search */
for (int[] element : SDSP) {
dx = (element[0] + xCenter) - x;
dy = (element[1] + yCenter) - y;
xidx = dx + searchDistance;
yidx = dy + searchDistance;
// Point to be searched is out of search area, skip it.
if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) {
continue;
}
/* We just calculate the blocks that haven't been calculated before */
if (computedFlg[xidx][yidx] == false) {
sumArray[xidx][yidx] = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy);
computedFlg[xidx][yidx] = true;
if (outputSearchErrorInfo) {
DSAverageNum++;
}
if (outputSearchErrorInfo) {
if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) {
log.warning("It seems that there're some bugs in the DS algorithm.");
}
}
}
if (sumArray[xidx][yidx] <= minSum) {
minSum = sumArray[xidx][yidx];
result.dx = -dx - dx_init; // minus is because result points to the past slice and motion is in the other direction
result.dy = -dy - dy_init;
result.sadValue = minSum;
}
// // debug
// if(result.dx==-searchDistance && result.dy==-searchDistance){
// System.out.println(result);
}
if (outputSearchErrorInfo) {
DSDx = result.dx;
DSDy = result.dy;
}
break;
case FullSearch:
for (dx = -searchDistance; dx <= searchDistance; dx++) {
for (dy = -searchDistance; dy <= searchDistance; dy++) {
sum = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy);
sumArray[dx + searchDistance][dy + searchDistance] = sum;
if (sum < minSum) {
minSum = sum;
result.dx = -dx - dx_init; // minus is because result points to the past slice and motion is in the other direction
result.dy = -dy - dy_init;
result.sadValue = minSum;
}
}
}
if (outputSearchErrorInfo) {
FSCnt += 1;
FSDx = result.dx;
FSDy = result.dy;
} else {
break;
}
case CrossDiamondSearch:
break;
}
// compute the indices into 2d histogram of all motion vector results.
// It's a bit complicated because of multiple scales.
// Also, we want the indexes to be centered in the histogram array so that searches at full scale appear at the middle
// of the array and not at 0,0 corner.
// Suppose searchDistance=1 and numScales=2. Then the histogram has size 2*2+1=5.
// Therefore the scale 0 results need to have offset added to them to center results in histogram that
// shows results over all scales.
result.scale = subSampleBy;
// convert dx in search steps to dx in pixels including subsampling
// compute index assuming no subsampling or centering
result.xidx = ( result.dx + dx_init ) + searchDistance;
result.yidx = ( result.dy + dy_init ) + searchDistance;
// compute final dx and dy including subsampling
result.dx = ( result.dx ) << subSampleBy;
result.dy = ( result.dy ) << subSampleBy;
// compute final index including subsampling and centering
// idxCentering is shift needed to be applyed to store this result finally into the hist,
final int idxCentering = (searchDistance << (numScales - 1)) - ((searchDistance) << subSampleBy); // i.e. for subSampleBy=0 and numScales=2, shift=1 so that full scale search is centered in 5x5 hist
result.xidx = (result.xidx << subSampleBy) + idxCentering;
result.yidx = (result.yidx << subSampleBy) + idxCentering;
// if (result.xidx < 0 || result.yidx < 0 || result.xidx > maxIdx || result.yidx > maxIdx) {
// log.warning("something wrong with result=" + result);
// return null;
if (outputSearchErrorInfo) {
if ((DSDx == FSDx) && (DSDy == FSDy)) {
DSCorrectCnt += 1;
} else {
DSAveError[0] += Math.abs(DSDx - FSDx);
DSAveError[1] += Math.abs(DSDy - FSDy);
}
if (0 == (FSCnt % 10000)) {
log.log(Level.INFO, "Correct Diamond Search times are {0}, Full Search times are {1}, accuracy is {2}, averageNumberPercent is {3}, averageError is ({4}, {5})",
new Object[]{DSCorrectCnt, FSCnt, DSCorrectCnt / FSCnt, DSAverageNum / (searchRange * searchRange * FSCnt), DSAveError[0] / FSCnt, DSAveError[1] / (FSCnt - DSCorrectCnt)});
}
}
// if (tmpSadResult.xidx == searchRange-1 && tmpSadResult.yidx == searchRange-1) {
// tmpSadResult.sadValue = 1; // reject results to top right that are likely result of ambiguous search
return result;
}
/**
* computes Hamming distance centered on x,y with patch of patchSize for
* prevSliceIdx relative to curSliceIdx patch.
*
* @param xfull coordinate x in full resolution
* @param yfull coordinate y in full resolution
* @param dx the offset in pixels in the subsampled space of the past slice.
* The motion vector is then *from* this position *to* the current slice.
* @param dy
* @param prevSlice
* @param curSlice
* @param subsampleBy the scale to search over
* @return Distance value, max 1 when all pixels differ, min 0 when all the
* same
*/
private float sadDistance(final int xfull, final int yfull,
final int dx, final int dy,
final byte[][][] curSlice,
final byte[][][] prevSlice,
final int subsampleBy) {
final int x = xfull >> subsampleBy;
final int y = yfull >> subsampleBy;
final int r = ((blockDimension) / 2);
// int w = subSizeX >> subsampleBy, h = subSizeY >> subsampleBy;
// int adx = dx > 0 ? dx : -dx; // abs val of dx and dy, to compute limits
// int ady = dy > 0 ? dy : -dy;
// // Make sure both ref block and past slice block are in bounds on all sides or there'll be arrayIndexOutOfBoundary exception.
// // Also we don't want to match ref block only on inner sides or there will be a bias towards motion towards middle
// if (x - r - adx < 0 || x + r + adx >= w
// || y - r - ady < 0 || y + r + ady >= h) {
// return 1; // tobi changed to 1 again // Float.MAX_VALUE; // return very large distance for this match so it is not selected
int validPixNumCurSlice = 0, validPixNumPrevSlice = 0; // The valid pixel number in the current block
int nonZeroMatchCount = 0;
// int saturatedPixNumCurSlice = 0, saturatedPixNumPrevSlice = 0; // The valid pixel number in the current block
int sumDist = 0;
// try {
for (int xx = x - r; xx <= (x + r); xx++) {
for (int yy = y - r; yy <= (y + r); yy++) {
// if (xx < 0 || yy < 0 || xx >= w || yy >= h
// || xx + dx < 0 || yy + dy < 0 || xx + dx >= w || yy + dy >= h) {
//// log.warning("out of bounds slice access; something wrong"); // TODO fix this check above
// continue;
int currSliceVal = curSlice[subsampleBy][xx][yy]; // binary value on (xx, yy) for current slice
int prevSliceVal = prevSlice[subsampleBy][xx + dx][yy + dy]; // binary value on (xx, yy) for previous slice at offset dx,dy in (possibly subsampled) slice
int dist = (currSliceVal - prevSliceVal);
if (dist < 0) {
dist = (-dist);
}
sumDist += dist;
// if (currSlicePol != prevSlicePol) {
// hd += 1;
// if (currSliceVal == sliceMaxValue || currSliceVal == -sliceMaxValue) {
// saturatedPixNumCurSlice++; // pixels that are not saturated
// if (prevSliceVal == sliceMaxValue || prevSliceVal == -sliceMaxValue) {
// saturatedPixNumPrevSlice++;
if (currSliceVal != 0) {
validPixNumCurSlice++; // pixels that are not saturated
}
if (prevSliceVal != 0) {
validPixNumPrevSlice++;
}
if (currSliceVal != 0 && prevSliceVal != 0) {
nonZeroMatchCount++; // pixels that both have events in them
}
}
}
// } catch (ArrayIndexOutOfBoundsException ex) {
// log.warning(ex.toString());
// debug
// if(dx==-1 && dy==-1) return 0; else return Float.MAX_VALUE;
// normalize by dimesion of subsampling, with idea that subsampling increases SAD
//by sqrt(area) because of Gaussian distribution of SAD values
sumDist = sumDist >> (subsampleBy << 1);
final int blockDim = (2 * r) + 1;
final int blockArea = (blockDim) * (blockDim); // TODO check math here for fraction correct with subsampling
// TODD: NEXT WORK IS TO DO THE RESEARCH ON WEIGHTED HAMMING DISTANCE
// Calculate the metric confidence value
final int minValidPixNum = (int) (this.validPixOccupancy * blockArea);
// final int maxSaturatedPixNum = (int) ((1 - this.validPixOccupancy) * blockArea);
final float sadNormalizer = 1f / (blockArea * (rectifyPolarties ? 2 : 1) * sliceMaxValue);
// if current or previous block has insufficient pixels with values or if all the pixels are filled up, then reject match
if ((validPixNumCurSlice < minValidPixNum)
|| (validPixNumPrevSlice < minValidPixNum)
|| (nonZeroMatchCount < minValidPixNum) // || (saturatedPixNumCurSlice >= maxSaturatedPixNum) || (saturatedPixNumPrevSlice >= maxSaturatedPixNum)
) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it.
return 1; // tobi changed to 1 to represent max distance // Float.MAX_VALUE;
} else {
/*
retVal consists of the distance and the dispersion. dispersion is used to describe the spatial relationship within one block.
Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion.
Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner.
*/
final float finalDistance = sadNormalizer * ((sumDist * weightDistance) + (Math.abs(validPixNumCurSlice - validPixNumPrevSlice) * (1 - weightDistance)));
return finalDistance;
}
}
/**
* Computes hamming weight around point x,y using blockDimension and
* searchDistance
*
* @param x coordinate in subsampled space
* @param y
* @param prevSlice
* @param curSlice
* @return SADResult that provides the shift and SAD value
*/
// private SADResult minJaccardDistance(int x, int y, BitSet prevSlice, BitSet curSlice) {
// private SADResult minJaccardDistance(int x, int y, byte[][] prevSlice, byte[][] curSlice) {
// float minSum = Integer.MAX_VALUE, sum = 0;
// SADResult sadResult = new SADResult(0, 0, 0);
// for (int dx = -searchDistance; dx <= searchDistance; dx++) {
// for (int dy = -searchDistance; dy <= searchDistance; dy++) {
// sum = jaccardDistance(x, y, dx, dy, prevSlice, curSlice);
// if (sum <= minSum) {
// minSum = sum;
// sadResult.dx = dx;
// sadResult.dy = dy;
// sadResult.sadValue = minSum;
// return sadResult;
/**
* computes Hamming distance centered on x,y with patch of patchSize for
* prevSliceIdx relative to curSliceIdx patch.
*
* @param x coordinate in subSampled space
* @param y
* @param patchSize
* @param prevSlice
* @param curSlice
* @return SAD value
*/
// private float jaccardDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) {
private float jaccardDistance(int x, int y, int dx, int dy, boolean[][] prevSlice, boolean[][] curSlice) {
float M01 = 0, M10 = 0, M11 = 0;
int blockRadius = blockDimension / 2;
// Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception.
if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius))
|| (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) {
return 1; // changed back to 1 // Float.MAX_VALUE;
}
for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) {
for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) {
final boolean c = curSlice[xx][yy], p = prevSlice[xx - dx][yy - dy];
if ((c == true) && (p == true)) {
M11 += 1;
}
if ((c == true) && (p == false)) {
M01 += 1;
}
if ((c == false) && (p == true)) {
M10 += 1;
}
// if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) {
// M11 += 1;
// if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == false)) {
// M01 += 1;
// if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == false) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) {
// M10 += 1;
}
}
float retVal;
if (0 == (M01 + M10 + M11)) {
retVal = 0;
} else {
retVal = M11 / (M01 + M10 + M11);
}
retVal = 1 - retVal;
return retVal;
}
// private SADResult minVicPurDistance(int blockX, int blockY) {
// ArrayList<Integer[]> seq1 = new ArrayList(1);
// SADResult sadResult = new SADResult(0, 0, 0);
// int size = spikeTrains[blockX][blockY].size();
// int lastTs = spikeTrains[blockX][blockY].get(size - forwardEventNum)[0];
// for (int i = size - forwardEventNum; i < size; i++) {
// seq1.add(spikeTrains[blockX][blockY].get(i));
//// if(seq1.get(2)[0] - seq1.get(0)[0] > thresholdTime) {
//// return sadResult;
// double minium = Integer.MAX_VALUE;
// for (int i = -1; i < 2; i++) {
// for (int j = -1; j < 2; j++) {
// // Remove the seq1 itself
// if ((0 == i) && (0 == j)) {
// continue;
// ArrayList<Integer[]> seq2 = new ArrayList(1);
// if ((blockX >= 2) && (blockY >= 2)) {
// ArrayList<Integer[]> tmpSpikes = spikeTrains[blockX + i][blockY + j];
// if (tmpSpikes != null) {
// for (int index = 0; index < tmpSpikes.size(); index++) {
// if (tmpSpikes.get(index)[0] >= lastTs) {
// seq2.add(tmpSpikes.get(index));
// double dis = vicPurDistance(seq1, seq2);
// if (dis < minium) {
// minium = dis;
// sadResult.dx = -i;
// sadResult.dy = -j;
// lastFireIndex[blockX][blockY] = spikeTrains[blockX][blockY].size() - 1;
// if ((sadResult.dx != 1) || (sadResult.dy != 0)) {
// // sadResult = new SADResult(0, 0, 0);
// return sadResult;
// private double vicPurDistance(ArrayList<Integer[]> seq1, ArrayList<Integer[]> seq2) {
// int sum1Plus = 0, sum1Minus = 0, sum2Plus = 0, sum2Minus = 0;
// Iterator itr1 = seq1.iterator();
// Iterator itr2 = seq2.iterator();
// int length1 = seq1.size();
// int length2 = seq2.size();
// double[][] distanceMatrix = new double[length1 + 1][length2 + 1];
// for (int h = 0; h <= length1; h++) {
// for (int k = 0; k <= length2; k++) {
// if (h == 0) {
// distanceMatrix[h][k] = k;
// continue;
// if (k == 0) {
// distanceMatrix[h][k] = h;
// continue;
// double tmpMin = Math.min(distanceMatrix[h][k - 1] + 1, distanceMatrix[h - 1][k] + 1);
// double event1 = seq1.get(h - 1)[0] - seq1.get(0)[0];
// double event2 = seq2.get(k - 1)[0] - seq2.get(0)[0];
// distanceMatrix[h][k] = Math.min(tmpMin, distanceMatrix[h - 1][k - 1] + (cost * Math.abs(event1 - event2)));
// while (itr1.hasNext()) {
// Integer[] ii = (Integer[]) itr1.next();
// if (ii[1] == 1) {
// sum1Plus += 1;
// } else {
// sum1Minus += 1;
// while (itr2.hasNext()) {
// Integer[] ii = (Integer[]) itr2.next();
// if (ii[1] == 1) {
// sum2Plus += 1;
// } else {
// sum2Minus += 1;
// // return Math.abs(sum1Plus - sum2Plus) + Math.abs(sum1Minus - sum2Minus);
// return distanceMatrix[length1][length2];
// /**
// * Computes min SAD shift around point x,y using blockDimension and
// * searchDistance
// *
// * @param x coordinate in subsampled space
// * @param y
// * @param prevSlice
// * @param curSlice
// * @return SADResult that provides the shift and SAD value
// */
// private SADResult minSad(int x, int y, BitSet prevSlice, BitSet curSlice) {
// // for now just do exhaustive search over all shifts up to +/-searchDistance
// SADResult sadResult = new SADResult(0, 0, 0);
// float minSad = 1;
// for (int dx = -searchDistance; dx <= searchDistance; dx++) {
// for (int dy = -searchDistance; dy <= searchDistance; dy++) {
// float sad = sad(x, y, dx, dy, prevSlice, curSlice);
// if (sad <= minSad) {
// minSad = sad;
// sadResult.dx = dx;
// sadResult.dy = dy;
// sadResult.sadValue = minSad;
// return sadResult;
// /**
// * computes SAD centered on x,y with shift of dx,dy for prevSliceIdx
// * relative to curSliceIdx patch.
// *
// * @param x coordinate x in subSampled space
// * @param y coordinate y in subSampled space
// * @param dx block shift of x
// * @param dy block shift of y
// * @param prevSliceIdx
// * @param curSliceIdx
// * @return SAD value
// */
// private float sad(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) {
// int blockRadius = blockDimension / 2;
// // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception.
// if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius))
// || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) {
// return Float.MAX_VALUE;
// float sad = 0, retVal = 0;
// float validPixNumCurrSli = 0, validPixNumPrevSli = 0; // The valid pixel number in the current block
// for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) {
// for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) {
// boolean currSlicePol = curSlice.get((xx + 1) + ((yy) * subSizeX)); // binary value on (xx, yy) for current slice
// boolean prevSlicePol = prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)); // binary value on (xx, yy) for previous slice
// int imuWarningDialog = (currSlicePol ? 1 : 0) - (prevSlicePol ? 1 : 0);
// if (currSlicePol == true) {
// validPixNumCurrSli += 1;
// if (prevSlicePol == true) {
// validPixNumPrevSli += 1;
// if (imuWarningDialog <= 0) {
// imuWarningDialog = -imuWarningDialog;
// sad += imuWarningDialog;
// // Calculate the metric confidence value
// float validPixNum = this.validPixOccupancy * (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1));
// if ((validPixNumCurrSli <= validPixNum) || (validPixNumPrevSli <= validPixNum)) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it.
// retVal = 1;
// } else {
// /*
// retVal is consisted of the distance and the dispersion, dispersion is used to describe the spatial relationship within one block.
// Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion.
// Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner.
// */
// retVal = ((sad * weightDistance) + (Math.abs(validPixNumCurrSli - validPixNumPrevSli) * (1 - weightDistance))) / (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1));
// return retVal;
private class SADResult {
int dx, dy; // best match offset in pixels to reference block from past slice block, i.e. motion vector points in this direction
float vx, vy; // optical flow in pixels/second corresponding to this match
float sadValue; // sum of absolute differences for this best match normalized by number of pixels in reference area
int xidx, yidx; // x and y indices into 2d matrix of result. 0,0 corresponds to motion SW. dx, dy may be negative, like (-1, -1) represents SW.
// However, for histgram index, it's not possible to use negative number. That's the reason for intrducing xidx and yidx.
// boolean minSearchedFlg = false; // The flag indicates that this minimum have been already searched before.
int scale;
/**
* Allocates new results initialized to zero
*/
public SADResult() {
this(0, 0, 0, 0);
}
public SADResult(int dx, int dy, float sadValue, int scale) {
this.dx = dx;
this.dy = dy;
this.sadValue = sadValue;
}
public void set(SADResult s) {
this.dx = s.dx;
this.dy = s.dy;
this.sadValue = s.sadValue;
this.xidx = s.xidx;
this.yidx = s.yidx;
this.scale = s.scale;
}
@Override
public String toString() {
return String.format("(dx,dy=%5d,%5d), (vx,vy=%.1f,%.1f pps), SAD=%f, scale=%d", dx, dy, vx, vy, sadValue, scale);
}
}
private class Statistics {
double[] data;
int size;
public Statistics(double[] data) {
this.data = data;
size = data.length;
}
double getMean() {
double sum = 0.0;
for (double a : data) {
sum += a;
}
return sum / size;
}
double getVariance() {
double mean = getMean();
double temp = 0;
for (double a : data) {
temp += (a - mean) * (a - mean);
}
return temp / size;
}
double getStdDev() {
return Math.sqrt(getVariance());
}
public double median() {
Arrays.sort(data);
if ((data.length % 2) == 0) {
return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
}
return data[data.length / 2];
}
public double getMin() {
Arrays.sort(data);
return data[0];
}
public double getMax() {
Arrays.sort(data);
return data[data.length - 1];
}
}
/**
* @return the blockDimension
*/
public int getBlockDimension() {
return blockDimension;
}
/**
* @param blockDimension the blockDimension to set
*/
synchronized public void setBlockDimension(int blockDimension) {
int old = this.blockDimension;
// enforce odd value
if ((blockDimension & 1) == 0) { // even
if (blockDimension > old) {
blockDimension++;
} else {
blockDimension
}
}
// clip final value
if (blockDimension < 1) {
blockDimension = 1;
} else if (blockDimension > 63) {
blockDimension = 63;
}
this.blockDimension = blockDimension;
getSupport().firePropertyChange("blockDimension", old, blockDimension);
putInt("blockDimension", blockDimension);
showBlockSizeAndSearchAreaTemporarily();
}
/**
* @return the sliceMethod
*/
public SliceMethod getSliceMethod() {
return sliceMethod;
}
/**
* @param sliceMethod the sliceMethod to set
*/
synchronized public void setSliceMethod(SliceMethod sliceMethod) {
SliceMethod old = this.sliceMethod;
this.sliceMethod = sliceMethod;
putString("sliceMethod", sliceMethod.toString());
if (sliceMethod == SliceMethod.AreaEventNumber || sliceMethod == SliceMethod.ConstantIntegratedFlow) {
showAreasForAreaCountsTemporarily();
}
// if(sliceMethod==SliceMethod.ConstantIntegratedFlow){
// setDisplayGlobalMotion(true);
getSupport().firePropertyChange("sliceMethod", old, this.sliceMethod);
}
public PatchCompareMethod getPatchCompareMethod() {
return patchCompareMethod;
}
synchronized public void setPatchCompareMethod(PatchCompareMethod patchCompareMethod) {
this.patchCompareMethod = patchCompareMethod;
putString("patchCompareMethod", patchCompareMethod.toString());
}
/**
*
* @return the search method
*/
public SearchMethod getSearchMethod() {
return searchMethod;
}
/**
*
* @param searchMethod the method to be used for searching
*/
synchronized public void setSearchMethod(SearchMethod searchMethod) {
SearchMethod old = this.searchMethod;
this.searchMethod = searchMethod;
putString("searchMethod", searchMethod.toString());
getSupport().firePropertyChange("searchMethod", old, this.searchMethod);
}
private void computeAveragePossibleMatchDistance() {
int n = 0;
double s = 0;
for (int xx = -searchDistance; xx <= searchDistance; xx++) {
for (int yy = -searchDistance; yy <= searchDistance; yy++) {
n++;
s += Math.sqrt((xx * xx) + (yy * yy));
}
}
double d = s / n; // avg for one scale
double s2 = 0;
for (int i = 0; i < numScales; i++) {
s2 += d * (1 << i);
}
double d2 = s2 / numScales;
log.info(String.format("searchDistance=%d numScales=%d: avgPossibleMatchDistance=%.1f", searchDistance, numScales, avgPossibleMatchDistance));
avgPossibleMatchDistance = (float) d2;
}
@Override
synchronized public void setSearchDistance(int searchDistance) {
int old = this.searchDistance;
if (searchDistance > 12) {
searchDistance = 12;
} else if (searchDistance < 1) {
searchDistance = 1; // limit size
}
this.searchDistance = searchDistance;
putInt("searchDistance", searchDistance);
getSupport().firePropertyChange("searchDistance", old, searchDistance);
resetFilter();
showBlockSizeAndSearchAreaTemporarily();
computeAveragePossibleMatchDistance();
}
/**
* @return the sliceDurationUs
*/
public int getSliceDurationUs() {
return sliceDurationUs;
}
/**
* @param sliceDurationUs the sliceDurationUs to set
*/
public void setSliceDurationUs(int sliceDurationUs) {
int old = this.sliceDurationUs;
if (sliceDurationUs < MIN_SLICE_DURATION_US) {
sliceDurationUs = MIN_SLICE_DURATION_US;
} else if (sliceDurationUs > MAX_SLICE_DURATION_US) {
sliceDurationUs = MAX_SLICE_DURATION_US; // limit it to one second
}
this.sliceDurationUs = sliceDurationUs;
/* If the slice duration is changed, reset FSCnt and DScorrect so we can get more accurate evaluation result */
FSCnt = 0;
DSCorrectCnt = 0;
putInt("sliceDurationUs", sliceDurationUs);
getSupport().firePropertyChange("sliceDurationUs", old, this.sliceDurationUs);
}
/**
* @return the sliceEventCount
*/
public int getSliceEventCount() {
return sliceEventCount;
}
/**
* @param sliceEventCount the sliceEventCount to set
*/
public void setSliceEventCount(int sliceEventCount) {
final int div=sliceMethod==SliceMethod.AreaEventNumber? numAreas:1;
final int old = this.sliceEventCount;
if (sliceEventCount < MIN_SLICE_EVENT_COUNT_FULL_FRAME/div) {
sliceEventCount = MIN_SLICE_EVENT_COUNT_FULL_FRAME/div;
} else if (sliceEventCount > MAX_SLICE_EVENT_COUNT_FULL_FRAME/div) {
sliceEventCount = MAX_SLICE_EVENT_COUNT_FULL_FRAME/div;
}
this.sliceEventCount = sliceEventCount;
putInt("sliceEventCount", sliceEventCount);
getSupport().firePropertyChange("sliceEventCount", old, this.sliceEventCount);
}
public float getMaxAllowedSadDistance() {
return maxAllowedSadDistance;
}
public void setMaxAllowedSadDistance(float maxAllowedSadDistance) {
float old = this.maxAllowedSadDistance;
if (maxAllowedSadDistance < 0) {
maxAllowedSadDistance = 0;
} else if (maxAllowedSadDistance > 1) {
maxAllowedSadDistance = 1;
}
this.maxAllowedSadDistance = maxAllowedSadDistance;
putFloat("maxAllowedSadDistance", maxAllowedSadDistance);
getSupport().firePropertyChange("maxAllowedSadDistance", old, this.maxAllowedSadDistance);
}
public float getValidPixOccupancy() {
return validPixOccupancy;
}
public void setValidPixOccupancy(float validPixOccupancy) {
float old = this.validPixOccupancy;
if (validPixOccupancy < 0) {
validPixOccupancy = 0;
} else if (validPixOccupancy > 1) {
validPixOccupancy = 1;
}
this.validPixOccupancy = validPixOccupancy;
putFloat("validPixOccupancy", validPixOccupancy);
getSupport().firePropertyChange("validPixOccupancy", old, this.validPixOccupancy);
}
public float getWeightDistance() {
return weightDistance;
}
public void setWeightDistance(float weightDistance) {
if (weightDistance < 0) {
weightDistance = 0;
} else if (weightDistance > 1) {
weightDistance = 1;
}
this.weightDistance = weightDistance;
putFloat("weightDistance", weightDistance);
}
// private int totalFlowEvents=0, filteredOutFlowEvents=0;
// private boolean filterOutInconsistentEvent(SADResult result) {
// if (!isOutlierMotionFilteringEnabled()) {
// return false;
// totalFlowEvents++;
// if (lastGoodSadResult == null) {
// return false;
// if (result.dx * lastGoodSadResult.dx + result.dy * lastGoodSadResult.dy >= 0) {
// return false;
// filteredOutFlowEvents++;
// return true;
synchronized private void checkArrays() {
if (subSizeX == 0 || subSizeY == 0) {
return; // don't do on init when chip is not known yet
}
// numSlices = getInt("numSlices", 3); // since resetFilter is called in super before numSlices is even initialized
if (slices == null || slices.length != numSlices
|| slices[0] == null || slices[0].length != numScales) {
if (numScales > 0 && numSlices > 0) { // deal with filter reconstruction where these fields are not set
slices = new byte[numSlices][numScales][][];
for (int n = 0; n < numSlices; n++) {
for (int s = 0; s < numScales; s++) {
int nx = (subSizeX >> s) + 1, ny = (subSizeY >> s) + 1;
if (slices[n][s] == null || slices[n][s].length != nx
|| slices[n][s][0] == null || slices[n][s][0].length != ny) {
slices[n][s] = new byte[nx][ny];
}
}
}
currentSliceIdx = 0; // start by filling slice 0
currentSlice = slices[currentSliceIdx];
sliceLastTs = Integer.MAX_VALUE;
sliceStartTimeUs = new int[numSlices];
sliceEndTimeUs = new int[numSlices];
sliceSummedSADValues = new float[numSlices];
sliceSummedSADCounts = new int[numSlices];
}
// log.info("allocated slice memory");
}
if (lastTimesMap != null) {
lastTimesMap = null; // save memory
}
int rhDim = (2 * (searchDistance << (numScales - 1))) + 1; // e.g. search distance 1, dim=3, 3x3 possibilties (including zero motion)
if ((resultHistogram == null) || (resultHistogram.length != rhDim)) {
resultHistogram = new int[rhDim][rhDim];
resultHistogramCount = 0;
}
checkNonGreedyRegionsAllocated();
}
/**
*
* @param distResult
* @return the confidence of the result. True means it's not good and should
* be rejected, false means we should accept it.
*/
private synchronized boolean isNotSufficientlyAccurate(SADResult distResult) {
boolean retVal = super.accuracyTests(); // check accuracy in super, if reject returns true
// additional test, normalized blaock distance must be small enough
// distance has max value 1
if (distResult.sadValue >= maxAllowedSadDistance) {
retVal = true;
}
return retVal;
}
/**
* @return the skipProcessingEventsCount
*/
public int getSkipProcessingEventsCount() {
return skipProcessingEventsCount;
}
/**
* @param skipProcessingEventsCount the skipProcessingEventsCount to set
*/
public void setSkipProcessingEventsCount(int skipProcessingEventsCount) {
int old = this.skipProcessingEventsCount;
if (skipProcessingEventsCount < 0) {
skipProcessingEventsCount = 0;
}
if (skipProcessingEventsCount > MAX_SKIP_COUNT) {
skipProcessingEventsCount = MAX_SKIP_COUNT;
}
this.skipProcessingEventsCount = skipProcessingEventsCount;
getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount);
putInt("skipProcessingEventsCount", skipProcessingEventsCount);
}
/**
* @return the displayResultHistogram
*/
public boolean isDisplayResultHistogram() {
return displayResultHistogram;
}
/**
* @param displayResultHistogram the displayResultHistogram to set
*/
public void setDisplayResultHistogram(boolean displayResultHistogram) {
this.displayResultHistogram = displayResultHistogram;
putBoolean("displayResultHistogram", displayResultHistogram);
}
/**
* @return the adaptiveEventSkipping
*/
public boolean isAdaptiveEventSkipping() {
return adaptiveEventSkipping;
}
/**
* @param adaptiveEventSkipping the adaptiveEventSkipping to set
*/
synchronized public void setAdaptiveEventSkipping(boolean adaptiveEventSkipping) {
boolean old = this.adaptiveEventSkipping;
this.adaptiveEventSkipping = adaptiveEventSkipping;
putBoolean("adaptiveEventSkipping", adaptiveEventSkipping);
if (adaptiveEventSkipping && adaptiveEventSkippingUpdateCounterLPFilter != null) {
adaptiveEventSkippingUpdateCounterLPFilter.reset();
}
getSupport().firePropertyChange("adaptiveEventSkipping", old, this.adaptiveEventSkipping);
}
public boolean isOutputSearchErrorInfo() {
return outputSearchErrorInfo;
}
public boolean isShowSliceBitMap() {
return showSliceBitMap;
}
/**
* @param showSliceBitMap
* @param showSliceBitMap the option of displaying bitmap
*/
synchronized public void setShowSliceBitMap(boolean showSliceBitMap) {
boolean old = this.showSliceBitMap;
this.showSliceBitMap = showSliceBitMap;
getSupport().firePropertyChange("showSliceBitMap", old, this.showSliceBitMap);
}
synchronized public void setOutputSearchErrorInfo(boolean outputSearchErrorInfo) {
this.outputSearchErrorInfo = outputSearchErrorInfo;
if (!outputSearchErrorInfo) {
searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.FullSearch.toString())); // make sure method is reset
}
}
private LowpassFilter adaptiveEventSkippingUpdateCounterLPFilter = null;
private int adaptiveEventSkippingUpdateCounter = 0;
private void adaptEventSkipping() {
if (!adaptiveEventSkipping) {
return;
}
if (chip.getAeViewer() == null) {
return;
}
int old = skipProcessingEventsCount;
if (chip.getAeViewer().isPaused() || chip.getAeViewer().isSingleStep()) {
skipProcessingEventsCount = 0;
getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount);
}
if (adaptiveEventSkippingUpdateCounterLPFilter == null) {
adaptiveEventSkippingUpdateCounterLPFilter = new LowpassFilter(chip.getAeViewer().getFrameRater().FPS_LOWPASS_FILTER_TIMECONSTANT_MS);
}
final float averageFPS = chip.getAeViewer().getFrameRater().getAverageFPS();
final int frameRate = chip.getAeViewer().getDesiredFrameRate();
boolean skipMore = averageFPS < (int) (0.75f * frameRate);
boolean skipLess = averageFPS > (int) (0.25f * frameRate);
float newSkipCount = skipProcessingEventsCount;
if (skipMore) {
newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter(1 + (skipChangeFactor * skipProcessingEventsCount), 1000 * (int) System.currentTimeMillis());
} else if (skipLess) {
newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter((skipProcessingEventsCount / skipChangeFactor) - 1, 1000 * (int) System.currentTimeMillis());
}
skipProcessingEventsCount = Math.round(newSkipCount);
if (skipProcessingEventsCount > MAX_SKIP_COUNT) {
skipProcessingEventsCount = MAX_SKIP_COUNT;
} else if (skipProcessingEventsCount < 0) {
skipProcessingEventsCount = 0;
}
getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount);
}
/**
* @return the adaptiveSliceDuration
*/
public boolean isAdaptiveSliceDuration() {
return adaptiveSliceDuration;
}
/**
* @param adaptiveSliceDuration the adaptiveSliceDuration to set
*/
synchronized public void setAdaptiveSliceDuration(boolean adaptiveSliceDuration) {
boolean old = this.adaptiveSliceDuration;
this.adaptiveSliceDuration = adaptiveSliceDuration;
putBoolean("adaptiveSliceDuration", adaptiveSliceDuration);
if (adaptiveSliceDurationLogging) {
if (adaptiveSliceDurationLogger == null) {
adaptiveSliceDurationLogger = new TobiLogger("PatchMatchFlow-SliceDurationControl", "slice duration or event count control logging");
adaptiveSliceDurationLogger.setHeaderLine("systemTimeMs\tpacketNumber\tavgMatchDistance\tmatchRadiusError\tglobalTranslationSpeedPPS\tsliceDurationUs\tsliceEventCount");
}
adaptiveSliceDurationLogger.setEnabled(adaptiveSliceDuration);
}
getSupport().firePropertyChange("adaptiveSliceDuration", old, this.adaptiveSliceDuration);
}
/**
* @return the processingTimeLimitMs
*/
public int getProcessingTimeLimitMs() {
return processingTimeLimitMs;
}
/**
* @param processingTimeLimitMs the processingTimeLimitMs to set
*/
public void setProcessingTimeLimitMs(int processingTimeLimitMs) {
this.processingTimeLimitMs = processingTimeLimitMs;
putInt("processingTimeLimitMs", processingTimeLimitMs);
}
/**
* clears all scales for a particular time slice
*
* @param slice [scale][x][y]
*/
private void clearSlice(byte[][][] slice) {
for (byte[][] scale : slice) { // for each scale
for (byte[] row : scale) { // for each col
Arrays.fill(row, (byte) 0); // fill col
}
}
}
private int dim = blockDimension + (2 * searchDistance);
protected static final String G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH = "G: search area\nR: ref block area\nB: best match";
/**
* Draws the block matching bitmap
*
* @param x
* @param y
* @param dx
* @param dy
* @param refBlock
* @param searchBlock
* @param subSampleBy
*/
synchronized private void drawMatching(SADResult result, PolarityEvent ein, byte[][][][] slices) {
// synchronized private void drawMatching(int x, int y, int dx, int dy, byte[][] refBlock, byte[][] searchBlock, int subSampleBy) {
int x = ein.x >> result.scale, y = ein.y >> result.scale;
int dx = (int) result.dx >> result.scale, dy = (int) result.dy >> result.scale;
byte[][] refBlock = slices[sliceIndex(1)][result.scale], searchBlock = slices[sliceIndex(2)][result.scale];
int subSampleBy = result.scale;
Legend sadLegend = null;
int dimNew = blockDimension + (2 * (searchDistance));
if (sliceBitMapFrame == null) {
String windowName = "Slice bitmaps";
sliceBitMapFrame = new JFrame(windowName);
sliceBitMapFrame.setLayout(new BoxLayout(sliceBitMapFrame.getContentPane(), BoxLayout.Y_AXIS));
sliceBitMapFrame.setPreferredSize(new Dimension(600, 600));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
sliceBitmapImageDisplay = ImageDisplay.createOpenGLCanvas();
sliceBitmapImageDisplay.setBorderSpacePixels(10);
sliceBitmapImageDisplay.setImageSize(dimNew, dimNew);
sliceBitmapImageDisplay.setSize(200, 200);
sliceBitmapImageDisplay.setGrayValue(0);
sliceBitmapLegend = sliceBitmapImageDisplay.addLegend(G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
panel.add(sliceBitmapImageDisplay);
sliceBitMapFrame.getContentPane().add(panel);
sliceBitMapFrame.pack();
sliceBitMapFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setShowSliceBitMap(false);
}
});
}
if (!sliceBitMapFrame.isVisible()) {
sliceBitMapFrame.setVisible(true);
}
final int radius = (blockDimension / 2) + searchDistance;
float scale = 1f / getSliceMaxValue();
try {
if ((x >= radius) && ((x + radius) < subSizeX)
&& (y >= radius) && ((y + radius) < subSizeY)) {
if (dimNew != sliceBitmapImageDisplay.getWidth()) {
dim = dimNew;
sliceBitmapImageDisplay.setImageSize(dimNew, dimNew);
sliceBitmapImageDisplay.clearLegends();
sliceBitmapLegend = sliceBitmapImageDisplay.addLegend(G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
}
// TextRenderer textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 12));
/* Reset the image first */
sliceBitmapImageDisplay.clearImage();
/* Rendering the reference patch in t-imuWarningDialog slice, it's on the center with color red */
for (int i = searchDistance; i < (blockDimension + searchDistance); i++) {
for (int j = searchDistance; j < (blockDimension + searchDistance); j++) {
float[] f = sliceBitmapImageDisplay.getPixmapRGB(i, j);
f[0] = scale * Math.abs(refBlock[((x - (blockDimension / 2)) + i) - searchDistance][((y - (blockDimension / 2)) + j) - searchDistance]);
sliceBitmapImageDisplay.setPixmapRGB(i, j, f);
}
}
/* Rendering the area within search distance in t-2d slice, it's full of the whole search area with color green */
for (int i = 0; i < ((2 * radius) + 1); i++) {
for (int j = 0; j < ((2 * radius) + 1); j++) {
float[] f = sliceBitmapImageDisplay.getPixmapRGB(i, j);
f[1] = scale * Math.abs(searchBlock[(x - radius) + i][(y - radius) + j]);
sliceBitmapImageDisplay.setPixmapRGB(i, j, f);
}
}
/* Rendering the best matching patch in t-2d slice, it's on the shifted position related to the center location with color blue */
for (int i = searchDistance + dx; i < (blockDimension + searchDistance + dx); i++) {
for (int j = searchDistance + dy; j < (blockDimension + searchDistance + dy); j++) {
float[] f = sliceBitmapImageDisplay.getPixmapRGB(i, j);
f[2] = scale * Math.abs(searchBlock[((x - (blockDimension / 2)) + i) - searchDistance][((y - (blockDimension / 2)) + j) - searchDistance]);
sliceBitmapImageDisplay.setPixmapRGB(i, j, f);
}
}
if (sliceBitmapLegend != null) {
sliceBitmapLegend.s
= G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH
+ "\nScale: "
+ subSampleBy
+ "\nSAD: "
+ engFmt.format(result.sadValue);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
}
sliceBitmapImageDisplay.repaint();
}
// /**
// * @return the numSlices
// */
// public int getNumSlices() {
// return numSlices;
// /**
// * @param numSlices the numSlices to set
// */
// synchronized public void setNumSlices(int numSlices) {
// if (numSlices < 3) {
// numSlices = 3;
// } else if (numSlices > 8) {
// numSlices = 8;
// this.numSlices = numSlices;
// putInt("numSlices", numSlices);
/**
* @return the sliceNumBits
*/
public int getSliceMaxValue() {
return sliceMaxValue;
}
/**
* @param sliceMaxValue the sliceMaxValue to set
*/
public void setSliceMaxValue(int sliceMaxValue) {
int old = this.sliceMaxValue;
if (sliceMaxValue < 1) {
sliceMaxValue = 1;
} else if (sliceMaxValue > 127) {
sliceMaxValue = 127;
}
this.sliceMaxValue = sliceMaxValue;
putInt("sliceMaxValue", sliceMaxValue);
getSupport().firePropertyChange("sliceMaxValue", old, this.sliceMaxValue);
}
/**
* @return the rectifyPolarties
*/
public boolean isRectifyPolarties() {
return rectifyPolarties;
}
/**
* @param rectifyPolarties the rectifyPolarties to set
*/
public void setRectifyPolarties(boolean rectifyPolarties) {
boolean old = this.rectifyPolarties;
this.rectifyPolarties = rectifyPolarties;
putBoolean("rectifyPolarties", rectifyPolarties);
getSupport().firePropertyChange("rectifyPolarties", old, this.rectifyPolarties);
}
/**
* @return the useSubsampling
*/
public boolean isUseSubsampling() {
return useSubsampling;
}
/**
* @param useSubsampling the useSubsampling to set
*/
public void setUseSubsampling(boolean useSubsampling) {
this.useSubsampling = useSubsampling;
}
/**
* @return the numScales
*/
public int getNumScales() {
return numScales;
}
/**
* @param numScales the numScales to set
*/
synchronized public void setNumScales(int numScales) {
int old = this.numScales;
if (numScales < 1) {
numScales = 1;
} else if (numScales > 4) {
numScales = 4;
}
this.numScales = numScales;
putInt("numScales", numScales);
setDefaultScalesToCompute();
scaleResultCounts = new int[numScales];
showBlockSizeAndSearchAreaTemporarily();
computeAveragePossibleMatchDistance();
getSupport().firePropertyChange("numScales", old, this.numScales);
}
/**
* Computes pooled (summed) value of slice at location xx, yy, in subsampled
* region around this point
*
* @param slice
* @param x
* @param y
* @param subsampleBy pool over 1<<subsampleBy by 1<<subsampleBy area to sum
* up the slice values @return
*/
private int pool(byte[][] slice, int x, int y, int subsampleBy) {
if (subsampleBy == 0) {
return slice[x][y];
} else {
int n = 1 << subsampleBy;
int sum = 0;
for (int xx = x; xx < x + n + n; xx++) {
for (int yy = y; yy < y + n + n; yy++) {
if (xx >= subSizeX || yy >= subSizeY) {
// log.warning("should not happen that xx="+xx+" or yy="+yy);
continue; // TODO remove this check when iteration avoids this sum explictly
}
sum += slice[xx][yy];
}
}
return sum;
}
}
/**
* @return the scalesToCompute
*/
public String getScalesToCompute() {
return scalesToCompute;
}
/**
* @param scalesToCompute the scalesToCompute to set
*/
synchronized public void setScalesToCompute(String scalesToCompute) {
this.scalesToCompute = scalesToCompute;
if (scalesToCompute == null || scalesToCompute.isEmpty()) {
setDefaultScalesToCompute();
} else {
StringTokenizer st = new StringTokenizer(scalesToCompute, ", ", false);
int n = st.countTokens();
if (n == 0) {
setDefaultScalesToCompute();
} else {
scalesToComputeArray = new Integer[n];
int i = 0;
while (st.hasMoreTokens()) {
try {
int scale = Integer.parseInt(st.nextToken());
scalesToComputeArray[i++] = scale;
} catch (NumberFormatException e) {
log.warning("bad string in scalesToCompute field, use blank or 0,2 for example");
setDefaultScalesToCompute();
}
}
}
}
}
private void setDefaultScalesToCompute() {
scalesToComputeArray = new Integer[numScales];
for (int i = 0; i < numScales; i++) {
scalesToComputeArray[i] = i;
}
}
/**
* @return the areaEventNumberSubsampling
*/
public int getAreaEventNumberSubsampling() {
return areaEventNumberSubsampling;
}
/**
* @param areaEventNumberSubsampling the areaEventNumberSubsampling to set
*/
synchronized public void setAreaEventNumberSubsampling(int areaEventNumberSubsampling) {
int old = this.areaEventNumberSubsampling;
if (areaEventNumberSubsampling < 3) {
areaEventNumberSubsampling = 3;
} else if (areaEventNumberSubsampling > 7) {
areaEventNumberSubsampling = 7;
}
this.areaEventNumberSubsampling = areaEventNumberSubsampling;
putInt("areaEventNumberSubsampling", areaEventNumberSubsampling);
showAreasForAreaCountsTemporarily();
clearAreaCounts();
if (sliceMethod != SliceMethod.AreaEventNumber) {
log.warning("AreaEventNumber method is not currently selected as sliceMethod");
}
getSupport().firePropertyChange("areaEventNumberSubsampling", old, this.areaEventNumberSubsampling);
}
private void showAreasForAreaCountsTemporarily() {
if (stopShowingStuffTask != null) {
stopShowingStuffTask.cancel();
}
stopShowingStuffTask = new TimerTask() {
@Override
public void run() {
showBlockSizeAndSearchAreaTemporarily = false; // in case we are canceling a task that would clear this
showAreaCountAreasTemporarily = false;
}
};
Timer showAreaCountsAreasTimer = new Timer();
showAreaCountAreasTemporarily = true;
showAreaCountsAreasTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS);
}
private void showBlockSizeAndSearchAreaTemporarily() {
if (stopShowingStuffTask != null) {
stopShowingStuffTask.cancel();
}
stopShowingStuffTask = new TimerTask() {
@Override
public void run() {
showAreaCountAreasTemporarily = false; // in case we are canceling a task that would clear this
showBlockSizeAndSearchAreaTemporarily = false;
}
};
Timer showBlockSizeAndSearchAreaTimer = new Timer();
showBlockSizeAndSearchAreaTemporarily = true;
showBlockSizeAndSearchAreaTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS);
}
private void clearAreaCounts() {
if (sliceMethod != SliceMethod.AreaEventNumber) {
return;
}
if (areaCounts == null || areaCounts.length != 1 + (subSizeX >> areaEventNumberSubsampling)) {
int nax = 1 + (subSizeX >> areaEventNumberSubsampling), nay = 1 + (subSizeY >> areaEventNumberSubsampling);
numAreas = nax * nay;
areaCounts = new int[nax][nay];
} else {
for (int[] i : areaCounts) {
Arrays.fill(i, 0);
}
}
areaCountExceeded = false;
}
private void clearNonGreedyRegions() {
if (!nonGreedyFlowComputingEnabled) {
return;
}
checkNonGreedyRegionsAllocated();
nonGreedyRegionsCount = 0;
for (boolean[] i : nonGreedyRegions) {
Arrays.fill(i, false);
}
}
private void checkNonGreedyRegionsAllocated() {
if (nonGreedyRegions == null || nonGreedyRegions.length != 1 + (subSizeX >> areaEventNumberSubsampling)) {
nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling));
nonGreedyRegions = new boolean[1 + (subSizeX >> areaEventNumberSubsampling)][1 + (subSizeY >> areaEventNumberSubsampling)];
nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling));
}
}
public int getSliceDeltaT() {
return sliceDeltaT;
}
/**
* @return the enableImuTimesliceLogging
*/
public boolean isEnableImuTimesliceLogging() {
return enableImuTimesliceLogging;
}
/**
* @param enableImuTimesliceLogging the enableImuTimesliceLogging to set
*/
public void setEnableImuTimesliceLogging(boolean enableImuTimesliceLogging) {
this.enableImuTimesliceLogging = enableImuTimesliceLogging;
if (enableImuTimesliceLogging) {
if (imuTimesliceLogger == null) {
imuTimesliceLogger = new TobiLogger("imuTimeslice.txt", "IMU rate gyro deg/s and patchmatch timeslice duration in ms");
imuTimesliceLogger.setHeaderLine("systemtime(ms) timestamp(us) timeslice(us) rate(deg/s)");
}
}
imuTimesliceLogger.setEnabled(enableImuTimesliceLogging);
}
/**
* @return the nonGreedyFlowComputingEnabled
*/
public boolean isNonGreedyFlowComputingEnabled() {
return nonGreedyFlowComputingEnabled;
}
/**
* @param nonGreedyFlowComputingEnabled the nonGreedyFlowComputingEnabled to
* set
*/
synchronized public void setNonGreedyFlowComputingEnabled(boolean nonGreedyFlowComputingEnabled) {
boolean old = this.nonGreedyFlowComputingEnabled;
this.nonGreedyFlowComputingEnabled = nonGreedyFlowComputingEnabled;
putBoolean("nonGreedyFlowComputingEnabled", nonGreedyFlowComputingEnabled);
if (nonGreedyFlowComputingEnabled) {
clearNonGreedyRegions();
}
getSupport().firePropertyChange("nonGreedyFlowComputingEnabled", old, nonGreedyFlowComputingEnabled);
}
/**
* @return the nonGreedyFractionToBeServiced
*/
public float getNonGreedyFractionToBeServiced() {
return nonGreedyFractionToBeServiced;
}
/**
* @param nonGreedyFractionToBeServiced the nonGreedyFractionToBeServiced to
* set
*/
public void setNonGreedyFractionToBeServiced(float nonGreedyFractionToBeServiced) {
this.nonGreedyFractionToBeServiced = nonGreedyFractionToBeServiced;
putFloat("nonGreedyFractionToBeServiced", nonGreedyFractionToBeServiced);
}
/**
* @return the adapativeSliceDurationProportionalErrorGain
*/
public float getAdapativeSliceDurationProportionalErrorGain() {
return adapativeSliceDurationProportionalErrorGain;
}
/**
* @param adapativeSliceDurationProportionalErrorGain the
* adapativeSliceDurationProportionalErrorGain to set
*/
public void setAdapativeSliceDurationProportionalErrorGain(float adapativeSliceDurationProportionalErrorGain) {
this.adapativeSliceDurationProportionalErrorGain = adapativeSliceDurationProportionalErrorGain;
putFloat("adapativeSliceDurationProportionalErrorGain", adapativeSliceDurationProportionalErrorGain);
}
/**
* @return the adapativeSliceDurationUseProportionalControl
*/
public boolean isAdapativeSliceDurationUseProportionalControl() {
return adapativeSliceDurationUseProportionalControl;
}
/**
* @param adapativeSliceDurationUseProportionalControl the
* adapativeSliceDurationUseProportionalControl to set
*/
public void setAdapativeSliceDurationUseProportionalControl(boolean adapativeSliceDurationUseProportionalControl) {
this.adapativeSliceDurationUseProportionalControl = adapativeSliceDurationUseProportionalControl;
putBoolean("adapativeSliceDurationUseProportionalControl", adapativeSliceDurationUseProportionalControl);
}
public boolean isPrintScaleCntStatEnabled() {
return printScaleCntStatEnabled;
}
public void setPrintScaleCntStatEnabled(boolean printScaleCntStatEnabled) {
this.printScaleCntStatEnabled = printScaleCntStatEnabled;
putBoolean("printScaleCntStatEnabled", printScaleCntStatEnabled);
}
} |
package org.neo4j.kernel;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.shell.AppCommandParser;
import org.neo4j.shell.Output;
import org.neo4j.shell.Session;
import org.neo4j.shell.kernel.apps.GraphDatabaseApp;
public class Noobinit extends GraphDatabaseApp
{
@Override
protected String exec( AppCommandParser parser, Session session, Output out ) throws Exception
{
try
{
RelationshipType type = DynamicRelationshipType.withName( "REL_TYPE" );
out.println( "getOrCreateSingleOtherNode" );
Node fromNode = getServer().getDb().getReferenceNode();
fromNode.removeProperty( "___locking_property___" );
out.println( "Grabbed lock" );
Relationship singleRelationship =
fromNode.getSingleRelationship( type, Direction.OUTGOING );
out.println( "Single relationship is " + singleRelationship );
Node otherNode = null;
if ( singleRelationship != null )
{
otherNode = singleRelationship.getOtherNode( fromNode );
}
else
{
otherNode = fromNode.getGraphDatabase().createNode();
fromNode.createRelationshipTo( otherNode, type );
out.println( "Created new relationship" );
}
return null;
}
catch ( Exception e )
{
e.printStackTrace();
throw e;
}
}
} |
package net.fortuna.ical4j.model;
import java.util.Calendar;
import java.util.GregorianCalendar;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* <p>Period Tester.</p>
*
* </p>Tests the behaviour of the Period class to make sure it acts in
* the expected way.</p>
* @see net.fortuna.ical4j.model.Period
*/
public class PeriodTest extends TestCase {
private static final Log LOG = LogFactory.getLog(PeriodTest.class);
private Period period;
private DateTime expectedDate;
private Period expectedPeriod;
/**
* @param period
* @param expectedDate
*/
public PeriodTest(String testMethod, Period period, DateTime expectedDate) {
super(testMethod);
this.period = period;
this.expectedDate = expectedDate;
}
/**
* @param testMethod
* @param period
* @param expectedPeriod
*/
public PeriodTest(String testMethod, Period period, Period expectedPeriod) {
super(testMethod);
this.period = period;
this.expectedPeriod = expectedPeriod;
}
/**
* @param testMethod
* @param period
*/
public PeriodTest(String testMethod, Period period) {
super(testMethod);
this.period = period;
}
public PeriodTest(String name)
{
super(name);
}
public void testGetStart() {
assertEquals(expectedDate, period.getStart());
}
public void testGetEnd() {
assertEquals(expectedDate, period.getEnd());
}
/**
* date is before
* date is during
* date is after
* date is at start
* date is at end
* @throws Exception
*/
public void testIncludes() {
assertTrue(period.includes(expectedDate));
}
public void testNotIncludes() {
assertFalse(period.includes(expectedDate));
}
/**
* test date before range
* test date after range
* test date during range
* test beginning of range
* test end of range
* @throws Exception
*/
/*
public void testBeforeWithDate() throws Exception
{
assertTrue("before() claims March isn't before May",
monthMarch.before(may1994));
assertFalse("before() claims May is before March",
monthMay.before(mar1994));
assertFalse("before() claims Winter is before March",
winter.before(mar1994));
assertFalse("before() claims March month is before its beginning",
monthMarch.before(mar1994));
assertTrue("before() claims March month isn't before its end",
monthMarch.before(apr1994));
}
*/
public void testBefore() {
assertTrue(period.before(expectedPeriod));
}
public void testNotBefore() {
assertFalse(period.before(expectedPeriod));
}
public void testAfter() {
assertTrue(period.after(expectedPeriod));
}
public void testNotAfter() {
assertFalse(period.after(expectedPeriod));
}
/**
* test date before range
* test date after range
* test date during range
* test beginning of range
* test end of range
* @throws Exception
*/
/*
public void testAfterWithDate() throws Exception
{
assertFalse("after() claims March is after May",
monthMarch.after(may1994));
assertTrue("after() claims May isn't after March",
monthMay.after(mar1994));
assertFalse("after() claims Winter is after March",
winter.after(mar1994));
assertTrue("after() claims March month isn't after its beginning",
monthMarch.after(mar1994));
assertFalse("after() claims March month is after its end",
monthMarch.after(apr1994));
}
*/
/**
* test range before
* test range after
* test range adjacent before
* test range adjacent after
* test overlap
* test reverse overlap
* test range contained within
* test range contains this one
*
* @throws Exception
*/
public void testIntersects() {
assertTrue(period.intersects(expectedPeriod));
}
public void testNotIntersects() {
assertFalse(period.intersects(expectedPeriod));
}
/**
* test range before
* test range after
* test range adjacent before
* test range adjacent after
* test overlap
* test reverse overlap
* test range contained within
* test range contains this one
*
* @throws Exception
*/
/*public void testAdjacent() throws Exception
{
assertFalse("adjacent() claims March month is adjacent May month",
monthMarch.adjacent(monthMay));
assertFalse("adjacent() claims May month is adjacent March month",
monthMay.adjacent(monthMarch));
assertTrue("adjacent() claims March month isn't adjacent April month",
monthMarch.adjacent(monthApril));
assertTrue("adjacent() claims April month isn't adjacent March month",
monthApril.adjacent(monthMarch));
assertFalse("adjacent() claims overlapping halves are adjacent each other",
firstHalf.adjacent(lastHalf));
assertFalse("adjacent() claims disordered halves are adjacent each other",
lastHalf.adjacent(firstHalf));
assertFalse("adjacent() claims Winter is adjacent March month",
winter.adjacent(monthMarch));
assertFalse("adjacent() claims March month is adjacent Winter",
monthMarch.adjacent(winter));
}*/
/**
* test range before
* test range after
* test range adjacent before
* test range adjacent after
* test overlap
* test reverse overlap
* test range contained within
* test range contains this one
*
* @throws Exception
*/
public void testContains() {
assertTrue(period.contains(expectedPeriod));
}
public void testNotContains() {
assertFalse(period.contains(expectedPeriod));
}
/**
* test range before
* test range after
* test range adjacent before
* test range adjacent after
* test overlap
* test reverse overlap
* test range contained within
* test range contains this one
*
* @throws Exception
*/
public void testEquals() {
assertEquals(expectedPeriod, period);
}
/**
* test dissimilar types
* test with null
* test range before
* test range after
* test range adjacent before
* test range adjacent after
* test overlap
* test reverse overlap
* test range contained within
* test range contains this one
* test ranges that are the same
* test ranges start the same, end earlier
* test ranges start the same, end later
*
* @throws Exception
*/
public void testCompareTo() throws Exception
{
/*
try {
monthMarch.compareTo(this);
} catch (ClassCastException cce) {
// Exception expected, ignore
}
try {
monthMarch.compareTo(null);
} catch (ClassCastException cce) {
// Exception expected, ignore
}
assertTrue("compareTo() claims March month is greater than May month",
monthMarch.compareTo(monthMay) < 0);
assertTrue("compareTo() claims May month is less than March month",
monthMay.compareTo(monthMarch) > 0);
assertTrue("compareTo() claims March month is greater than April month",
monthMarch.compareTo(monthApril) < 0);
assertTrue("compareTo() claims April month is less than March month",
monthApril.compareTo(monthMarch) > 0);
assertTrue("compareTo() claims first half is greater than the last",
firstHalf.compareTo(lastHalf) < 0);
assertTrue("compareTo() claims second half is less than the first",
lastHalf.compareTo(firstHalf) > 0);
assertTrue("compareTo() claims Winter is greater than March month",
winter.compareTo(monthMarch) < 0);
assertTrue("compareTo() claims March month is less than Winter",
monthMarch.compareTo(winter) > 0);
assertTrue("compareTo() claims year1994 is not the same as duplicate",
year1994.compareTo(duplicateRange) == 0);
assertTrue("compareTo() claims April month is greater than Spring",
monthApril.compareTo(spring) < 0);
assertTrue("compareTo() claims Spring is less than April month",
spring.compareTo(monthApril) > 0);
*/
}
/**
* Testing of timezone functionality.
*/
public void testTimezone() {
java.util.Calendar cal = java.util.Calendar.getInstance();
DateTime start = new DateTime(cal.getTime());
cal.add(Calendar.DAY_OF_YEAR, 1);
// cal.setTimeZone(TimeZone.getTimeZone(TimeZones.UTC_ID));
DateTime end = new DateTime(cal.getTime());
end.setUtc(true);
Period p = new Period(start, end);
LOG.info("Timezone test - period: [" + p + "]");
assertFalse(p.getStart().isUtc());
// end utc flag should be automatically set to same as start..
assertFalse(p.getEnd().isUtc());
start.setUtc(true);
p = new Period(start, end);
LOG.info("Timezone test - period: [" + p + "]");
assertTrue(p.getStart().isUtc());
assertTrue(p.getEnd().isUtc());
p.setUtc(false);
LOG.info("Timezone test - period: [" + p + "]");
assertFalse(p.getStart().isUtc());
assertFalse(p.getEnd().isUtc());
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
TimeZone timezone = registry.getTimeZone("Australia/Melbourne");
p.setUtc(true);
p.setTimeZone(timezone);
assertFalse(p.getStart().isUtc());
assertFalse(p.getEnd().isUtc());
assertEquals(timezone, p.getStart().getTimeZone());
assertEquals(timezone, p.getEnd().getTimeZone());
}
/**
* Unit tests for {@link Period#isEmpty()}.
*/
public void testIsEmpty() {
Calendar cal = Calendar.getInstance();
DateTime start = new DateTime(cal.getTime());
assertTrue(new Period(start, start).isEmpty());
assertTrue(new Period(start, new Dur(0)).isEmpty());
cal.add(Calendar.SECOND, 1);
assertFalse(new Period(start, new DateTime(cal.getTime())).isEmpty());
assertFalse(new Period(start, new Dur(0, 0, 0, 1)).isEmpty());
}
/**
* @return
*/
public static Test suite() {
TestSuite suite = new TestSuite();
java.util.Calendar cal = new GregorianCalendar(1980,
java.util.Calendar.JANUARY, 23);
DateTime past = new DateTime(cal.getTime().getTime());
cal.set(2022, java.util.Calendar.FEBRUARY, 23);
DateTime future = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.JANUARY, 1);
DateTime begin1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.DECEMBER, 31);
DateTime end1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.MARCH, 4);
DateTime mar1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.APRIL, 12);
DateTime apr1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.MAY, 19);
DateTime may1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.JUNE, 22);
DateTime jun1994 = new DateTime(cal.getTime().getTime());
cal.set(1994, java.util.Calendar.JULY, 29);
DateTime jul1994 = new DateTime(cal.getTime().getTime());
Period year1994 = new Period(begin1994, end1994);
Period monthMarch = new Period(mar1994, apr1994);
Period monthApril = new Period(apr1994, may1994);
Period monthMay = new Period(may1994, jun1994);
Period firstHalf = new Period(begin1994, jun1994);
Period lastHalf = new Period(may1994, end1994);
Period winter = new Period(begin1994, apr1994);
Period spring = new Period(apr1994, jul1994);
Period marchToMay = new Period(mar1994, jun1994);
Period marchToApril = new Period(mar1994, may1994);
// Period duplicateRange = new Period(begin1994, end1994);
Period testPeriod;
/*
long testMillis;
long todayMillis;
todayMillis = today.getTime();
testPeriod = new DateRange();
testMillis = testRange.getStartDate().getTime();
assertTrue("Uninitialized start date should have been set to NOW",
(todayMillis - testMillis) < 5000);
testRange = new DateRange();
testMillis = testRange.getEndDate().getTime();
assertTrue("Uninitialized end date should have been set to NOW",
(todayMillis - testMillis) < 5000);
*/
testPeriod = new Period(past, (DateTime) null);
suite.addTest(new PeriodTest("testGetStart", testPeriod, past));
/*
testMillis = testPeriod.getEnd().getTime();
assertTrue("No end date with set start date should have been set to NOW",
(todayMillis - testMillis) < 5000);
*/
testPeriod = new Period(past, future);
suite.addTest(new PeriodTest("testGetStart", testPeriod, past));
suite.addTest(new PeriodTest("testGetEnd", testPeriod, future));
/*
testRange = new DateRange();
testRange.setEndDate(future);
testMillis = testRange.getStartDate().getTime();
assertTrue("No start date with set end date should have been NOW",
(todayMillis - testMillis) < 5000);
testRange = new DateRange();
testRange.setEndDate(past);
assertEquals(past, testRange.getEndDate());
testRange.setStartDate(future);
assertEquals(past, testRange.getStartDate());
assertEquals(future, testRange.getEndDate());
*/
suite.addTest(new PeriodTest("testNotIncludes", year1994, past));
suite.addTest(new PeriodTest("testIncludes", year1994, mar1994));
suite.addTest(new PeriodTest("testNotIncludes", year1994, future));
suite.addTest(new PeriodTest("testIncludes", year1994, begin1994));
suite.addTest(new PeriodTest("testIncludes", year1994, end1994));
suite.addTest(new PeriodTest("testBefore", monthMarch, monthMay));
suite.addTest(new PeriodTest("testNotBefore", monthMay, monthMarch));
suite.addTest(new PeriodTest("testNotBefore", winter, monthMarch));
suite.addTest(new PeriodTest("testNotBefore", monthMarch, winter));
suite.addTest(new PeriodTest("testNotBefore", firstHalf, lastHalf));
suite.addTest(new PeriodTest("testNotBefore", lastHalf, firstHalf));
// because month march end is same as month april start, march is not
// before april..
suite.addTest(new PeriodTest("testNotBefore", monthMarch, monthApril));
suite.addTest(new PeriodTest("testNotBefore", monthApril, monthMarch));
suite.addTest(new PeriodTest("testNotAfter", monthMarch, monthMay));
suite.addTest(new PeriodTest("testAfter", monthMay, monthMarch));
suite.addTest(new PeriodTest("testNotAfter", winter, monthMarch));
suite.addTest(new PeriodTest("testNotAfter", monthMarch, winter));
suite.addTest(new PeriodTest("testNotAfter", firstHalf, lastHalf));
suite.addTest(new PeriodTest("testNotAfter", lastHalf, firstHalf));
suite.addTest(new PeriodTest("testNotAfter", monthMarch, monthApril));
// because month march end is same as month april start, april is not
// after march..
suite.addTest(new PeriodTest("testNotAfter", monthApril, monthMarch));
suite.addTest(new PeriodTest("testNotIntersects", monthMarch, monthMay));
suite.addTest(new PeriodTest("testNotIntersects", monthMay, monthMarch));
suite.addTest(new PeriodTest("testNotIntersects", monthMarch, monthApril));
suite.addTest(new PeriodTest("testNotIntersects", monthApril, monthMarch));
suite.addTest(new PeriodTest("testIntersects", firstHalf, lastHalf));
suite.addTest(new PeriodTest("testIntersects", lastHalf, firstHalf));
suite.addTest(new PeriodTest("testIntersects", winter, monthMarch));
suite.addTest(new PeriodTest("testIntersects", monthMarch, winter));
suite.addTest(new PeriodTest("testNotContains", monthMarch, monthMay));
suite.addTest(new PeriodTest("testNotContains", monthMay, monthMarch));
suite.addTest(new PeriodTest("testNotContains", monthMarch, monthApril));
suite.addTest(new PeriodTest("testNotContains", monthApril, monthMarch));
suite.addTest(new PeriodTest("testNotContains", firstHalf, lastHalf));
suite.addTest(new PeriodTest("testNotContains", lastHalf, firstHalf));
suite.addTest(new PeriodTest("testContains", winter, monthMarch));
suite.addTest(new PeriodTest("testNotContains", monthMarch, winter));
suite.addTest(new PeriodTest("testEquals", monthMarch.add(monthMay), marchToMay));
suite.addTest(new PeriodTest("testEquals", monthMay.add(monthMarch), marchToMay));
suite.addTest(new PeriodTest("testEquals", monthMarch.add(monthApril), marchToApril));
suite.addTest(new PeriodTest("testEquals", monthApril.add(monthMarch), marchToApril));
suite.addTest(new PeriodTest("testEquals", firstHalf.add(lastHalf), year1994));
suite.addTest(new PeriodTest("testEquals", lastHalf.add(firstHalf), year1994));
suite.addTest(new PeriodTest("testEquals", winter.add(monthMarch), winter));
suite.addTest(new PeriodTest("testEquals", monthMarch.add(winter), winter));
// test period contained by subtraction..
suite.addTest(new PeriodListTest("testIsEmpty", firstHalf.subtract(year1994)));
suite.addTest(new PeriodListTest("testIsEmpty", winter.subtract(winter)));
// test non-intersecting periods..
suite.addTest(new PeriodListTest("testContains", winter.subtract(spring), winter));
suite.addTest(new PeriodListTest(winter.subtract(spring), 1));
// test intersecting periods..
PeriodList aprToMay = marchToMay.subtract(marchToApril);
suite.addTest(new PeriodListTest(aprToMay, 1));
// test subtraction contained by period..
suite.addTest(new PeriodListTest(year1994.subtract(monthApril), 2));
// other tests..
suite.addTest(new PeriodTest("testTimezone"));
suite.addTest(new PeriodTest("testEquals"));
return suite;
}
} |
package net.teamio.blockunit;
public class TestingHarness {
public void assertEquals(int a, int b) {
if (a != b) {
throw new TestAssertionException("AssertEquals: %d is not equal to %d", a, b);
}
}
public void assertEquals(boolean a, boolean b) {
if (a != b) {
throw new TestAssertionException("AssertEquals: %s is not equal to %s", a, b);
}
}
public void assertNull(Object o) {
if (o != null) {
throw new TestAssertionException("AssertNull: passed object is not null");
}
}
public void assertNotNull(Object o) {
if (o == null) {
throw new TestAssertionException("AssertNotNull: passed object is null");
}
}
public void assertTrue(boolean b) {
if (!b) {
throw new TestAssertionException("AssertTrue: passed value is false");
}
}
public void assertFalse(boolean b) {
if (b) {
throw new TestAssertionException("AssertFalse: passed value is true");
}
}
public void fail() {
throw new TestAssertionException("Test failed");
}
public void fail(String message) {
throw new TestAssertionException("Test failed: %s", message);
}
} |
import com.github.phf.jb.Bench;
import com.github.phf.jb.Bee;
/**
* Comparing basic operations on integers. The one thing that still seems to be
* true these days is that division/modulo is a LOT slower than anything else.
*/
public final class BasicOps {
private static final int COUNT = 1 << 21;
public static int x = 10, y = 20, z = 30;
public static int[] a = new int[COUNT];
public static boolean c = false;
@Bench
public void add(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = y + i;
}
}
}
@Bench
public void subtract(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = y - i;
}
}
}
@Bench
public void multiply(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = y * i;
}
}
}
@Bench
public void divide(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y / i;
}
}
}
@Bench
public void modulo(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y % i;
}
}
}
@Bench
public void equals(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
c = x == i;
}
}
}
@Bench
public void less(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
c = x < i;
}
}
}
@Bench
public void and(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = y & i;
}
}
}
@Bench
public void or(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = y | i;
}
}
}
@Bench
public void not(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = ~i;
}
}
}
@Bench
public void index(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = a[i];
}
}
}
@Bench
public void divideConstant(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y / 1037;
}
}
}
@Bench
public void divideConstantPowerOfTwo(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y / 1024;
}
}
}
@Bench
public void shiftRightConstant(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y >> 7;
}
}
}
@Bench
public void shiftLeftConstant(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y << 7;
}
}
}
} |
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Model {
private final Map<String, Long> wordList;
private final Set<OnModelDataChangedListener> listeners;
public Model() {
wordList = new HashMap<>();
listeners = new HashSet<>();
}
public void addWord(String word) {
if (wordList.containsKey(word)) {
long count = wordList.get(word);
wordList.put(word, ++count);
} else {
wordList.put(word, 1l);
}
}
public Map<String, Long> getWordList() {
return this.wordList;
}
public long getCountForWord(String word) {
if (wordList.containsKey(word)) {
return wordList.get(word);
} else {
return 0;
}
}
public void addSentence(String sentence) {
String[] words = sentence.split(" ");
if (words.length > 0) {
for (String word : words) {
addWord(word);
}
}
}
public long getHighestCount() {
final List<Long> counts = wordList.values();
Collections.sort(counts);
return counts.get(counts.size() -1);
}
public String[] getMostCountedWords() {
List<String> words = new ArrayList<>();
long highestCount = getHighestCount();
for (String word : wordList.keySet()) {
if (wordList.get(word) == highestCount) {
words.add(word);
}
}
String[] wordsArray = new String[words.size()];
for (int i = 0; i < words.size(); i++) {
wordsArray[i] = words.get(i);
}
return wordsArray;
}
public void addListener(OnModelDataChangedListener listener) {
if (listener != null) {
listeners.add(listener);
} else {
throw new IllegalArgumentException("Listener can't be null");
}
}
public void removeListener(OnModelDataChangedListener listener) {
if (listeners.contains(listener)) {
listeners.remove(listener);
} else {
throw new IllegalArgumentException("Listener is already removed");
}
}
public boolean isListenerAdded(OnModelDataChangedListener listener, Map<String, Long> wordList) {
return listeners.contains(listener);
}
private void notifyListeners(String word, long newCount, long oldCount) {
for (OnModelDataChangedListener l : listeners) {
l.onModelDataChanged(word, newCount, oldCount);
}
}
public interface OnModelDataChangedListener {
void onModelDataChanged(String word, long newCount, long oldCount);
}
} |
package com.sometrik.framework;
import java.io.IOException;
import java.io.InputStream;
import android.content.res.AssetManager;
import android.graphics.Bitmap.Config;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class FWButton extends Button implements NativeCommandHandler {
FrameWork frame;
BitmapDrawable leftDraw;
BitmapDrawable rightDraw;
BitmapDrawable bottomDraw;
BitmapDrawable topDraw;
Animation animation = null;
private GradientDrawable currentBackground = null;
public FWButton(FrameWork frameWork) {
super(frameWork);
this.frame = frameWork;
// this.setBackground(frame.getResources().getDrawable(android.R.drawable.dialog_holo_light_frame));
final FWButton button = this;
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (!FrameWork.transitionAnimation) {
frame.intChangedEvent(System.currentTimeMillis() / 1000.0, getElementId(), 1, 0);
if (animation != null) button.startAnimation(animation);
}
}
});
}
private GradientDrawable createBackground() {
if (currentBackground == null) {
currentBackground = new GradientDrawable();
setBackground(currentBackground);
}
currentBackground.setColor(Color.parseColor("#ffffff")); // Changes this drawable to use a single color instead of a gradient
return currentBackground;
}
@Override
public void addChild(View view) {
System.out.println("FWButton couldn't handle command");
}
@Override
public void addOption(int optionId, String text) {
System.out.println("FWButton couldn't handle command");
}
@Override
public void setValue(String v) {
setText(v);
}
@Override
public void setValue(int v) {
System.out.println("FWButton couldn't handle command");
}
@Override
public int getElementId() {
return getId();
}
@Override
public void setViewEnabled(Boolean enabled) {
setEnabled(enabled);
}
@Override
public void setStyle(String key, String value) {
System.out.println("Button style " + key + " " + value);
if (key.equals("font-size")){
if (value.equals("small")){
this.setTextSize(9);
} else if (value.equals("medium")){
this.setTextSize(12);
} else if (value.equals("large")){
this.setTextSize(15);
} else {
setTextSize(Integer.parseInt(value));
}
} else if (key.equals("gravity")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("bottom")) {
params.gravity = Gravity.BOTTOM;
} else if (value.equals("top")) {
params.gravity = Gravity.TOP;
} else if (value.equals("left")) {
params.gravity = Gravity.LEFT;
} else if (value.equals("right")) {
params.gravity = Gravity.RIGHT;
}
setLayoutParams(params);
} else if (key.equals("width")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("wrap-content")) {
params.width = LinearLayout.LayoutParams.WRAP_CONTENT;
} else if (value.equals("match-parent")) {
params.width = LinearLayout.LayoutParams.MATCH_PARENT;
}
setLayoutParams(params);
} else if (key.equals("height")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("wrap-content")) {
params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
} else if (value.equals("match-parent")) {
params.height = LinearLayout.LayoutParams.MATCH_PARENT;
}
setLayoutParams(params);
} else if (key.equals("weight")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.weight = Integer.parseInt(value);
setLayoutParams(params);
System.out.println("button weight: " + params.weight);
} else if (key.equals("pressed")) {
if (value.equals("true") || value.equals("1")) {
this.setPressed(true);
this.setTextColor(Color.RED);
} else {
this.setTextColor(Color.BLACK);
this.setPressed(false);
}
} else if (key.equals("icon-left") || key.equals("icon-right") || key.equals("icon-top") || key.equals("icon-bottom")){
AssetManager mgr = frame.getAssets();
try {
InputStream stream = mgr.open(value);
BitmapDrawable draw = new BitmapDrawable(stream);
this.setGravity(Gravity.CENTER);
if (key.equals("icon-right")){
rightDraw = draw;
} else if (key.equals("icon-top")){
topDraw = draw;
} else if (key.equals("icon-bottom")){
bottomDraw = draw;
} else if (key.equals("icon-left")){
leftDraw = draw;
}
this.setCompoundDrawablesWithIntrinsicBounds(leftDraw, topDraw, rightDraw, bottomDraw);
} catch (IOException e) {
System.out.println("no picture found: " + value);
e.printStackTrace();
}
} else if (key.equals("border")) {
if (value.equals("none")) {
setBackgroundResource(0);
} else {
GradientDrawable gd = createBackground();
gd.setStroke(1, Color.parseColor(value));
}
} else if (key.equals("border-radius")) {
final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (Integer.parseInt(value) * scale + 0.5f);
GradientDrawable gd = createBackground();
gd.setCornerRadius(pixels);
} else if (key.equals("white-space")) {
boolean single = false;
if (value.equals("nowrap")) single = true;
setSingleLine(single);
} else if (key.equals("color")) {
setTextColor(Color.parseColor(value));
} else if (key.equals("background-color")) {
setBackgroundColor(Color.parseColor(value));
} else if (key.equals("padding-top")) {
setPadding(getPaddingLeft(), Integer.parseInt(value), getPaddingRight(), getPaddingBottom());
} else if (key.equals("padding-bottom")) {
setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), Integer.parseInt(value));
} else if (key.equals("padding-left")) {
setPadding(Integer.parseInt(value), getPaddingTop(), getPaddingRight(), getPaddingBottom());
} else if (key.equals("padding-right")) {
setPadding(getPaddingLeft(), getPaddingTop(), Integer.parseInt(value), getPaddingBottom());
} else if (key.equals("margin-right")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.rightMargin = Integer.parseInt(value);
setLayoutParams(params);
} else if (key.equals("margin-left")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.leftMargin = Integer.parseInt(value);
setLayoutParams(params);
} else if (key.equals("margin-top")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.topMargin = Integer.parseInt(value);
setLayoutParams(params);
} else if (key.equals("margin-bottom")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.bottomMargin = Integer.parseInt(value);
setLayoutParams(params);
} else if (key.equals("animation")) {
if (value.equals("rotate")) {
RotateAnimation r = new RotateAnimation(-5f, 5f,50,50);
r.setDuration(100);
r.setRepeatCount(10);
r.setRepeatMode(RotateAnimation.REVERSE);
animation = r;
}
}
}
@Override
public void setError(boolean hasError, String errorText) { }
@Override
public void onScreenOrientationChange(boolean isLandscape) {
// TODO Auto-generated method stub
}
@Override
public void addData(String text, int row, int column, int sheet) {
System.out.println("FWButton couldn't handle command");
}
@Override
public void setViewVisibility(boolean visibility) {
if (visibility){
this.setVisibility(VISIBLE);
} else {
this.setVisibility(INVISIBLE);
}
}
@Override
public void clear() {
System.out.println("couldn't handle command");
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
@Override
public void addColumn(String text, int columnType) {
// TODO Auto-generated method stub
}
@Override
public void reshape(int value, int size) {
// TODO Auto-generated method stub
}
@Override
public void setImage(byte[] bytes, int width, int height, Config config) {
// TODO Auto-generated method stub
}
@Override
public void reshape(int size) {
// TODO Auto-generated method stub
}
} |
package com.sometrik.framework;
import com.sometrik.framework.NativeCommand.Selector;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.Layout;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FWDialog extends Dialog implements NativeCommandHandler {
private FrameWork frame;
private LinearLayout baseView;
private int id;
private ViewStyleManager normalStyle, activeStyle, currentStyle;
private FWTextView titleView;
public FWDialog(final FrameWork frame, final int id) {
super(frame);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.frame = frame;
this.id = id;
baseView = new LinearLayout(frame);
baseView.setOrientation(LinearLayout.VERTICAL);
setContentView(baseView);
LayoutParams params = getWindow().getAttributes();
params.height = LayoutParams.WRAP_CONTENT;
params.width = LayoutParams.MATCH_PARENT;
getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
final float scale = getContext().getResources().getDisplayMetrics().density;
this.normalStyle = currentStyle = new ViewStyleManager(frame.bitmapCache, scale, true);
this.activeStyle = new ViewStyleManager(frame.bitmapCache, scale, false);
titleView = new FWTextView(frame, false);
titleView.setStyle(Selector.NORMAL, "background-color", "#ffffff");
titleView.setStyle(Selector.NORMAL, "width", "match-parent");
titleView.setStyle(Selector.NORMAL, "gravity", "center-horizontal");
titleView.setStyle(Selector.NORMAL, "height", "wrap-content");
titleView.setStyle(Selector.NORMAL, "font-size", "24");
titleView.setStyle(Selector.NORMAL, "padding-top", "12");
titleView.setStyle(Selector.NORMAL, "padding-bottom", "12");
titleView.setStyle(Selector.NORMAL, "font-weight", "bold");
titleView.setStyle(Selector.NORMAL, "padding-left", "14");
titleView.setStyle(Selector.NORMAL, "color", "#c1272d");
baseView.addView(titleView);
LinearLayout dividerView = new LinearLayout(frame);
LinearLayout.LayoutParams dividerParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 5);
dividerView.setBackgroundColor(Color.parseColor("#c1272d"));
dividerView.setLayoutParams(dividerParams);
baseView.addView(dividerView);
this.setOnCancelListener(new OnCancelListener(){
@Override
public void onCancel(DialogInterface arg0) {
frame.intChangedEvent(id, 0, 0);
}
});
show();
}
public View getContentView() {
return baseView;
}
@Override
public void onScreenOrientationChange(boolean isLandscape) {
}
@Override
public void addChild(View view) {
baseView.addView(view);
}
@Override
public void addOption(int optionId, String text) {
System.out.println("FWDialog couldn't handle command");
}
@Override
public void addData(String text, int row, int column, int sheet) {
System.out.println("FWDialog couldn't handle command");
}
@Override
public void setValue(String v) {
titleView.setText(v);
}
@Override
public void setValue(int v) { }
@Override
public void setViewVisibility(boolean visible) {
if (visible) {
show();
} else {
dismiss();
}
}
@Override
public void setStyle(Selector selector, String key, String value) {
if (selector == Selector.NORMAL) {
normalStyle.setStyle(key, value);
if (normalStyle == currentStyle) normalStyle.apply(this);
} else if (selector == Selector.ACTIVE) {
activeStyle.setStyle(key, value);
if (activeStyle == currentStyle) activeStyle.apply(this);
}
}
@Override
public void setError(boolean hasError, String errorText) { }
@Override
public void clear() {
dismiss();
}
@Override
public int getElementId() {
return id;
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
@Override
public void addColumn(String text, int columnType) {
// TODO Auto-generated method stub
}
@Override
public void reshape(int value, int size) {
// TODO Auto-generated method stub
}
@Override
public void setBitmap(Bitmap bitmap) { }
@Override
public void reshape(int size) {
// TODO Auto-generated method stub
}
@Override
public void deinitialize() {
dismiss();
}
@Override
public void addImageUrl(String url, int width, int height) {
// TODO Auto-generated method stub
}
} |
package com.sometrik.framework;
import java.util.ArrayList;
import java.util.Iterator;
import com.sometrik.framework.NativeCommand.Selector;
import android.graphics.Bitmap;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
public class FWLayout extends LinearLayout implements NativeCommandHandler {
private FrameWork frame;
private ViewStyleManager normalStyle, activeStyle, currentStyle;
public FWLayout(FrameWork frameWork, int id) {
super(frameWork);
this.frame = frameWork;
this.setId(id);
this.setFocusable(false);
this.setClickable(false);
final float scale = getContext().getResources().getDisplayMetrics().density;
this.normalStyle = currentStyle = new ViewStyleManager(frame.bitmapCache, scale, true);
this.activeStyle = new ViewStyleManager(frame.bitmapCache, scale, false);
}
@Override
public int getElementId() {
return getId();
}
@Override
public void addChild(final View view) {
addView(view);
}
@Override
public void addOption(int optionId, String text) { }
@Override
public void setValue(String v) { }
@Override
public void setValue(int v) { }
@Override
public void setStyle(Selector selector, String key, String value) {
if (selector == Selector.NORMAL) {
normalStyle.setStyle(key, value);
} else if (selector == Selector.ACTIVE) {
activeStyle.setStyle(key, value);
}
if (key.equals("frame")) {
if (value.equals("light")) {
this.setBackgroundDrawable(frame.getResources().getDrawable(android.R.drawable.dialog_holo_light_frame));
// this.setDividerDrawable(frame.getResources().getDrawable(android.R.drawable.divider_horizontal_bright));
} else if (value.equals("dark")) {
this.setBackgroundDrawable(frame.getResources().getDrawable(android.R.drawable.alert_light_frame));
}
} else if (key.equals("divider")) {
if (value.equals("middle")) {
// this.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
} else if (value.equals("end")) {
// this.setShowDividers(LinearLayout.SHOW_DIVIDER_END);
} else if (value.equals("beginning")) {
// this.setShowDividers(LinearLayout.SHOW_DIVIDER_BEGINNING);
}
}
}
@Override
public void applyStyles() {
currentStyle.apply(this);
}
@Override
public void setError(boolean hasError, String errorText) { }
@Override
public void onScreenOrientationChange(boolean isLandscape) {
invalidate();
}
@Override
public void addData(String text, int row, int column, int sheet) { }
@Override
public void setViewVisibility(boolean visibility) {
if (visibility) {
this.setVisibility(VISIBLE);
} else {
this.setVisibility(GONE);
}
}
@Override
public void clear() { }
@Override
public void flush() { }
@Override
public void addColumn(String text, int columnType) { }
@Override
public void reshape(int value, int size) { }
@Override
public void setBitmap(Bitmap bitmap) { }
@Override
public void reshape(int size) { }
@Override
public void deinitialize() { }
@Override
public void addImageUrl(String url, int width, int height) { }
} |
package com.sometrik.framework;
import java.util.Map.Entry;
import java.util.TreeMap;
import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class FWPicker extends Spinner implements NativeCommandHandler {
private Context context;
private ArrayAdapter<String> adapter;
private TreeMap<Long, String> valueMap;
private final int id;
private native void pickerOptionSelected(double timestamp, int id, int position);
public FWPicker(Context context) {
super(context);
adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item);
valueMap = new TreeMap<Long, String>();
id = getId();
this.context = context;
setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
pickerOptionSelected(System.currentTimeMillis() / 1000.0, id, position);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
public void handleCommand(NativeCommand command) {
}
@Override
public void showView() {
System.out.println("Picker couldn't handle showView");
}
@Override
public int getElementId() {
return getId();
}
@Override
public void addChild(View view) {
System.out.println("Picker couldn't handle addChild");
//TODO
}
@Override
public void addOption(long optionId, String text) {
adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item);
valueMap.put(optionId, text);
for(Entry<Long, String> entry : valueMap.entrySet()) {
adapter.add(entry.getValue());
}
setAdapter(adapter);
}
@Override
public void removeChild(int id) {
System.out.println("Picker couldn't handle remove element");
// TODO Auto-generated method stub
}
} |
public class Prova {
public static void main(String[] args) {
System.out.println(42);
System.out.println("Prova di modifica");
}
} |
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;
public class Racun {
int tip;
final int prvaStevilka;
final int drugaStevilka;
final int rezultat;
String vStringu;
String zgodovina;
ArrayList<Integer> tipiRacunov;
public Racun(int zah, ArrayList<Integer> tipiRacunov){
tip = nakljucniElement(tipiRacunov);
if (tip == 1){
prvaStevilka = randInt(10, 10 + 10*zah);
drugaStevilka = randInt(10, 10 + 10*zah);
vStringu = prvaStevilka + " + " + drugaStevilka + " = ";
rezultat = prvaStevilka + drugaStevilka;
zgodovina = vStringu + rezultat;
}
else if (tip == 2){
prvaStevilka = randInt(0, 10*zah);
drugaStevilka = randInt(0, 10*zah);
vStringu = prvaStevilka + " - " + drugaStevilka + " = ";
rezultat = prvaStevilka - drugaStevilka;
zgodovina = vStringu + rezultat;
}
else if (tip == 3){
prvaStevilka = randInt(3, 2*zah);
drugaStevilka = randInt(3, 2*zah);
vStringu = prvaStevilka + " * " + drugaStevilka + " = ";
rezultat = prvaStevilka * drugaStevilka;
zgodovina = vStringu + rezultat;
}
else if (tip == 4){
prvaStevilka = randInt(10, 10 + 2*zah);
drugaStevilka = randInt(1,2*zah);
vStringu = prvaStevilka*drugaStevilka + " / " + prvaStevilka + " = ";
rezultat = drugaStevilka;
zgodovina = vStringu + rezultat;
}
else {
drugaStevilka = randInt(0,2*zah);
prvaStevilka = randInt(1,2*zah);
vStringu = "__ / " + prvaStevilka + " = " + drugaStevilka + " ";
rezultat = prvaStevilka*drugaStevilka;
zgodovina = rezultat + " / " + prvaStevilka + " = " + drugaStevilka + " ";
}
}
@Override
public String toString() {
return "Racun [prvaStevilka=" + prvaStevilka + ", drugaStevilka=" + drugaStevilka
+ ", rezultat=" + rezultat + "]";
}
private static int nakljucniElement(ArrayList<Integer> tipi){
int rnd = randInt(0, tipi.size() - 1);
return tipi.get(rnd);
}
private static int randInt(int min, int max) {
return ThreadLocalRandom.current().nextInt(min, max + 1);
}
} |
package cc.arduino.view.findreplace;
import processing.app.Base;
import processing.app.Editor;
import processing.app.helpers.OSUtils;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import java.util.Map;
import static processing.app.I18n.tr;
public class FindReplace extends javax.swing.JFrame {
private static final String FIND_TEXT = "findText";
private static final String REPLACE_TEXT = "replaceText";
private static final String IGNORE_CASE = "ignoreCase";
private static final String SEARCH_ALL_FILES = "searchAllFiles";
private static final String WRAP_AROUND = "wrapAround";
private final Editor editor;
public FindReplace(Editor editor, Map<String, Object> state) {
this.editor = editor;
initComponents();
if (OSUtils.isMacOS()) {
buttonsContainer.removeAll();
buttonsContainer.add(replaceAllButton);
buttonsContainer.add(replaceButton);
buttonsContainer.add(replaceFindButton);
buttonsContainer.add(previousButton);
buttonsContainer.add(findButton);
}
Base.registerWindowCloseKeys(getRootPane(), e -> {
setVisible(false);
Base.FIND_DIALOG_STATE = findDialogState();
});
Base.setIcon(this);
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
findField.requestFocusInWindow();
findField.selectAll();
}
});
restoreFindDialogState(state);
}
@Override
public void setVisible(boolean b) {
getRootPane().setDefaultButton(findButton);
super.setVisible(b);
}
private Map<String, Object> findDialogState() {
Map<String, Object> state = new HashMap<>();
state.put(FIND_TEXT, findField.getText());
state.put(REPLACE_TEXT, replaceField.getText());
state.put(IGNORE_CASE, ignoreCaseBox.isSelected());
state.put(WRAP_AROUND, wrapAroundBox.isSelected());
state.put(SEARCH_ALL_FILES, searchAllFilesBox.isSelected());
return state;
}
private void restoreFindDialogState(Map<String, Object> state) {
if (state.containsKey(FIND_TEXT)) {
findField.setText((String) state.get(FIND_TEXT));
}
if (state.containsKey(REPLACE_TEXT)) {
replaceField.setText((String) state.get(REPLACE_TEXT));
}
if (state.containsKey(IGNORE_CASE)) {
ignoreCaseBox.setSelected((Boolean) state.get(IGNORE_CASE));
}
if (state.containsKey(SEARCH_ALL_FILES)) {
searchAllFilesBox.setSelected((Boolean) state.get(SEARCH_ALL_FILES));
}
if (state.containsKey(WRAP_AROUND)) {
wrapAroundBox.setSelected((Boolean) state.get(WRAP_AROUND));
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
javax.swing.JLabel findLabel = new javax.swing.JLabel();
findField = new javax.swing.JTextField();
javax.swing.JLabel replaceLabel = new javax.swing.JLabel();
replaceField = new javax.swing.JTextField();
ignoreCaseBox = new javax.swing.JCheckBox();
wrapAroundBox = new javax.swing.JCheckBox();
searchAllFilesBox = new javax.swing.JCheckBox();
buttonsContainer = new javax.swing.JPanel();
findButton = new javax.swing.JButton();
previousButton = new javax.swing.JButton();
replaceFindButton = new javax.swing.JButton();
replaceButton = new javax.swing.JButton();
replaceAllButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(tr("Find"));
setResizable(false);
findLabel.setText(tr("Find:"));
findField.setColumns(20);
replaceLabel.setText(tr("Replace with:"));
replaceField.setColumns(20);
ignoreCaseBox.setSelected(true);
ignoreCaseBox.setText(tr("Ignore Case"));
wrapAroundBox.setSelected(true);
wrapAroundBox.setText(tr("Wrap Around"));
searchAllFilesBox.setText(tr("Search all Sketch Tabs"));
findButton.setText(tr("Find"));
findButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
findButtonActionPerformed(evt);
}
});
buttonsContainer.add(findButton);
previousButton.setText(tr("Previous"));
previousButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
previousButtonActionPerformed(evt);
}
});
buttonsContainer.add(previousButton);
replaceFindButton.setText(tr("Replace & Find"));
replaceFindButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
replaceFindButtonActionPerformed(evt);
}
});
buttonsContainer.add(replaceFindButton);
replaceButton.setText(tr("Replace"));
replaceButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
replaceButtonActionPerformed(evt);
}
});
buttonsContainer.add(replaceButton);
replaceAllButton.setText(tr("Replace All"));
replaceAllButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
replaceAllButtonActionPerformed(evt);
}
});
buttonsContainer.add(replaceAllButton);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(replaceLabel)
.addComponent(findLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(findField)
.addComponent(replaceField)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(searchAllFilesBox)
.addComponent(wrapAroundBox)
.addComponent(ignoreCaseBox))
.addGap(0, 0, Short.MAX_VALUE))))
.addComponent(buttonsContainer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(findLabel)
.addComponent(findField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(replaceLabel)
.addComponent(replaceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ignoreCaseBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(wrapAroundBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(searchAllFilesBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonsContainer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void findButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_findButtonActionPerformed
findNext();
}//GEN-LAST:event_findButtonActionPerformed
private void previousButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_previousButtonActionPerformed
findPrevious();
}//GEN-LAST:event_previousButtonActionPerformed
private void replaceFindButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_replaceFindButtonActionPerformed
replaceAndFindNext();
}//GEN-LAST:event_replaceFindButtonActionPerformed
private void replaceButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_replaceButtonActionPerformed
replace();
}//GEN-LAST:event_replaceButtonActionPerformed
private void replaceAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_replaceAllButtonActionPerformed
replaceAll();
}//GEN-LAST:event_replaceAllButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonsContainer;
private javax.swing.JButton findButton;
private javax.swing.JTextField findField;
private javax.swing.JCheckBox ignoreCaseBox;
private javax.swing.JButton previousButton;
private javax.swing.JButton replaceAllButton;
private javax.swing.JButton replaceButton;
private javax.swing.JTextField replaceField;
private javax.swing.JButton replaceFindButton;
private javax.swing.JCheckBox searchAllFilesBox;
private javax.swing.JCheckBox wrapAroundBox;
// End of variables declaration//GEN-END:variables
private boolean find(boolean wrap, boolean backwards, boolean searchTabs, int originTab) {
String search = findField.getText();
if (search.length() == 0) {
return false;
}
String text = editor.getCurrentTab().getText();
if (ignoreCaseBox.isSelected()) {
search = search.toLowerCase();
text = text.toLowerCase();
}
int nextIndex;
if (!backwards) {
// int selectionStart = editor.textarea.getSelectionStart();
int selectionEnd = editor.getCurrentTab().getSelectionStop();
nextIndex = text.indexOf(search, selectionEnd);
} else {
// int selectionStart = editor.textarea.getSelectionStart();
int selectionStart = editor.getCurrentTab().getSelectionStart() - 1;
if (selectionStart >= 0) {
nextIndex = text.lastIndexOf(search, selectionStart);
} else {
nextIndex = -1;
}
}
boolean wrapNeeded = false;
if (wrap && nextIndex == -1) {
// if wrapping, a second chance is ok, start from the end
wrapNeeded = true;
}
if (nextIndex == -1) {
// Nothing found on this tab: Search other tabs if required
if (searchTabs) {
int numTabs = editor.getTabs().size();
if (numTabs > 1) {
int realCurrentTab = editor.getCurrentTabIndex();
if (originTab != realCurrentTab) {
if (originTab < 0) {
originTab = realCurrentTab;
}
if (!wrap) {
if ((!backwards && realCurrentTab + 1 >= numTabs)
|| (backwards && realCurrentTab - 1 < 0)) {
return false; // Can't continue without wrap
}
}
if (backwards) {
editor.selectPrevTab();
this.setVisible(true);
int l = editor.getCurrentTab().getText().length() - 1;
editor.getCurrentTab().setSelection(l, l);
} else {
editor.selectNextTab();
this.setVisible(true);
editor.getCurrentTab().setSelection(0, 0);
}
return find(wrap, backwards, true, originTab);
}
}
}
if (wrapNeeded) {
nextIndex = backwards ? text.lastIndexOf(search) : text.indexOf(search, 0);
}
}
if (nextIndex != -1) {
editor.getCurrentTab().getTextArea().getFoldManager().ensureOffsetNotInClosedFold(nextIndex);
editor.getCurrentTab().setSelection(nextIndex, nextIndex + search.length());
return true;
}
return false;
}
/**
* Replace the current selection with whatever's in the replacement text
* field.
*/
private void replace() {
if (findField.getText().length() == 0) {
return;
}
int newpos = editor.getCurrentTab().getSelectionStart() - findField.getText().length();
if (newpos < 0) {
newpos = 0;
}
editor.getCurrentTab().setSelection(newpos, newpos);
boolean foundAtLeastOne = false;
if (find(false, false, searchAllFilesBox.isSelected(), -1)) {
foundAtLeastOne = true;
editor.getCurrentTab().setSelectedText(replaceField.getText());
}
if (!foundAtLeastOne) {
Toolkit.getDefaultToolkit().beep();
}
}
/**
* Replace the current selection with whatever's in the replacement text
* field, and then find the next match
*/
private void replaceAndFindNext() {
replace();
findNext();
}
/**
* Replace everything that matches by doing find and replace alternately until
* nothing more found.
*/
private void replaceAll() {
if (findField.getText().length() == 0) {
return;
}
if (searchAllFilesBox.isSelected()) {
editor.selectTab(0); // select the first tab
}
editor.getCurrentTab().setSelection(0, 0); // move to the beginning
boolean foundAtLeastOne = false;
while (true) {
if (find(false, false, searchAllFilesBox.isSelected(), -1)) {
foundAtLeastOne = true;
editor.getCurrentTab().setSelectedText(replaceField.getText());
} else {
break;
}
}
if (!foundAtLeastOne) {
Toolkit.getDefaultToolkit().beep();
}
}
public void findNext() {
if (!find(wrapAroundBox.isSelected(), false, searchAllFilesBox.isSelected(), -1)) {
Toolkit.getDefaultToolkit().beep();
}
}
public void findPrevious() {
if (!find(wrapAroundBox.isSelected(), true, searchAllFilesBox.isSelected(), -1)) {
Toolkit.getDefaultToolkit().beep();
}
}
public void setFindText(String text) {
if (text == null) {
return;
}
findField.setText(text);
}
} |
package org.stepic.droid.model;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import com.yandex.metrica.YandexMetrica;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.stepic.droid.R;
import org.stepic.droid.base.MainApplication;
import org.stepic.droid.configuration.IConfig;
import java.io.Serializable;
import java.util.Locale;
import javax.inject.Inject;
public class Course implements Serializable, Parcelable {
@Inject
transient IConfig mConfig;
private transient Context mContext;
private transient DateTimeFormatter mFormatForView;
private long id;
private String summary;
private String workload;
private String cover;
private String intro;
private String course_format;
private String target_audience;
private String certificate_footer;
private String certificate_cover_org;
private long[] instructors;
private long[] sections;
private String certificate;
private String requirements;
private String description;
private int total_units;
private int enrollment;
private long owner;
private boolean is_contest;
private boolean is_featured;
private boolean is_spoc;
private boolean is_active;
private String certificate_link;
private String title;
private String begin_date_source;
private String last_deadline;
private String language;
private boolean is_public;
private String slug; //link to ../course/#slug#
private boolean is_cached;
private boolean is_loading;
private Video intro_video;
@Deprecated
public boolean is_loading() {
return is_loading;
}
@Deprecated
public synchronized void setIs_loading(boolean is_loading) {
this.is_loading = is_loading;
}
@Deprecated
public boolean is_cached() {
return is_cached;
}
@Deprecated
public synchronized void setIs_cached(boolean is_cached) {
this.is_cached = is_cached;
}
private transient DateTime mBeginDateTime = null;
private transient DateTime mEndDateTime = null;
private String formatForView = null;
public Course() {
mContext = MainApplication.getAppContext();
MainApplication.component(MainApplication.getAppContext()).inject(this);
mFormatForView = DateTimeFormat
.forPattern(mConfig.getDatePatternForView())
.withZone(DateTimeZone.getDefault())
.withLocale(Locale.getDefault());
}
public String getDateOfCourse() {
if (formatForView != null) return formatForView;
StringBuilder sb = new StringBuilder();
if (begin_date_source == null && last_deadline == null) {
sb.append("");
} else if (last_deadline == null) {
sb.append(mContext.getResources().getString(R.string.begin_date));
sb.append(": ");
try {
sb.append(getPresentOfDate(begin_date_source));
} catch (Throwable throwable) {
YandexMetrica.reportError("present_date_course_begin", throwable);
return "";
}
} else if (begin_date_source != null) {
//both is not null
try {
sb.append(getPresentOfDate(begin_date_source));
sb.append(" - ");
sb.append(getPresentOfDate(last_deadline));
} catch (Throwable throwable) {
YandexMetrica.reportError("present_date_course_last", throwable);
return "";
}
}
formatForView = sb.toString();
return formatForView;
}
private String getPresentOfDate(String dateInISOformat) {
DateTime dateTime = new DateTime(dateInISOformat);
return mFormatForView.print(dateTime);
}
@Nullable
public DateTime getEndDateTime() {
if (mEndDateTime != null)
return mEndDateTime;
if (last_deadline == null) {
mEndDateTime = null; //infinity
} else {
mEndDateTime = new DateTime(last_deadline);
}
return mEndDateTime;
}
@Nullable
public DateTime getBeginDateTime() {
if (mBeginDateTime != null)
return mBeginDateTime;
if (begin_date_source == null) {
mBeginDateTime = null; //infinity
} else {
mBeginDateTime = new DateTime(begin_date_source);
}
return mBeginDateTime;
}
public long getCourseId() {
return id;
}
public String getSummary() {
return summary;
}
public String getWorkload() {
return workload;
}
public String getCover() {
return cover;
}
public String getIntro() {
return intro;
}
public String getCourse_format() {
return course_format;
}
public String getTarget_audience() {
return target_audience;
}
public String getCertificate_footer() {
return certificate_footer;
}
public String getCertificate_cover_org() {
return certificate_cover_org;
}
public long[] getInstructors() {
return instructors;
}
public String getCertificate() {
return certificate;
}
public String getRequirements() {
return requirements;
}
public String getDescription() {
return description;
}
public int getTotal_units() {
return total_units;
}
public int getEnrollment() {
return enrollment;
}
public boolean is_featured() {
return is_featured;
}
public boolean is_spoc() {
return is_spoc;
}
public String getCertificate_link() {
return certificate_link;
}
public long getOwner() {
return owner;
}
public boolean is_contest() {
return is_contest;
}
public String getLanguage() {
return language;
}
public boolean is_public() {
return is_public;
}
public String getSlug() {
return slug;
}
public String getTitle() {
return title;
}
public void setmFormatForView(DateTimeFormatter mFormatForView) {
this.mFormatForView = mFormatForView;
}
public void setId(long id) {
this.id = id;
}
public void setSummary(String summary) {
this.summary = summary;
}
public void setWorkload(String workload) {
this.workload = workload;
}
public void setCover(String cover) {
this.cover = cover;
}
public void setIntro(String intro) {
this.intro = intro;
}
public void setCourse_format(String course_format) {
this.course_format = course_format;
}
public void setTarget_audience(String target_audience) {
this.target_audience = target_audience;
}
public void setCertificate_footer(String certificate_footer) {
this.certificate_footer = certificate_footer;
}
public void setCertificate_cover_org(String certificate_cover_org) {
this.certificate_cover_org = certificate_cover_org;
}
public void setInstructors(long[] instructors) {
this.instructors = instructors;
}
public void setCertificate(String certificate) {
this.certificate = certificate;
}
public void setRequirements(String requirements) {
this.requirements = requirements;
}
public void setDescription(String description) {
this.description = description;
}
public void setTotal_units(int total_units) {
this.total_units = total_units;
}
public void setEnrollment(int enrollment) {
this.enrollment = enrollment;
}
public void setOwner(long owner) {
this.owner = owner;
}
public void setIs_contest(boolean is_contest) {
this.is_contest = is_contest;
}
public void setIs_featured(boolean is_featured) {
this.is_featured = is_featured;
}
public void setIs_spoc(boolean is_spoc) {
this.is_spoc = is_spoc;
}
public void setIs_active(boolean is_active) {
this.is_active = is_active;
}
public void setCertificate_link(String certificate_link) {
this.certificate_link = certificate_link;
}
public void setTitle(String title) {
this.title = title;
}
public void setBegin_date_source(String begin_date_source) {
this.begin_date_source = begin_date_source;
}
public void setLast_deadline(String last_deadline) {
this.last_deadline = last_deadline;
}
public void setLanguage(String language) {
this.language = language;
}
public void setIs_public(boolean is_public) {
this.is_public = is_public;
}
public void setSlug(String slug) {
this.slug = slug;
}
public void setmBeginDateTime(DateTime mBeginDateTime) {
this.mBeginDateTime = mBeginDateTime;
}
public void setmEndDateTime(DateTime mEndDateTime) {
this.mEndDateTime = mEndDateTime;
}
public void setFormatForView(String formatForView) {
this.formatForView = formatForView;
}
public String getBegin_date_source() {
return begin_date_source;
}
public String getLast_deadline() {
return last_deadline;
}
public long[] getSections() {
return sections;
}
public void setSections(long[] sections) {
this.sections = sections;
}
public Video getIntro_video() {
return intro_video;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.id);
dest.writeString(this.summary);
dest.writeString(this.workload);
dest.writeString(this.cover);
dest.writeString(this.intro);
dest.writeString(this.course_format);
dest.writeString(this.target_audience);
dest.writeString(this.certificate_footer);
dest.writeString(this.certificate_cover_org);
dest.writeLongArray(this.instructors);
dest.writeLongArray(this.sections);
dest.writeString(this.certificate);
dest.writeString(this.requirements);
dest.writeString(this.description);
dest.writeInt(this.total_units);
dest.writeInt(this.enrollment);
dest.writeLong(this.owner);
dest.writeByte(is_contest ? (byte) 1 : (byte) 0);
dest.writeByte(is_featured ? (byte) 1 : (byte) 0);
dest.writeByte(is_spoc ? (byte) 1 : (byte) 0);
dest.writeByte(is_active ? (byte) 1 : (byte) 0);
dest.writeString(this.certificate_link);
dest.writeString(this.title);
dest.writeString(this.begin_date_source);
dest.writeString(this.last_deadline);
dest.writeString(this.language);
dest.writeByte(is_public ? (byte) 1 : (byte) 0);
dest.writeString(this.slug);
dest.writeByte(is_cached ? (byte) 1 : (byte) 0);
dest.writeByte(is_loading ? (byte) 1 : (byte) 0);
dest.writeParcelable(this.intro_video, 0);
dest.writeSerializable(this.mBeginDateTime);
dest.writeSerializable(this.mEndDateTime);
dest.writeString(this.formatForView);
}
protected Course(Parcel in) {
this.id = in.readLong();
this.summary = in.readString();
this.workload = in.readString();
this.cover = in.readString();
this.intro = in.readString();
this.course_format = in.readString();
this.target_audience = in.readString();
this.certificate_footer = in.readString();
this.certificate_cover_org = in.readString();
this.instructors = in.createLongArray();
this.sections = in.createLongArray();
this.certificate = in.readString();
this.requirements = in.readString();
this.description = in.readString();
this.total_units = in.readInt();
this.enrollment = in.readInt();
this.owner = in.readLong();
this.is_contest = in.readByte() != 0;
this.is_featured = in.readByte() != 0;
this.is_spoc = in.readByte() != 0;
this.is_active = in.readByte() != 0;
this.certificate_link = in.readString();
this.title = in.readString();
this.begin_date_source = in.readString();
this.last_deadline = in.readString();
this.language = in.readString();
this.is_public = in.readByte() != 0;
this.slug = in.readString();
this.is_cached = in.readByte() != 0;
this.is_loading = in.readByte() != 0;
this.intro_video = in.readParcelable(Video.class.getClassLoader());
this.mBeginDateTime = (DateTime) in.readSerializable();
this.mEndDateTime = (DateTime) in.readSerializable();
this.formatForView = in.readString();
}
public static final Creator<Course> CREATOR = new Creator<Course>() {
public Course createFromParcel(Parcel source) {
return new Course(source);
}
public Course[] newArray(int size) {
return new Course[size];
}
};
} |
import java.awt.*;
public class Stone {
StoneTypes type;
private boolean[][] pattern;
Point position = null;
public Stone() {
this(StoneType.random());
}
public Stone(StoneTypes type) {
this.type = type;
pattern = StoneType.getPattern(type);
}
public Stone(StoneTypes type, Point position) {
this.type = type;
pattern = StoneType.getPattern(type);
this.position = position;
}
public void rotate() {
boolean[][] newpattern = new boolean[4][4];
for (int x = 0; x < pattern.length; x++) {
for (int y = 0; y < pattern[x].length; y++)
newpattern[x][3 - y] = pattern[y][x];
}
pattern = newpattern;
}
public Point dimension(){
Point p = new Point(position);
p.translate(pattern[0].length, pattern.length);
return p;
}
public boolean[][] getPattern() {
return pattern;
}
public String getPatternString() {
StringBuilder s = new StringBuilder();
for (boolean[] row : pattern) {
for (boolean field : row)
s.append(field ? "x" : "_");
s.append("\n");
}
return s.toString();
}
@Override
public String toString() {
return StoneType.toString(type);
}
} |
@SuppressWarnings("unused")
public class Tocka {
private double x,y,z;
public Tocka(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
} |
import java.util.Set;
public class GoTerm {
private String id;
private String name;
private String namespace;
private Set<String> isa;
private Set<String> children;
public GoTerm(String id, String name, String namespace, Set<String> isa, Set<String> children){
this.id = id;
this.name = name;
this.namespace = namespace;
this.isa = isa;
this.children = children;
}
public void setChildren(Set<String> children){
this.children=children;
}
public String getId(){
return id;
}
public String getName(){
return name;
}
public String getNamespace(){
return namespace;
}
public Set<String> getParents(){
return isa;
}
public Set<String> getChildren(){
return children;
}
} |
import java.util.HashSet;
import java.util.Set;
public class GoTerm {
private String id;
private String name;
private String namespace;
private Set<GoTerm> parents = new HashSet<GoTerm>();
private Set<GoTerm> children = new HashSet<GoTerm>();
private Set<String> genes = new HashSet<String>();
public GoTerm(String id, String name, String namespace){
this.id = id;
this.name = name;
this.namespace = namespace;
}
public void addGene(String gen){
this.genes.add(gen);
}
public Set<String> getGenes(){
return genes;
}
public void addChild(GoTerm child){
this.children.add(child);
}
public void addParent(GoTerm parent){
this.parents.add(parent);
}
public String getId(){
return id;
}
public String getName(){
return name;
}
public String getNamespace(){
return namespace;
}
public Set<GoTerm> getParents(){
return parents;
}
public Set<GoTerm> getChildren(){
return children;
}
public boolean hasParents(){
return !parents.isEmpty();
}
} |
package robot1;
/**
* still in development :-)
* @author christopher-rehm
*/
import java.util.TimerTask;
public class Sight extends TimerTask {
int counter = 0;
int counter2 = 0;
@Override
public void run() {
// The logic of task/job that is going to be executed.
// Here we are going to print the following string value
System.out.format("in Sight This is being printed every 1 sec. %d%n ", counter);
counter = counter + 1;
for(int i=1; i<1000000; i++){
counter2++;
}
}
} |
// Block Chain should maintain only limited block nodes to satisfy the functions
// You should not have all the blocks added to the block chain in memory
// as it would cause a memory overflow.
import java.util.ArrayList;
import java.util.HashMap;
public class BlockChain {
private class BlockNode {
public Block b;
public BlockNode parent;
public ArrayList<BlockNode> children;
public int height;
// utxo pool for making a new block on top of this block
private UTXOPool uPool;
public BlockNode(Block b, BlockNode parent, UTXOPool uPool) {
this.b = b;
this.parent = parent;
children = new ArrayList<>();
this.uPool = uPool;
if (parent != null) {
height = parent.height + 1;
parent.children.add(this);
} else {
height = 1;
}
}
public UTXOPool getUTXOPoolCopy() {
return new UTXOPool(uPool);
}
}
//BlockNode blockChain;
private HashMap<ByteArrayWrapper, BlockNode> blockChain;
private BlockNode maxHeightNode;
private TransactionPool txPool;
public static final int CUT_OFF_AGE = 10;
/**
* create an empty block chain with just a genesis block. Assume {@code genesisBlock} is a valid
* block
*/
public BlockChain(Block genesisBlock) {
blockChain = new HashMap<>();
UTXOPool utxoPool = new UTXOPool();
Transaction coinbase = genesisBlock.getCoinbase();
for (int i = 0; i < coinbase.numOutputs(); i++) {
Transaction.Output out = coinbase.getOutput(i);
UTXO utxo = new UTXO(coinbase.getHash(), i);
utxoPool.addUTXO(utxo, out);
}
BlockNode genesisNode = new BlockNode(genesisBlock, null, utxoPool);
blockChain.put(wrap(genesisBlock.getHash()), genesisNode);
txPool = new TransactionPool();
maxHeightNode = genesisNode;
}
/**
* Get the maximum height block
*/
public Block getMaxHeightBlock() {
return maxHeightNode.b;
}
/**
* Get the UTXOPool for mining a new block on top of max height block
*/
public UTXOPool getMaxHeightUTXOPool() {
return maxHeightNode.getUTXOPoolCopy();
}
/**
* Get the transaction pool to mine a new block
*/
public TransactionPool getTransactionPool() {
return txPool;
}
/**
* Add {@code block} to the block chain if it is valid. For validity, all transactions should be
* valid and block should be at {@code height > (maxHeight - CUT_OFF_AGE)}.
* <p>
* <p>
* For example, you can try creating a new block over the genesis block (block height 2) if the
* block chain height is {@code <=
* CUT_OFF_AGE + 1}. As soon as {@code height > CUT_OFF_AGE + 1}, you cannot create a new block
* at height 2.
*
* @return true if block is successfully added
*/
public boolean addBlock(Block block) {
byte[] prevBlockHash = block.getPrevBlockHash();
if (prevBlockHash == null)
return false;
BlockNode parentBlockNode = blockChain.get(wrap(prevBlockHash));
if (parentBlockNode == null) {
return false;
}
TxHandler handler = new TxHandler(parentBlockNode.getUTXOPoolCopy());
Transaction[] txs = block.getTransactions().toArray(new Transaction[0]);
Transaction[] validTxs = handler.handleTxs(txs);
if (validTxs.length != txs.length) {
return false;
}
int proposedHeight = parentBlockNode.height + 1;
if (proposedHeight <= maxHeightNode.height - CUT_OFF_AGE) {
return false;
}
UTXOPool utxoPool = handler.getUTXOPool();
Transaction coinbase = block.getCoinbase();
utxoPool.addUTXO(new UTXO(coinbase.getHash(), 0), coinbase.getOutput(0));
BlockNode node = new BlockNode(block, parentBlockNode, utxoPool);
blockChain.put(wrap(block.getHash()), node);
if (proposedHeight > maxHeightNode.height) {
maxHeightNode = node;
}
return true;
}
/**
* Add a transaction to the transaction pool
*/
public void addTransaction(Transaction tx) {
txPool.addTransaction(tx);
}
private static ByteArrayWrapper wrap(byte[] arr) {
return new ByteArrayWrapper(arr);
}
} |
package ceylon.language;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import com.redhat.ceylon.compiler.java.language.AbstractCallable;
import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor;
import ceylon.language.ArraySequence;
import ceylon.language.Boolean;
import ceylon.language.Iterator;
import ceylon.language.Sequential;
import ceylon.language.empty_;
import ceylon.language.finished_;
public class ArraySequenceTest {
private static ceylon.language.Integer i(int i) {
return ceylon.language.Integer.instance(i);
}
private static ceylon.language.String s(java.lang.String s) {
return ceylon.language.String.instance(s);
}
private static ceylon.language.String[] cs(java.lang.String... jstrings) {
ceylon.language.String[] result = new ceylon.language.String[jstrings.length];
for (int ii = 0; ii < jstrings.length; ii++) {
result[ii] = ceylon.language.String.instance(jstrings[ii]);
}
return result;
}
@SuppressWarnings("rawtypes")
private final Sequential empty = empty_.getEmpty$();
@Test
public void testConstructor() {
try {
ArraySequence.instance(ceylon.language.String.$TypeDescriptor,
cs());
Assert.fail();
} catch (IllegalArgumentException e) {
// checking this is thrown
}
try {
ArraySequence.backedBy$hidden(ceylon.language.String.$TypeDescriptor,
cs("a"), 1, 1);
Assert.fail();
} catch (IllegalArgumentException e) {
// checking this is thrown
}
try {
ArraySequence.backedBy$hidden(ceylon.language.String.$TypeDescriptor,
cs("a"), 0, 0);
Assert.fail();
} catch (IllegalArgumentException e) {
// checking this is thrown
}
ArraySequence.backedBy$hidden(ceylon.language.String.$TypeDescriptor,
cs("a"), 0, 1);
try {
ArraySequence.backedBy$hidden(ceylon.language.String.$TypeDescriptor,
cs("a"), 0, 2);
Assert.fail();
} catch (IllegalArgumentException e) {
// checking this is thrown
}
}
/**
* Returns a list of {@link ArraySequence}s representing
* <code>{ "a", "b", "c" }</code>, but each has a different backing
* array.
*/
Map<java.lang.String, ArraySequence<ceylon.language.String>> abcs() {
Map<java.lang.String, ArraySequence<ceylon.language.String>> result = new LinkedHashMap<java.lang.String, ArraySequence<ceylon.language.String>>();
result.put("{a b c}: ",
ArraySequence.<String>instance(
ceylon.language.String.$TypeDescriptor,
cs("a", "b", "c")));
result.put("{a b c d}, 0, 3: ",
ArraySequence.backedBy$hidden(
ceylon.language.String.$TypeDescriptor,
cs("a", "b", "c", "d"), 0, 3));
result.put("{z a b c}, 1, 3: ",
ArraySequence.backedBy$hidden(
ceylon.language.String.$TypeDescriptor,
cs("z", "a", "b", "c"), 1, 3));
result.put("{z a b c d}, 1, 3: ",
ArraySequence.backedBy$hidden(
ceylon.language.String.$TypeDescriptor,
cs("z", "a", "b", "c", "d"), 1, 3));
return result;
}
/**
* This test is mainly aimed as checking ArraySequence
* accesses the elements of the array correctly, respecting the
* first and length parameters passed to it's ctor.
*/
@Test
public void testBasic() {
for (Map.Entry<java.lang.String, ArraySequence<ceylon.language.String>> abc : abcs().entrySet()) {
java.lang.String description = abc.getKey();
ArraySequence<ceylon.language.String> abc1 = abc.getValue();
Assert.assertFalse(description, abc1.getEmpty());
Assert.assertEquals(description, abc1.getSize(), 3);
Assert.assertEquals(description, abc1.getFirst().value, "a");
Assert.assertEquals(description, abc1.getLast().value, "c");
Assert.assertEquals(description, abc1.getLastIndex().longValue(), 2L);
}
}
@Test
public void testDefines() {
for (Map.Entry<java.lang.String, ArraySequence<ceylon.language.String>> abc : abcs().entrySet()) {
java.lang.String description = abc.getKey();
ArraySequence<ceylon.language.String> abc1 = abc.getValue();
Assert.assertTrue(description, abc1.defines(i(0)));
Assert.assertTrue(description, abc1.defines(i(1)));
Assert.assertTrue(description, abc1.defines(i(2)));
Assert.assertFalse(description, abc1.defines(i(3)));
}
}
@Test
public void testContains() {
for (Map.Entry<java.lang.String, ArraySequence<ceylon.language.String>> abc : abcs().entrySet()) {
java.lang.String description = abc.getKey();
ArraySequence<ceylon.language.String> abc1 = abc.getValue();
Assert.assertTrue(description, abc1.contains(s("a")));
Assert.assertTrue(description, abc1.contains(s("b")));
Assert.assertTrue(description, abc1.contains(s("c")));
Assert.assertFalse(description, abc1.contains(s("d")));
Assert.assertFalse(description, abc1.contains(s("z")));
}
}
@Test
public void testGet() {
for (Map.Entry<java.lang.String, ArraySequence<ceylon.language.String>> abc : abcs().entrySet()) {
java.lang.String description = abc.getKey();
ArraySequence<ceylon.language.String> abc1 = abc.getValue();
Assert.assertEquals(description, s("a"), abc1.get(i(0)));
Assert.assertEquals(description, s("b"), abc1.get(i(1)));
Assert.assertEquals(description, s("c"), abc1.get(i(2)));
Assert.assertEquals(description, null, abc1.get(i(3)));
}
}
@Test
public void testRest() {
for (Map.Entry<java.lang.String, ArraySequence<ceylon.language.String>> abc : abcs().entrySet()) {
java.lang.String description = abc.getKey();
ArraySequence<ceylon.language.String> abc1 = abc.getValue();
final ArraySequence<ceylon.language.String> bc =
ArraySequence.instance(ceylon.language.String.$TypeDescriptor,
cs("b", "c"));
Assert.assertEquals(description, abc1.getRest(), bc);
}
}
@Test
public void testCount() {
for (Map.Entry<java.lang.String, ArraySequence<ceylon.language.String>> abc : abcs().entrySet()) {
java.lang.String description = abc.getKey();
ArraySequence<ceylon.language.String> abc1 = abc.getValue();
Assert.assertEquals(description, 1, abc1.count(equalsPredicate("a")));
Assert.assertEquals(description, 1, abc1.count(equalsPredicate("b")));
Assert.assertEquals(description, 1, abc1.count(equalsPredicate("c")));
Assert.assertEquals(description, 0, abc1.count(equalsPredicate("d")));
Assert.assertEquals(description, 0, abc1.count(equalsPredicate("z")));
}
}
private AbstractCallable<Boolean> equalsPredicate(java.lang.String str) {
final ceylon.language.String toMatch = s(str);
return new AbstractCallable<ceylon.language.Boolean>(Boolean.$TypeDescriptor,
TypeDescriptor.klass(Tuple.class, String.$TypeDescriptor, String.$TypeDescriptor, Empty.$TypeDescriptor),
"") {
public ceylon.language.Boolean $call(java.lang.Object arg0) {
ceylon.language.String argString = (ceylon.language.String)arg0;
return ceylon.language.Boolean.instance(toMatch.equals(argString));
}
};
}
@Test
public void testSort() {
for (Map.Entry<java.lang.String, ArraySequence<ceylon.language.String>> abc : abcs().entrySet()) {
java.lang.String description = abc.getKey();
ArraySequence<ceylon.language.String> abc1 = abc.getValue();
ArraySequence<ceylon.language.String> cba = ArraySequence.instance(ceylon.language.String.$TypeDescriptor,
cs("c", "b", "a"));
AbstractCallable<ceylon.language.Comparison> alphabeticOrder = alphabeticalOrder();
Assert.assertEquals(description, abc1, abc1.sort(alphabeticOrder));
Assert.assertEquals(description, abc1, cba.sort(alphabeticOrder));
}
}
private AbstractCallable<ceylon.language.Comparison> alphabeticalOrder() {
AbstractCallable<ceylon.language.Comparison> alphabeticOrder = new AbstractCallable<ceylon.language.Comparison>(Comparison.$TypeDescriptor,
TypeDescriptor.klass(Tuple.class, String.$TypeDescriptor, String.$TypeDescriptor, TypeDescriptor.klass(Tuple.class, String.$TypeDescriptor, String.$TypeDescriptor, Empty.$TypeDescriptor)),
"") {
public ceylon.language.Comparison $call(java.lang.Object arg0, java.lang.Object arg1) {
ceylon.language.String first = (ceylon.language.String)arg0;
ceylon.language.String second = (ceylon.language.String)arg1;
return first.compare(second);
}
};
return alphabeticOrder;
}
@Test
public void testIterator() {
for (Map.Entry<java.lang.String, ArraySequence<ceylon.language.String>> abc : abcs().entrySet()) {
java.lang.String description = abc.getKey();
ArraySequence<ceylon.language.String> abc1 = abc.getValue();
Iterator<ceylon.language.String> iterator = abc1.iterator();
Assert.assertEquals(description, s("a"), iterator.next());
Assert.assertEquals(description, s("b"), iterator.next());
Assert.assertEquals(description, s("c"), iterator.next());
Assert.assertEquals(description, finished_.getFinished$(), iterator.next());
}
}
@Test
public void testReversed() {
for (Map.Entry<java.lang.String, ArraySequence<ceylon.language.String>> abcs : abcs().entrySet()) {
java.lang.String description = abcs.getKey();
ArraySequence<ceylon.language.String> abc = abcs.getValue();
Assert.assertEquals(description, abc.getReversed().toString(), "[c, b, a]");
ArraySequence<ceylon.language.String> bc = ArraySequence.backedBy$hidden(ceylon.language.String.$TypeDescriptor,
cs("a", "b", "c"), 1, 2);
Assert.assertEquals(description, bc.getReversed().toString(), "[c, b]");
ArraySequence<ceylon.language.String> b = ArraySequence.backedBy$hidden(ceylon.language.String.$TypeDescriptor,
cs("a", "b", "c"), 1, 1);
Assert.assertEquals(description, b.getReversed().toString(), "[b]");
}
}
@Test
public void testSpan() {
ArraySequence<ceylon.language.String> ab = ArraySequence.instance(
ceylon.language.String.$TypeDescriptor,
cs("a", "b"));
ArraySequence<ceylon.language.String> a = ArraySequence.instance(
ceylon.language.String.$TypeDescriptor,
cs("a"));
ArraySequence<ceylon.language.String> bc = ArraySequence.instance(
ceylon.language.String.$TypeDescriptor,
cs("b","c"));
ArraySequence<ceylon.language.String> c = ArraySequence.instance(
ceylon.language.String.$TypeDescriptor,
cs("c"));
for (Map.Entry<java.lang.String, ArraySequence<ceylon.language.String>> abcs : abcs().entrySet()) {
java.lang.String description = abcs.getKey();
ArraySequence<ceylon.language.String> abc = abcs.getValue();
Assert.assertEquals(description, a, abc.span(i(0), i(0)));
Assert.assertEquals(description, ab, abc.span(i(0), i(1)));
Assert.assertEquals(description, abc, abc.span(i(0), i(2)));
Assert.assertEquals(description, abc, abc.span(i(0), i(3)));
Assert.assertEquals(description, bc, abc.span(i(1), i(2)));
Assert.assertEquals(description, bc, abc.span(i(1), i(4)));
Assert.assertEquals(description, c, abc.span(i(2), i(2)));
Assert.assertEquals(description, c, abc.span(i(2), i(3)));
Assert.assertEquals(description, empty, abc.span(i(3), i(3)));
Assert.assertEquals(description, a, abc.span(i(-1), i(0)));
Assert.assertEquals(description, abc, abc.span(i(-1), i(3)));
// Reversed
Assert.assertEquals(description, a, abc.span(i(0), i(0)));
Assert.assertEquals(description, ab.getReversed(), abc.span(i(1), i(0)));
Assert.assertEquals(description, abc.getReversed(), abc.span(i(2), i(0)));
Assert.assertEquals(description, abc.getReversed(), abc.span(i(3), i(0)));
Assert.assertEquals(description, bc.getReversed(), abc.span(i(2), i(1)));
Assert.assertEquals(description, bc.getReversed(), abc.span(i(4), i(1)));
Assert.assertEquals(description, c, abc.span(i(2), i(2)));
Assert.assertEquals(description, c, abc.span(i(3), i(2)));
Assert.assertEquals(description, empty, abc.span(i(3), i(3)));
Assert.assertEquals(description, a, abc.span(i(0), i(-1)));
Assert.assertEquals(description, abc.getReversed(), abc.span(i(3), i(-1)));
}
}
@Test
public void testSpanFrom() {
ArraySequence<ceylon.language.String> bc = ArraySequence.instance(
ceylon.language.String.$TypeDescriptor,
cs("b","c"));
ArraySequence<ceylon.language.String> c = ArraySequence.instance(
ceylon.language.String.$TypeDescriptor,
cs("c"));
for (Map.Entry<java.lang.String, ArraySequence<ceylon.language.String>> abcs : abcs().entrySet()) {
java.lang.String description = abcs.getKey();
ArraySequence<ceylon.language.String> abc = abcs.getValue();
Assert.assertEquals(description, abc, abc.spanFrom(i(-1)));
Assert.assertEquals(description, abc, abc.spanFrom(i(0)));
Assert.assertEquals(description, bc, abc.spanFrom(i(1)));
Assert.assertEquals(description, c, abc.spanFrom(i(2)));
Assert.assertEquals(description, empty, abc.spanFrom(i(3)));
}
}
@Test
public void testSpanTo() {
ArraySequence<ceylon.language.String> ab = ArraySequence.instance(ceylon.language.String.$TypeDescriptor,
cs("a", "b"));
ArraySequence<ceylon.language.String> a = ArraySequence.instance(ceylon.language.String.$TypeDescriptor,
cs("a"));
for (Map.Entry<java.lang.String, ArraySequence<ceylon.language.String>> abcs : abcs().entrySet()) {
java.lang.String description = abcs.getKey();
ArraySequence<ceylon.language.String> abc = abcs.getValue();
Assert.assertEquals(description, abc, abc.spanTo(i(3)));
Assert.assertEquals(description, abc, abc.spanTo(i(2)));
Assert.assertEquals(description, ab, abc.spanTo(i(1)));
Assert.assertEquals(description, a, abc.spanTo(i(0)));
Assert.assertEquals(description, empty, abc.spanTo(i(-1)));
}
}
@Test
public void testSegment() {
ArraySequence<ceylon.language.String> ab = ArraySequence.instance(
ceylon.language.String.$TypeDescriptor,
cs("a", "b"));
ArraySequence<ceylon.language.String> a = ArraySequence.instance(
ceylon.language.String.$TypeDescriptor,
cs("a"));
ArraySequence<ceylon.language.String> b = ArraySequence.instance(
ceylon.language.String.$TypeDescriptor,
cs("b"));
ArraySequence<ceylon.language.String> bc = ArraySequence.instance(
ceylon.language.String.$TypeDescriptor,
cs("b","c"));
ArraySequence<ceylon.language.String> c = ArraySequence.instance(
ceylon.language.String.$TypeDescriptor,
cs("c"));
for (Map.Entry<java.lang.String, ArraySequence<ceylon.language.String>> abcs : abcs().entrySet()) {
java.lang.String description = abcs.getKey();
ArraySequence<ceylon.language.String> abc = abcs.getValue();
Assert.assertEquals(description, abc, abc.segment(i(-1), 4));
Assert.assertEquals(description, ab, abc.segment(i(-1), 3));
Assert.assertEquals(description, a, abc.segment(i(-1), 2));
Assert.assertEquals(description, empty, abc.segment(i(-1), 1));
Assert.assertEquals(description, empty, abc.segment(i(-1), 0));
Assert.assertEquals(description, abc, abc.segment(i(0), 4));
Assert.assertEquals(description, abc, abc.segment(i(0), 3));
Assert.assertEquals(description, ab, abc.segment(i(0), 2));
Assert.assertEquals(description, a, abc.segment(i(0), 1));
Assert.assertEquals(description, empty, abc.segment(i(0), 0));
Assert.assertEquals(description, bc, abc.segment(i(1), 4));
Assert.assertEquals(description, bc, abc.segment(i(1), 3));
Assert.assertEquals(description, bc, abc.segment(i(1), 2));
Assert.assertEquals(description, b, abc.segment(i(1), 1));
Assert.assertEquals(description, empty, abc.segment(i(1), 0));
Assert.assertEquals(description, c, abc.segment(i(2), 4));
Assert.assertEquals(description, c, abc.segment(i(2), 3));
Assert.assertEquals(description, c, abc.segment(i(2), 2));
Assert.assertEquals(description, c, abc.segment(i(2), 1));
Assert.assertEquals(description, empty, abc.segment(i(2), 0));
Assert.assertEquals(description, empty, abc.segment(i(3), 4));
Assert.assertEquals(description, empty, abc.segment(i(3), 3));
Assert.assertEquals(description, empty, abc.segment(i(3), 2));
Assert.assertEquals(description, empty, abc.segment(i(3), 1));
Assert.assertEquals(description, empty, abc.segment(i(3), 0));
}
}
} |
package com.ecyrd.jspwiki.auth.user;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Properties;
import org.apache.catalina.util.HexUtils;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.NoRequiredPropertyException;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.auth.NoSuchPrincipalException;
import com.ecyrd.jspwiki.auth.WikiPrincipal;
import com.ecyrd.jspwiki.auth.WikiSecurityException;
public abstract class AbstractUserDatabase implements UserDatabase
{
protected static final Logger log = Logger.getLogger( AbstractUserDatabase.class );
protected static final String SHA_PREFIX = "{SHA}";
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#commit()
*/
public abstract void commit() throws WikiSecurityException;
/**
* Looks up and returns the first {@link UserProfile}in the user database
* that whose login name, full name, or wiki name matches the supplied
* string. This method provides a "forgiving" search algorithm for resolving
* principal names when the exact profile attribute that supplied the name
* is unknown.
* @param index the login name, full name, or wiki name
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#find(java.lang.String)
*/
public UserProfile find( String index ) throws NoSuchPrincipalException
{
UserProfile profile = null;
// Try finding by full name
try {
profile = findByFullName( index );
}
catch ( NoSuchPrincipalException e )
{
}
if ( profile != null )
{
return profile;
}
// Try finding by wiki name
try {
profile = findByWikiName( index );
}
catch ( NoSuchPrincipalException e )
{
}
if ( profile != null )
{
return profile;
}
// Try finding by login name
try {
profile = findByLoginName( index );
}
catch ( NoSuchPrincipalException e )
{
}
if ( profile != null )
{
return profile;
}
throw new NoSuchPrincipalException( "Not in database: " + index );
}
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByEmail(java.lang.String)
*/
public abstract UserProfile findByEmail( String index ) throws NoSuchPrincipalException;
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByFullName(java.lang.String)
*/
public abstract UserProfile findByFullName( String index ) throws NoSuchPrincipalException;
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByLoginName(java.lang.String)
*/
public abstract UserProfile findByLoginName( String index ) throws NoSuchPrincipalException;
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByWikiName(java.lang.String)
*/
public abstract UserProfile findByWikiName( String index ) throws NoSuchPrincipalException;
/**
* <p>Looks up the Principals representing a user from the user database. These
* are defined as a set of WikiPrincipals manufactured from the login name,
* full name, and wiki name. If the user database does not contain a user
* with the supplied identifier, throws a {@link NoSuchPrincipalException}.</p>
* <p>When this method creates WikiPrincipals, the Principal containing
* the user's full name is marked as containing the common name (see
* {@link com.ecyrd.jspwiki.auth.WikiPrincipal#WikiPrincipal(String, String)}).
* @param identifier the name of the principal to retrieve; this corresponds to
* value returned by the user profile's
* {@link UserProfile#getLoginName()}method.
* @return the array of Principals representing the user
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#getPrincipals(java.lang.String)
*/
public Principal[] getPrincipals( String identifier ) throws NoSuchPrincipalException
{
try
{
UserProfile profile = findByLoginName( identifier );
ArrayList principals = new ArrayList();
if ( profile.getLoginName() != null && profile.getLoginName().length() > 0 )
{
principals.add( new WikiPrincipal( profile.getLoginName(), WikiPrincipal.LOGIN_NAME ) );
}
if ( profile.getFullname() != null && profile.getFullname().length() > 0 )
{
principals.add( new WikiPrincipal( profile.getFullname(), WikiPrincipal.FULL_NAME ) );
}
if ( profile.getWikiName() != null && profile.getWikiName().length() > 0 )
{
principals.add( new WikiPrincipal( profile.getWikiName(), WikiPrincipal.WIKI_NAME ) );
}
return (Principal[]) principals.toArray( new Principal[principals.size()] );
}
catch( NoSuchPrincipalException e )
{
throw e;
}
}
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#initialize(com.ecyrd.jspwiki.WikiEngine, java.util.Properties)
*/
public abstract void initialize( WikiEngine engine, Properties props ) throws NoRequiredPropertyException;
/**
* Factory method that instantiates a new DefaultUserProfile.
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#newProfile()
*/
public UserProfile newProfile()
{
return new DefaultUserProfile();
}
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#save(com.ecyrd.jspwiki.auth.user.UserProfile)
*/
public abstract void save( UserProfile profile ) throws WikiSecurityException;
/**
* Validates the password for a given user. If the user does not exist in
* the user database, this method always returns <code>false</code>. If
* the user exists, the supplied password is compared to the stored
* password. Note that if the stored password's value starts with
* <code>{SHA}</code>, the supplied password is hashed prior to the
* comparison.
* @param loginName the user's login name
* @param password the user's password (obtained from user input, e.g., a web form)
* @return <code>true</code> if the supplied user password matches the
* stored password
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#validatePassword(java.lang.String,
* java.lang.String)
*/
public boolean validatePassword( String loginName, String password )
{
String hashedPassword = getHash( password );
try
{
UserProfile profile = findByLoginName( loginName );
String storedPassword = profile.getPassword();
if ( storedPassword.startsWith( SHA_PREFIX ) )
{
storedPassword = storedPassword.substring( SHA_PREFIX.length() );
}
return ( hashedPassword.equals( storedPassword ) );
}
catch( NoSuchPrincipalException e )
{
return false;
}
}
/**
* Private method that calculates the SHA-1 hash of a given
* <code>String</code>
* @param text the text to hash
* @return the result hash
*/
protected String getHash( String text )
{
String hash = null;
try
{
MessageDigest md = MessageDigest.getInstance( "SHA" );
md.update( text.getBytes() );
byte digestedBytes[] = md.digest();
hash = HexUtils.convert( digestedBytes );
}
catch( NoSuchAlgorithmException e )
{
log.error( "Error creating SHA password hash:" + e.getMessage() );
hash = text;
}
return hash;
}
} |
package com.ecyrd.jspwiki.providers;
import junit.framework.*;
import java.io.*;
import java.util.*;
import com.ecyrd.jspwiki.*;
public class FileSystemProviderTest extends TestCase
{
FileSystemProvider m_provider;
String m_pagedir;
public FileSystemProviderTest( String s )
{
super( s );
}
public void setUp()
throws Exception
{
m_pagedir = System.getProperties().getProperty("java.io.tmpdir");
Properties props = new Properties();
props.setProperty( FileSystemProvider.PROP_PAGEDIR,
m_pagedir );
m_provider = new FileSystemProvider();
m_provider.initialize( props );
}
public void tearDown()
{
}
public void testScandinavianLetters()
throws Exception
{
try
{
WikiPage page = new WikiPage("Test");
m_provider.putPageText( page, "test" );
File resultfile = new File( m_pagedir, "%C5%E4Test.txt" );
assertTrue("No such file", resultfile.exists());
String contents = FileUtil.readContents( new FileInputStream(resultfile),
"ISO-8859-1" );
assertEquals("Wrong contents", contents, "test");
}
finally
{
File resultfile = new File( m_pagedir,
"%C5%E4Test.txt" );
try
{
resultfile.delete();
}
catch(Exception e) {}
}
}
public void testNonExistantDirectory()
throws Exception
{
String tmpdir = m_pagedir;
String dirname = "non-existant-directory";
String newdir = tmpdir + File.separator + dirname;
Properties props = new Properties();
props.setProperty( FileSystemProvider.PROP_PAGEDIR,
newdir );
FileSystemProvider test = new FileSystemProvider();
try
{
test.initialize( props );
fail( "Wiki did not warn about wrong property." );
}
catch( IOException e )
{
if( e instanceof FileNotFoundException )
{
// This is okay.
}
else
{
fail("Wrong exception: "+e);
}
}
}
public void testDirectoryIsFile()
throws Exception
{
File tmpFile = null;
try
{
tmpFile = FileUtil.newTmpFile("foobar"); // Content does not matter.
Properties props = new Properties();
props.setProperty( FileSystemProvider.PROP_PAGEDIR,
tmpFile.getAbsolutePath() );
FileSystemProvider test = new FileSystemProvider();
try
{
test.initialize( props );
fail( "Wiki did not warn about wrong property." );
}
catch( IOException e )
{
// This is okay.
}
}
finally
{
if( tmpFile != null )
{
tmpFile.delete();
}
}
}
public static Test suite()
{
return new TestSuite( FileSystemProviderTest.class );
}
} |
package com.markupartist.sthlmtraveling;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* Sectioned adapter groups several adapters into one.
*/
abstract public class SectionedAdapter extends BaseAdapter {
abstract protected View getHeaderView(Section section, int index,
View convertView, ViewGroup parent);
private List<Section> sections = new ArrayList<Section>();
private static int TYPE_SECTION_HEADER = 0;
public SectionedAdapter() {
super();
}
public void addSection(int id, String caption, Adapter adapter) {
sections.add(new Section(id, caption, adapter));
}
/**
* Get current section and the given position.
* @author johan
* @param position the position
* @return the current section
*/
public Section getSection(int position) {
for (Section section : this.sections) {
if (position == 0) {
return (section);
}
int size = section.adapter.getCount() + 1;
if (position < size) {
return section;
}
position -= size;
}
return null;
}
/**
* Get the section id of the inner adapter
* @author johan
* @param position the position
* @return the inner adapters position
*/
public int getSectionIndex(int position) {
int sectionIndex = 0;
for (Section section : this.sections) {
int size = section.adapter.getCount() + 1;
if (position < size) {
return position - 1;
}
position -= size;
sectionIndex++;
}
return sectionIndex;
}
public Object getItem(int position) {
for (Section section : this.sections) {
if (position == 0) {
return (section);
}
int size = section.adapter.getCount() + 1;
if (position < size) {
return (section.adapter.getItem(position - 1));
}
position -= size;
}
return (null);
}
public int getCount() {
int total = 0;
for (Section section : this.sections) {
total += section.adapter.getCount() + 1; // add one for header
}
return (total);
}
public int getViewTypeCount() {
int total = 1; // one for the header, plus those from sections
for (Section section : this.sections) {
total += section.adapter.getViewTypeCount();
}
return (total);
}
public int getItemViewType(int position) {
int typeOffset = TYPE_SECTION_HEADER + 1; // start counting from here
for (Section section : this.sections) {
if (position == 0) {
return (TYPE_SECTION_HEADER);
}
int size = section.adapter.getCount() + 1;
if (position < size) {
return (typeOffset + section.adapter
.getItemViewType(position - 1));
}
position -= size;
typeOffset += section.adapter.getViewTypeCount();
}
return (-1);
}
public boolean areAllItemsSelectable() {
return (false);
}
public boolean isEnabled(int position) {
return (getItemViewType(position) != TYPE_SECTION_HEADER);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int sectionIndex = 0;
for (Section section : this.sections) {
if (position == 0) {
return (getHeaderView(section, sectionIndex,
convertView, parent));
}
int size = section.adapter.getCount() + 1;
if (position < size) {
return (section.adapter.getView(position - 1, convertView,
parent));
}
position -= size;
sectionIndex++;
}
return (null);
}
@Override
public long getItemId(int position) {
return (position);
}
class Section {
int id;
String caption;
Adapter adapter;
Section(int id, String caption, Adapter adapter) {
this.id = id;
this.caption = caption;
this.adapter = adapter;
}
}
} |
/*
* This Java source file was generated by the Gradle 'init' task.
*/
import org.junit.Test;
import static org.junit.Assert.*;
public class LibraryTest {
@Test
public void testSomeLibraryMethod() {
Library classUnderTest = new Library();
assertTrue("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod());
}
} |
package com.swabunga.spell.engine;
import java.io.*;
import java.util.*;
public class SpellDictionaryHashMap extends SpellDictionaryASpell {
/** A field indicating the initial hash map capacity (16KB) for the main
* dictionary hash map. Interested to see what the performance of a
* smaller initial capacity is like.
*/
private final static int INITIAL_CAPACITY = 16 * 1024;
/**
* The hashmap that contains the word dictionary. The map is hashed on the doublemeta
* code. The map entry contains a LinkedList of words that have the same double meta code.
*/
protected Hashtable mainDictionary = new Hashtable(INITIAL_CAPACITY);
/** Holds the dictionary file for appending*/
private File dictFile = null;
/**
* Dictionary Constructor.
*/
public SpellDictionaryHashMap() throws IOException{
super((File)null);
}
/**
* Dictionary Constructor.
*/
public SpellDictionaryHashMap(Reader wordList) throws IOException {
super((File)null);
createDictionary(new BufferedReader(wordList));
}
/**
* Dictionary Convienence Constructor.
*/
public SpellDictionaryHashMap(File wordList)
throws FileNotFoundException, IOException {
this(new FileReader(wordList));
dictFile = wordList;
}
/**
* Dictionary constructor that uses an aspell phonetic file to
* build the transformation table.
*/
public SpellDictionaryHashMap(File wordList, File phonetic)
throws FileNotFoundException, IOException {
super(phonetic);
dictFile = wordList;
createDictionary(new BufferedReader(new FileReader(wordList)));
}
/**
* Dictionary constructor that uses an aspell phonetic file to
* build the transformation table.
*/
public SpellDictionaryHashMap(Reader wordList, Reader phonetic) throws IOException
{
super(phonetic);
dictFile = null;
createDictionary(new BufferedReader(wordList));
}
/**
* Add words from a file to existing dictionary hashmap.
* This function can be called as many times as needed to
* build the internal word list. Duplicates are not added.
* <p>
* Note that adding a dictionary does not affect the target
* dictionary file for the addWord method. That is, addWord() continues
* to make additions to the dictionary file specified in createDictionary()
* <P>
* @param wordList a File object that contains the words, on word per line.
* @throws FileNotFoundException
* @throws IOException
*/
public void addDictionary(File wordList)
throws FileNotFoundException, IOException {
addDictionaryHelper(new BufferedReader(new FileReader(wordList)));
}
public void addDictionary(Reader wordList) throws IOException
{
addDictionaryHelper(new BufferedReader(wordList));
}
/**
* Add a word permanantly to the dictionary (and the dictionary file).
* <p>This needs to be made thread safe (synchronized)</p>
*/
public void addWord(String word) {
putWord(word);
if (dictFile == null)
return;
try {
FileWriter w = new FileWriter(dictFile.toString(), true);
// Open with append.
w.write(word);
w.write("\n");
w.close();
} catch (IOException ex) {
System.out.println("Error writing to dictionary file");
}
}
/**
* Constructs the dictionary from a word list file.
* <p>
* Each word in the reader should be on a seperate line.
* <p>
* This is a very slow function. On my machine it takes quite a while to
* load the data in. I suspect that we could speed this up quite alot.
*/
protected void createDictionary(BufferedReader in) throws IOException {
String line = "";
while (line != null) {
line = in.readLine();
if (line != null && line.length() > 0) {
line = new String(line.toCharArray());
putWord(line);
}
}
}
/**
* Adds to the existing dictionary from a word list file. If the word
* already exists in the dictionary, a new entry is not added.
* <p>
* Each word in the reader should be on a seperate line.
* <p>
* Note: for whatever reason that I haven't yet looked into, the phonetic codes
* for a particular word map to a vector of words rather than a hash table.
* This is a drag since in order to check for duplicates you have to iterate
* through all the words that use the phonetic code.
* If the vector-based implementation is important, it may be better
* to subclass for the cases where duplicates are bad.
*/
protected void addDictionaryHelper(BufferedReader in) throws IOException {
String line = "";
while (line != null) {
line = in.readLine();
if (line != null && line.length() > 0) {
line = new String(line.toCharArray());
putWordUnique(line);
}
}
}
/**
* Allocates a word in the dictionary
*/
protected void putWord(String word) {
String code = getCode(word);
Vector list = (Vector) mainDictionary.get(code);
if (list != null) {
list.addElement(word);
} else {
list = new Vector();
list.addElement(word);
mainDictionary.put(code, list);
}
}
protected void putWordUnique(String word) {
String code = getCode(word);
Vector list = (Vector) mainDictionary.get(code);
if (list != null) {
boolean isAlready = false;
for( int i = 0; i < list.size(); i++ ){
if( word.compareTo((String)list.elementAt(i)) == 0 ){
isAlready = true;
break;
}
}
if( !isAlready )
list.addElement(word);
} else {
list = new Vector();
list.addElement(word);
mainDictionary.put(code, list);
}
}
/**
* Returns a list of strings (words) for the code.
*/
public List getWords(String code) {
//Check the main dictionary.
Vector mainDictResult = (Vector) mainDictionary.get(code);
if (mainDictResult == null)
return new Vector();
return mainDictResult;
}
} |
package com.team254.lib.web.handlers;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.json.simple.JSONObject;
import com.team254.lib.util.SystemManager;
public class GetAllStatesHandler extends AbstractHandler {
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
HashMap<String, String> s = SystemManager.getInstance().get();
JSONObject json = new JSONObject(s);
response.getWriter().println(json.toJSONString());
}
} |
package com.brogrammers.agora;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class AnswerAdapter extends BaseAdapter {
private Question question;
private LayoutInflater inflater;
AnswerAdapter(Question q){
this.question = q;
this.inflater = (LayoutInflater)Agora.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return question.countAnswers();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return question.getAnswers().get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return question.getAnswers().get(position).getID();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null){
convertView = inflater.inflate(R.layout.answer_object, null);
}
//inflate each listview item with "answer_object"
Answer answer = (Answer)getItem(position);
Button comment = (Button) convertView.findViewById(R.id.aComment);
ImageButton upvote = (ImageButton) convertView.findViewById(R.id.aUpvote);
comment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Intent intent = new Intent(Agora.getContext(), CommentActivity.class);
//Agora.getContext().startActivity(intent);
Toast.makeText(Agora.getContext(), "link to CommentView later" , Toast.LENGTH_SHORT).show();
}
});
upvote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(Agora.getContext(), "call upvote" , Toast.LENGTH_SHORT).show();
}
});
//set text on each TextView
((TextView)convertView.findViewById(R.id.aBody)).setText(answer.getBody());
((TextView)convertView.findViewById(R.id.aScore)).setText(Integer.toString(answer.getRating()));
((TextView)convertView.findViewById(R.id.aAuthourDate)).setText(answer.getDate().toString());
return convertView;
}
} |
package annotator;
import annotator.find.AnnotationInsertion;
import annotator.find.CastInsertion;
import annotator.find.ConstructorInsertion;
import annotator.find.Criteria;
import annotator.find.GenericArrayLocationCriterion;
import annotator.find.Insertion;
import annotator.find.Insertions;
import annotator.find.NewInsertion;
import annotator.find.ReceiverInsertion;
import annotator.find.TreeFinder;
import annotator.find.TypedInsertion;
import annotator.scanner.LocalVariableScanner;
import annotator.scanner.TreePathUtil;
import annotator.specification.IndexFileSpecification;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.SetMultimap;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.tree.JCTree;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.objectweb.asm.TypePath;
import org.plumelib.options.Option;
import org.plumelib.options.OptionGroup;
import org.plumelib.options.Options;
import org.plumelib.reflection.ReflectionPlume;
import org.plumelib.util.FileIOException;
import org.plumelib.util.FilesPlume;
import org.plumelib.util.Pair;
import scenelib.annotations.Annotation;
import scenelib.annotations.el.ABlock;
import scenelib.annotations.el.AClass;
import scenelib.annotations.el.ADeclaration;
import scenelib.annotations.el.AElement;
import scenelib.annotations.el.AExpression;
import scenelib.annotations.el.AField;
import scenelib.annotations.el.AMethod;
import scenelib.annotations.el.AScene;
import scenelib.annotations.el.ATypeElement;
import scenelib.annotations.el.ATypeElementWithType;
import scenelib.annotations.el.AnnotationDef;
import scenelib.annotations.el.DefException;
import scenelib.annotations.el.ElementVisitor;
import scenelib.annotations.el.LocalLocation;
import scenelib.annotations.el.TypePathEntry;
import scenelib.annotations.io.ASTIndex;
import scenelib.annotations.io.ASTPath;
import scenelib.annotations.io.ASTRecord;
import scenelib.annotations.io.DebugWriter;
import scenelib.annotations.io.IndexFileParser;
import scenelib.annotations.io.IndexFileWriter;
import scenelib.annotations.util.CommandLineUtils;
import scenelib.annotations.util.coll.VivifyingMap;
/**
* This is the main class for the annotator, which inserts annotations in Java source code. You can
* call it as {@code java annotator.Main} or by using the shell script {@code
* insert-annotations-to-source}.
*
* <p>It takes as input
*
* <ul>
* <li>annotation (index) files, which indicate the annotations to insert
* <li>Java source files, into which the annotator inserts annotations
* </ul>
*
* Annotations that are not for the specified Java files are ignored.
*
* <p>The <a id="command-line-options">command-line options</a> are as follows:
* <!-- start options doc (DO NOT EDIT BY HAND) -->
*
* <ul>
* <li id="optiongroup:General-options">General options
* <ul>
* <li id="option:outdir"><b>-d</b> <b>--outdir=</b><i>directory</i>. Directory in which
* output files are written. [default: annotated/]
* <li id="option:in-place"><b>-i</b> <b>--in-place=</b><i>boolean</i>. If true, overwrite
* original source files (making a backup first). Furthermore, if the backup files
* already exist, they are used instead of the .java files. This behavior permits a user
* to tweak the {@code .jaif} file and re-run the annotator.
* <p>Note that if the user runs the annotator with --in-place, makes edits, and then
* re-runs the annotator with this --in-place option, those edits are lost. Similarly,
* if the user runs the annotator twice in a row with --in-place, only the last set of
* annotations will appear in the codebase at the end.
* <p>To preserve changes when using the --in-place option, first remove the backup
* files. Or, use the {@code -d .} option, which makes (and reads) no backup, instead of
* --in-place. [default: false]
* <li id="option:abbreviate"><b>-a</b> <b>--abbreviate=</b><i>boolean</i>. If true, insert
* {@code import} statements as necessary. [default: true]
* <li id="option:comments"><b>-c</b> <b>--comments=</b><i>boolean</i>. Insert annotations
* in comments [default: false]
* <li id="option:omit-annotation"><b>-o</b> <b>--omit-annotation=</b><i>string</i>. Omit
* given annotation
* <li id="option:nowarn"><b>--nowarn=</b><i>boolean</i>. Suppress warnings about disallowed
* insertions [default: false]
* <li id="option:convert-jaifs"><b>--convert-jaifs=</b><i>boolean</i>. Convert JAIFs to AST
* Path format, but do no insertion into source [default: false]
* <li id="option:help"><b>-h</b> <b>--help=</b><i>boolean</i>. Print usage information and
* exit [default: false]
* </ul>
* <li id="optiongroup:Debugging-options">Debugging options
* <ul>
* <li id="option:verbose"><b>-v</b> <b>--verbose=</b><i>boolean</i>. Verbose (print
* progress information) [default: false]
* <li id="option:debug"><b>--debug=</b><i>boolean</i>. Debug (print debug information)
* [default: false]
* <li id="option:print-error-stack"><b>--print-error-stack=</b><i>boolean</i>. Print error
* stack [default: false]
* </ul>
* </ul>
*
* <!-- end options doc -->
*/
public class Main {
// Options
/** Directory in which output files are written. */
@OptionGroup("General options")
@Option("-d <directory> Directory in which output files are written")
public static String outdir = "annotated/";
/**
* If true, overwrite original source files (making a backup first). Furthermore, if the backup
* files already exist, they are used instead of the .java files. This behavior permits a user to
* tweak the {@code .jaif} file and re-run the annotator.
*
* <p>Note that if the user runs the annotator with --in-place, makes edits, and then re-runs the
* annotator with this --in-place option, those edits are lost. Similarly, if the user runs the
* annotator twice in a row with --in-place, only the last set of annotations will appear in the
* codebase at the end.
*
* <p>To preserve changes when using the --in-place option, first remove the backup files. Or, use
* the {@code -d .} option, which makes (and reads) no backup, instead of --in-place.
*/
@Option("-i Overwrite original source files")
public static boolean in_place = false;
/** If true, insert {@code import} statements as necessary. */
@Option("-a Abbreviate annotation names")
public static boolean abbreviate = true;
@Option("-c Insert annotations in comments")
public static boolean comments = false;
@Option("-o Omit given annotation")
public static String omit_annotation;
@Option("Suppress warnings about disallowed insertions")
public static boolean nowarn;
// Instead of doing insertions, create new JAIFs using AST paths
// extracted from existing JAIFs and source files they match
@Option("Convert JAIFs to AST Path format, but do no insertion into source")
public static boolean convert_jaifs = false;
@Option("-h Print usage information and exit")
public static boolean help = false;
// Debugging options go below here.
@OptionGroup("Debugging options")
@Option("-v Verbose (print progress information)")
public static boolean verbose = false;
@Option("Debug (print debug information)")
public static boolean debug = false;
@Option("Print error stack")
public static boolean print_error_stack = false;
// TODO: remove this.
public static boolean temporaryDebug = false;
private static ElementVisitor<Void, AElement> classFilter =
new ElementVisitor<Void, AElement>() {
<K, V extends AElement> Void filter(VivifyingMap<K, V> vm0, VivifyingMap<K, V> vm1) {
for (Map.Entry<K, V> entry : vm0.entrySet()) {
entry.getValue().accept(this, vm1.getVivify(entry.getKey()));
}
return null;
}
@Override
public Void visitAnnotationDef(AnnotationDef def, AElement el) {
// not used, since package declarations not handled here
return null;
}
@Override
public Void visitBlock(ABlock el0, AElement el) {
ABlock el1 = (ABlock) el;
filter(el0.locals, el1.locals);
return visitExpression(el0, el);
}
@Override
public Void visitClass(AClass el0, AElement el) {
AClass el1 = (AClass) el;
filter(el0.methods, el1.methods);
filter(el0.fields, el1.fields);
filter(el0.fieldInits, el1.fieldInits);
filter(el0.staticInits, el1.staticInits);
filter(el0.instanceInits, el1.instanceInits);
return visitDeclaration(el0, el);
}
@Override
public Void visitDeclaration(ADeclaration el0, AElement el) {
ADeclaration el1 = (ADeclaration) el;
VivifyingMap<ASTPath, ATypeElement> insertAnnotations = el1.insertAnnotations;
VivifyingMap<ASTPath, ATypeElementWithType> insertTypecasts = el1.insertTypecasts;
for (Map.Entry<ASTPath, ATypeElement> entry : el0.insertAnnotations.entrySet()) {
ASTPath p = entry.getKey();
ATypeElement e = entry.getValue();
insertAnnotations.put(p, e);
// visitTypeElement(e, insertAnnotations.getVivify(p));
}
for (Map.Entry<ASTPath, ATypeElementWithType> entry : el0.insertTypecasts.entrySet()) {
ASTPath p = entry.getKey();
ATypeElementWithType e = entry.getValue();
scenelib.type.Type type = e.getType();
if (type instanceof scenelib.type.DeclaredType
&& ((scenelib.type.DeclaredType) type).getName().isEmpty()) {
insertAnnotations.put(p, e);
// visitTypeElement(e, insertAnnotations.getVivify(p));
} else {
insertTypecasts.put(p, e);
// visitTypeElementWithType(e, insertTypecasts.getVivify(p));
}
}
return null;
}
@Override
public Void visitExpression(AExpression el0, AElement el) {
AExpression el1 = (AExpression) el;
filter(el0.typecasts, el1.typecasts);
filter(el0.instanceofs, el1.instanceofs);
filter(el0.news, el1.news);
return null;
}
@Override
public Void visitField(AField el0, AElement el) {
return visitDeclaration(el0, el);
}
@Override
public Void visitMethod(AMethod el0, AElement el) {
AMethod el1 = (AMethod) el;
filter(el0.bounds, el1.bounds);
el0.returnType.accept(this, el1.returnType);
el0.receiver.accept(this, el1.receiver);
filter(el0.parameters, el1.parameters);
filter(el0.throwsException, el1.throwsException);
filter(el0.preconditions, el1.preconditions);
filter(el0.postconditions, el1.postconditions);
el0.body.accept(this, el1.body);
return visitDeclaration(el0, el);
}
@Override
public Void visitTypeElement(ATypeElement el0, AElement el) {
ATypeElement el1 = (ATypeElement) el;
filter(el0.innerTypes, el1.innerTypes);
return null;
}
@Override
public Void visitTypeElementWithType(ATypeElementWithType el0, AElement el) {
ATypeElementWithType el1 = (ATypeElementWithType) el;
el1.setType(el0.getType());
return visitTypeElement(el0, el);
}
@Override
public Void visitElement(AElement el, AElement arg) {
return null;
}
};
private static AScene filteredScene(final AScene scene) {
final AScene filtered = new AScene();
filtered.packages.putAll(scene.packages);
filtered.imports.putAll(scene.imports);
for (Map.Entry<String, AClass> entry : scene.classes.entrySet()) {
String key = entry.getKey();
AClass clazz0 = entry.getValue();
AClass clazz1 = filtered.classes.getVivify(key);
clazz0.accept(classFilter, clazz1);
}
filtered.prune();
return filtered;
}
private static ATypeElement findInnerTypeElement(
ASTRecord rec, ADeclaration decl, Insertion ins) {
ASTPath astPath = rec.astPath;
GenericArrayLocationCriterion galc = ins.getCriteria().getGenericArrayLocation();
assert astPath != null && galc != null;
List<TypePathEntry> tpes = galc.getLocation();
ASTPath.ASTEntry entry;
for (TypePathEntry tpe : tpes) {
switch (tpe.step) {
case TypePath.ARRAY_ELEMENT:
if (!astPath.isEmpty()) {
entry = astPath.getLast();
if (entry.getTreeKind() == Tree.Kind.NEW_ARRAY && entry.childSelectorIs(ASTPath.TYPE)) {
entry =
new ASTPath.ASTEntry(Tree.Kind.NEW_ARRAY, ASTPath.TYPE, entry.getArgument() + 1);
break;
}
}
entry = new ASTPath.ASTEntry(Tree.Kind.ARRAY_TYPE, ASTPath.TYPE);
break;
case TypePath.INNER_TYPE:
entry = new ASTPath.ASTEntry(Tree.Kind.MEMBER_SELECT, ASTPath.EXPRESSION);
break;
case TypePath.TYPE_ARGUMENT:
entry =
new ASTPath.ASTEntry(
Tree.Kind.PARAMETERIZED_TYPE, ASTPath.TYPE_ARGUMENT, tpe.argument);
break;
case TypePath.WILDCARD_BOUND:
entry = new ASTPath.ASTEntry(Tree.Kind.UNBOUNDED_WILDCARD, ASTPath.BOUND);
break;
default:
throw new IllegalArgumentException("unknown type tag " + tpe.step);
}
astPath = astPath.extend(entry);
}
return decl.insertAnnotations.getVivify(astPath);
}
private static void convertInsertion(
String pkg,
JCTree.JCCompilationUnit tree,
ASTRecord rec,
Insertion ins,
AScene scene,
Multimap<Insertion, Annotation> insertionSources) {
Collection<Annotation> annos = insertionSources.get(ins);
if (rec == null) {
if (ins.getCriteria().isOnPackage()) {
for (Annotation anno : annos) {
scene.packages.get(pkg).tlAnnotationsHere.add(anno);
}
}
} else if (scene != null && rec.className != null) {
AClass clazz = scene.classes.getVivify(rec.className);
ADeclaration decl = null; // insertion target
if (ins.getCriteria().onBoundZero()) {
int n = rec.astPath.size();
if (!rec.astPath.get(n - 1).childSelectorIs(ASTPath.BOUND)) {
ASTPath astPath = ASTPath.empty();
for (int i = 0; i < n; i++) {
astPath = astPath.extend(rec.astPath.get(i));
}
astPath =
astPath.extend(new ASTPath.ASTEntry(Tree.Kind.TYPE_PARAMETER, ASTPath.BOUND, 0));
rec = rec.replacePath(astPath);
}
}
if (rec.methodName == null) {
decl = rec.varName == null ? clazz : clazz.fields.getVivify(rec.varName);
} else {
AMethod meth = clazz.methods.getVivify(rec.methodName);
if (rec.varName == null) {
decl = meth;
} else {
try {
int i = Integer.parseInt(rec.varName);
decl = i < 0 ? meth.receiver : meth.parameters.getVivify(i);
} catch (NumberFormatException e) {
TreePath path = ASTIndex.getTreePath(tree, rec);
JCTree.JCVariableDecl varTree = null;
JCTree.JCMethodDecl methTree = null;
loop:
while (path != null) {
Tree leaf = path.getLeaf();
switch (leaf.getKind()) {
case VARIABLE:
varTree = (JCTree.JCVariableDecl) leaf;
break;
case METHOD:
methTree = (JCTree.JCMethodDecl) leaf;
break;
case ANNOTATION:
case CLASS:
case ENUM:
case INTERFACE:
break loop;
default:
path = path.getParentPath();
}
}
while (path != null) {
Tree leaf = path.getLeaf();
Tree.Kind kind = leaf.getKind();
if (kind == Tree.Kind.METHOD) {
methTree = (JCTree.JCMethodDecl) leaf;
int i = LocalVariableScanner.indexOfVarTree(path, varTree, rec.varName);
int m = methTree.getStartPosition();
int a = varTree.getStartPosition();
int b = varTree.getEndPosition(tree.endPositions);
LocalLocation loc = new LocalLocation(i, a - m, b - a);
decl = meth.body.locals.getVivify(loc);
break;
}
if (ASTPath.isClassEquiv(kind)) {
// classTree = (JCTree.JCClassDecl) leaf;
break;
}
path = path.getParentPath();
}
}
}
}
if (decl != null) {
AElement el;
if (rec.astPath.isEmpty()) {
el = decl;
} else if (ins.getKind() == Insertion.Kind.CAST) {
scenelib.annotations.el.ATypeElementWithType elem =
decl.insertTypecasts.getVivify(rec.astPath);
elem.setType(((CastInsertion) ins).getType());
el = elem;
} else {
el = decl.insertAnnotations.getVivify(rec.astPath);
}
for (Annotation anno : annos) {
el.tlAnnotationsHere.add(anno);
}
if (ins instanceof TypedInsertion) {
TypedInsertion ti = (TypedInsertion) ins;
if (!rec.astPath.isEmpty()) {
// addInnerTypePaths(decl, rec, ti, insertionSources);
}
for (Insertion inner : ti.getInnerTypeInsertions()) {
Tree t = ASTIndex.getNode(tree, rec);
if (t != null) {
ATypeElement elem = findInnerTypeElement(rec, decl, inner);
for (Annotation a : insertionSources.get(inner)) {
elem.tlAnnotationsHere.add(a);
}
}
}
}
}
}
}
// Implementation details:
// 1. The annotator partially compiles source
// files using the compiler API (JSR-199), obtaining an AST.
// 2. The annotator reads the specification file, producing a set of
// annotator.find.Insertions. Insertions completely specify what to
// write (as a String, which is ultimately translated according to the
// keyword file) and how to write it (as annotator.find.Criteria).
// 3. It then traverses the tree, looking for nodes that satisfy the
// Insertion Criteria, translating the Insertion text against the
// keyword file, and inserting the annotations into the source file.
/**
* Runs the annotator, parsing the source and spec files and applying the annotations.
*
* @param args .jaif files and/or .java files and/or @arg-files, in any order
*/
@SuppressWarnings({
"ReferenceEquality", // interned operand
"EmptyCatch", // TODO
})
public static void main(String[] args) throws IOException {
if (verbose) {
System.out.printf(
"insert-annotations-to-source (%s)%n",
scenelib.annotations.io.classfile.ClassFileReader.INDEX_UTILS_VERSION);
}
Options options =
new Options(
"java annotator.Main [options] { jaif-file | java-file | @arg-file } ..."
+ System.lineSeparator()
+ "(Contents of argfiles are expanded into the argument list.)",
Main.class);
String[] cl_args;
String[] file_args;
try {
cl_args = CommandLineUtils.parseCommandLine(args);
file_args = options.parse(true, cl_args);
} catch (Exception ex) {
System.err.println(ex);
System.err.println("(For non-argfile beginning with \"@\", use \"@@\" for initial \"@\".");
System.err.println("Alternative for filenames: indicate directory, e.g. as './@file'.");
System.err.println("Alternative for flags: use '=', as in '-o=@Deprecated'.)");
System.exit(1);
throw new Error("Unreachable");
}
DebugWriter dbug = new DebugWriter(debug);
DebugWriter verb = new DebugWriter(verbose);
TreeFinder.warn.setEnabled(!nowarn);
TreeFinder.dbug.setEnabled(debug);
Criteria.dbug.setEnabled(debug);
if (help) {
options.printUsage();
System.exit(0);
}
if (in_place && outdir != "annotated/") { // interned
System.out.println("The --outdir and --in-place options are mutually exclusive.");
options.printUsage();
System.exit(1);
}
if (file_args.length < 2) {
System.out.printf("Supplied %d arguments, at least 2 needed%n", file_args.length);
System.out.printf("Supplied arguments: %s%n", Arrays.toString(args));
System.out.printf(
" (After javac parsing, remaining arguments = %s)%n", Arrays.toString(cl_args));
System.out.printf(" (File arguments = %s)%n", Arrays.toString(file_args));
options.printUsage();
System.exit(1);
}
// The names of annotation files (.jaif files).
List<String> jaifFiles = new ArrayList<>();
// The Java files into which to insert.
List<String> javafiles = new ArrayList<>();
for (String arg : file_args) {
if (arg.endsWith(".java")) {
javafiles.add(arg);
} else if (arg.endsWith(".jaif") || arg.endsWith(".jann")) {
jaifFiles.add(arg);
} else {
System.out.println("Unrecognized file extension: " + arg);
System.exit(1);
throw new Error("unreachable");
}
}
computeConstructors(javafiles);
// The insertions specified by the annotation files.
Insertions insertions = new Insertions();
// Indices to maintain insertion source traces.
Map<String, Multimap<Insertion, Annotation>> insertionIndex = new HashMap<>();
Map<Insertion, String> insertionOrigins = new HashMap<>();
Map<String, AScene> scenes = new HashMap<>();
// maintain imports info for annotations field
// Key: fully-qualified annotation name. e.g. "com.foo.Bar" for annotation @com.foo.Bar(x).
// Value: names of packages this annotation needs.
Map<String, Set<String>> annotationImports = new HashMap<>();
IndexFileParser.setAbbreviate(abbreviate);
for (String jaifFile : jaifFiles) {
IndexFileSpecification spec = new IndexFileSpecification(jaifFile);
try {
List<Insertion> parsedSpec = spec.parse();
if (temporaryDebug) {
System.out.printf("parsedSpec (size %d):%n", parsedSpec.size());
for (Insertion insertion : parsedSpec) {
System.out.printf(" %s, isInserted=%s%n", insertion, insertion.isInserted());
}
}
AScene scene = spec.getScene();
Collections.sort(
parsedSpec,
new Comparator<Insertion>() {
@Override
public int compare(Insertion i1, Insertion i2) {
ASTPath p1 = i1.getCriteria().getASTPath();
ASTPath p2 = i2.getCriteria().getASTPath();
return p1 == null ? p2 == null ? 0 : -1 : p2 == null ? 1 : p1.compareTo(p2);
}
});
if (convert_jaifs) {
scenes.put(jaifFile, filteredScene(scene));
for (Insertion ins : parsedSpec) {
insertionOrigins.put(ins, jaifFile);
}
if (!insertionIndex.containsKey(jaifFile)) {
insertionIndex.put(jaifFile, LinkedHashMultimap.<Insertion, Annotation>create());
}
insertionIndex.get(jaifFile).putAll(spec.insertionSources());
}
verb.debug("Read %d annotations from %s%n", parsedSpec.size(), jaifFile);
if (omit_annotation != null) {
List<Insertion> filtered = new ArrayList<Insertion>(parsedSpec.size());
for (Insertion insertion : parsedSpec) {
// TODO: this won't omit annotations if the insertion is more than
// just the annotation (such as if the insertion is a cast
// insertion or a 'this' parameter in a method declaration).
if (!omit_annotation.equals(insertion.getText())) {
filtered.add(insertion);
}
}
parsedSpec = filtered;
verb.debug("After filtering: %d annotations from %s%n", parsedSpec.size(), jaifFile);
}
// if (dbug.isEnabled()) {
// dbug.debug("parsedSpec:%n");
// for (Insertion insertion : parsedSpec) {
// dbug.debug(" %s, isInserted=%s%n", insertion, insertion.isInserted());
insertions.addAll(parsedSpec);
annotationImports.putAll(spec.annotationImports());
} catch (RuntimeException e) {
if (e.getCause() != null && e.getCause() instanceof FileNotFoundException) {
System.err.println("File not found: " + jaifFile);
System.exit(1);
} else {
throw e;
}
} catch (FileIOException e) {
// Add 1 to the line number since line numbers in text editors are usually one-based.
System.err.println(
"Error while parsing annotation file "
+ jaifFile
+ " at line "
+ (e.lineNumber + 1)
+ ":");
if (e.getMessage() != null) {
System.err.println(" " + e.getMessage());
}
if (e.getCause() != null && e.getCause().getMessage() != null) {
String causeMessage = e.getCause().getMessage();
System.err.println(" " + causeMessage);
if (causeMessage.startsWith("Could not load class: ")) {
System.err.println(
"To fix the problem, add class "
+ causeMessage.substring(22)
+ " to the classpath.");
System.err.println("The classpath is:");
System.err.println(ReflectionPlume.classpathToString());
}
}
if (print_error_stack) {
e.printStackTrace();
}
System.exit(1);
}
}
if (dbug.isEnabled()) {
dbug.debug("In annotator.Main:%n");
dbug.debug("%d insertions, %d .java files%n", insertions.size(), javafiles.size());
dbug.debug("Insertions:%n");
for (Insertion insertion : insertions) {
dbug.debug(" %s, isInserted=%s%n", insertion, insertion.isInserted());
}
}
for (String javafilename : javafiles) {
verb.debug("Processing %s%n", javafilename);
File javafile = new File(javafilename);
File unannotated = new File(javafilename + ".unannotated");
if (in_place) {
// It doesn't make sense to check timestamps;
// if the .java.unannotated file exists, then just use it.
// A user can rename that file back to just .java to cause the
// .java file to be read.
if (unannotated.exists()) {
verb.debug("Renaming %s to %s%n", unannotated, javafile);
boolean success = unannotated.renameTo(javafile);
if (!success) {
throw new Error(String.format("Failed renaming %s to %s", unannotated, javafile));
}
}
}
Source src = fileToSource(javafilename);
if (src == null) {
return;
} else {
verb.debug("Parsed %s%n", javafilename);
}
String fileLineSep;
try {
// fileLineSep is set here so that exceptions can be caught
fileLineSep = FilesPlume.inferLineSeparator(javafilename);
} catch (IOException e) {
throw new Error("Cannot read " + javafilename, e);
}
// Imports required to resolve annotations (when abbreviate==true).
LinkedHashSet<String> imports = new LinkedHashSet<>();
int num_insertions = 0;
String pkg = "";
for (CompilationUnitTree cut : src.parse()) {
JCTree.JCCompilationUnit tree = (JCTree.JCCompilationUnit) cut;
ExpressionTree pkgExp = cut.getPackageName();
pkg = pkgExp == null ? "" : pkgExp.toString();
// Create a finder, and use it to get positions.
TreeFinder finder = new TreeFinder(tree);
SetMultimap<Pair<Integer, ASTPath>, Insertion> positions =
finder.getPositions(tree, insertions);
if (dbug.isEnabled()) {
dbug.debug("In annotator.Main:%n");
dbug.debug("positions (for %d insertions) = %s%n", insertions.size(), positions);
}
if (convert_jaifs) {
// With --convert-jaifs command-line option, the program is used only for JAIF conversion.
// Execute the following block and then skip the remainder of the loop.
Multimap<ASTRecord, Insertion> astInsertions = finder.getPaths();
for (Map.Entry<ASTRecord, Collection<Insertion>> entry :
astInsertions.asMap().entrySet()) {
ASTRecord rec = entry.getKey();
for (Insertion ins : entry.getValue()) {
if (ins.getCriteria().getASTPath() != null) {
continue;
}
String arg = insertionOrigins.get(ins);
AScene scene = scenes.get(arg);
Multimap<Insertion, Annotation> insertionSources = insertionIndex.get(arg);
// String text =
// ins.getText(comments, abbreviate, false, 0, '\0');
// TODO: adjust for missing end of path (?)
if (insertionSources.containsKey(ins)) {
convertInsertion(pkg, tree, rec, ins, scene, insertionSources);
}
}
}
continue;
}
// Apply the positions to the source file.
verb.debug(
"getPositions returned %d positions in tree for %s%n", positions.size(), javafilename);
Set<Pair<Integer, ASTPath>> positionKeysUnsorted = positions.keySet();
Set<Pair<Integer, ASTPath>> positionKeysSorted =
new TreeSet<Pair<Integer, ASTPath>>(
new Comparator<Pair<Integer, ASTPath>>() {
@Override
public int compare(Pair<Integer, ASTPath> p1, Pair<Integer, ASTPath> p2) {
int c = Integer.compare(p2.a, p1.a);
if (c != 0) {
return c;
}
return p2.b == null
? (p1.b == null ? 0 : -1)
: (p1.b == null ? 1 : p2.b.compareTo(p1.b));
}
});
positionKeysSorted.addAll(positionKeysUnsorted);
for (Pair<Integer, ASTPath> pair : positionKeysSorted) {
boolean receiverInserted = false;
boolean newInserted = false;
boolean constructorInserted = false;
Set<String> seen = new TreeSet<>();
List<Insertion> toInsertList = new ArrayList<>(positions.get(pair));
// The Multimap interface doesn't seem to have a way to specify the order of elements in
// the collection, so sort them here.
toInsertList.sort(insertionSorter);
dbug.debug("insertion pos: %d%n", pair.a);
dbug.debug("insertions sorted: %s%n", toInsertList);
assert pair.a >= 0
: "pos is negative: " + pair.a + " " + toInsertList.get(0) + " " + javafilename;
for (Insertion iToInsert : toInsertList) {
// Possibly add whitespace after the insertion
String trailingWhitespace = "";
boolean gotSeparateLine = false;
int pos = pair.a; // reset each iteration in case of dyn adjustment
if (iToInsert.isSeparateLine()) {
// System.out.printf("isSeparateLine=true for insertion at pos %d: %s%n", pos,
// iToInsert);
// If an annotation should have its own line, first check that the insertion location
// is the first non-whitespace on its line. If so, then the insertion content should
// be the annotation, followed, by a line break, followed by a copy of the indentation
// of the line being inserted onto. This puts the annotation on its own line aligned
// with the contents of the next line.
// Number of whitespace characters preceeding the insertion position on the same line
// (tabs count as one).
int indentation = 0;
while ((pos - indentation != 0)
// horizontal whitespace
&& (src.charAt(pos - indentation - 1) == ' '
|| src.charAt(pos - indentation - 1) == '\t')) {
// System.out.printf("src.charAt(pos-indentation-1 == %d-%d-1)='%s'%n",
// pos, indentation, src.charAt(pos-indentation-1));
indentation++;
}
// Checks that insertion position is the first non-whitespace on the line it occurs
if ((pos - indentation == 0)
|| (src.charAt(pos - indentation - 1) == '\f'
|| src.charAt(pos - indentation - 1) == '\n'
|| src.charAt(pos - indentation - 1) == '\r')) {
trailingWhitespace = fileLineSep + src.substring(pos - indentation, pos);
gotSeparateLine = true;
}
}
char precedingChar;
if (pos != 0) {
precedingChar = src.charAt(pos - 1);
} else {
precedingChar = '\0';
}
if (iToInsert.getKind() == Insertion.Kind.ANNOTATION) {
AnnotationInsertion ai = (AnnotationInsertion) iToInsert;
if (ai.isGenerateBound()) { // avoid multiple ampersands
try {
String s = src.substring(pos, pos + 9);
if ("Object & ".equals(s)) {
ai.setGenerateBound(false);
precedingChar = '.'; // suppress leading space
}
} catch (StringIndexOutOfBoundsException e) {
}
}
if (ai.isGenerateExtends()) { // avoid multiple "extends"
try {
String s = src.substring(pos, pos + 9);
if (" extends ".equals(s)) {
ai.setGenerateExtends(false);
pos += 8;
}
} catch (StringIndexOutOfBoundsException e) {
}
}
} else if (iToInsert.getKind() == Insertion.Kind.CAST) {
((CastInsertion) iToInsert).setOnArrayLiteral(src.charAt(pos) == '{');
} else if (iToInsert.getKind() == Insertion.Kind.RECEIVER) {
ReceiverInsertion ri = (ReceiverInsertion) iToInsert;
ri.setAnnotationsOnly(receiverInserted);
receiverInserted = true;
} else if (iToInsert.getKind() == Insertion.Kind.NEW) {
NewInsertion ni = (NewInsertion) iToInsert;
ni.setAnnotationsOnly(newInserted);
newInserted = true;
} else if (iToInsert.getKind() == Insertion.Kind.CONSTRUCTOR) {
ConstructorInsertion ci = (ConstructorInsertion) iToInsert;
if (constructorInserted) {
ci.setAnnotationsOnly(true);
}
constructorInserted = true;
}
String toInsert =
iToInsert.getText(comments, abbreviate, gotSeparateLine, pos, precedingChar)
+ trailingWhitespace;
// eliminate duplicates
if (seen.contains(toInsert)) {
continue;
}
seen.add(toInsert);
// If it's an annotation and already there, don't re-insert. This is a hack!
// Also, I think this is already checked when constructing the
// insertions.
if (toInsert.startsWith("@")) {
int precedingTextPos = pos - toInsert.length() - 1;
if (precedingTextPos >= 0) {
String precedingTextPlusChar = src.getString().substring(precedingTextPos, pos);
if (toInsert.equals(precedingTextPlusChar.substring(0, toInsert.length()))
|| toInsert.equals(precedingTextPlusChar.substring(1))) {
dbug.debug(
"Inserting '%s' at %d in code of length %d with preceding text '%s'%n",
toInsert, pos, src.getString().length(), precedingTextPlusChar);
dbug.debug("Already present, skipping%n");
continue;
}
}
int followingTextEndPos = pos + toInsert.length();
if (followingTextEndPos < src.getString().length()) {
String followingText = src.getString().substring(pos, followingTextEndPos);
dbug.debug("followingText=\"%s\"%n", followingText);
dbug.debug("toInsert=\"%s\"%n", toInsert);
// toInsertNoWs does not contain the trailing whitespace.
String toInsertNoWs = toInsert.substring(0, toInsert.length() - 1);
if (followingText.equals(toInsert)
|| (followingText.substring(0, followingText.length() - 1).equals(toInsertNoWs)
// Untested. Is there an off-by-one error here?
&& Character.isWhitespace(src.getString().charAt(followingTextEndPos)))) {
dbug.debug("Already present, skipping %s%n", toInsertNoWs);
continue;
}
}
}
// TODO: Neither the above hack nor this check should be
// necessary. Find out why re-insertions still occur and
// fix properly.
if (iToInsert.isInserted()) {
continue;
}
src.insert(pos, toInsert);
if (verbose && !debug) {
System.out.print(".");
num_insertions++;
if ((num_insertions % 50) == 0) {
System.out.println(); // terminate the line that contains dots
}
}
dbug.debug("Post-insertion source: %s%n", src.getString());
Collection<String> packageNames = nonJavaLangClasses(iToInsert.getPackageNames());
if (!packageNames.isEmpty()) {
dbug.debug("Need import %s%n due to insertion %s%n", packageNames, toInsert);
imports.addAll(packageNames);
}
if (iToInsert instanceof AnnotationInsertion) {
AnnotationInsertion annoToInsert = (AnnotationInsertion) iToInsert;
Set<String> annoImports =
annotationImports.get(annoToInsert.getAnnotationFullyQualifiedName());
if (annoImports != null) {
imports.addAll(annoImports);
}
}
}
}
}
if (verbose && !debug && (num_insertions % 50) != 0) {
// after all insertions, if necessary, terminate the line that contains dots
System.out.println();
}
if (convert_jaifs) {
for (Map.Entry<String, AScene> entry : scenes.entrySet()) {
String filename = entry.getKey();
AScene scene = entry.getValue();
try {
IndexFileWriter.write(scene, filename + ".converted");
} catch (DefException e) {
System.err.println(filename + ": " + " format error in conversion");
if (print_error_stack) {
e.printStackTrace();
}
}
}
return; // done with conversion
}
if (dbug.isEnabled()) {
dbug.debug("%d imports to insert%n", imports.size());
for (String classname : imports) {
dbug.debug(" %s%n", classname);
}
}
// insert import statements
{
Pattern importPattern = Pattern.compile("(?m)^import\\b");
Pattern packagePattern = Pattern.compile("(?m)^package\\b.*;(\\n|\\r\\n?)");
int importIndex = 0; // default: beginning of file
String srcString = src.getString();
Matcher m = importPattern.matcher(srcString);
Set<String> inSource = new TreeSet<>();
if (m.find()) {
importIndex = m.start();
do {
int i = m.start();
int j = srcString.indexOf(System.lineSeparator(), i) + 1;
if (j <= 0) {
j = srcString.length();
}
String s = srcString.substring(i, j);
inSource.add(s);
} while (m.find());
} else {
// Debug.info("Didn't find import in " + srcString);
m = packagePattern.matcher(srcString);
if (m.find()) {
importIndex = m.end();
}
}
for (String classname : imports) {
String toInsert = "import " + classname + ";" + fileLineSep;
if (!inSource.contains(toInsert)) {
inSource.add(toInsert);
src.insert(importIndex, toInsert);
importIndex += toInsert.length();
}
}
}
// Write the source file.
File outfile = null;
try {
if (in_place) {
outfile = javafile;
if (verbose) {
System.out.printf("Renaming %s to %s%n", javafile, unannotated);
}
boolean success = javafile.renameTo(unannotated);
if (!success) {
throw new Error(String.format("Failed renaming %s to %s", javafile, unannotated));
}
} else {
if (pkg.isEmpty()) {
outfile = new File(outdir, javafile.getName());
} else {
@SuppressWarnings("StringSplitter") // false positive because pkg is non-empty
String[] pkgPath = pkg.split("\\.");
StringBuilder sb = new StringBuilder(outdir);
for (int i = 0; i < pkgPath.length; i++) {
sb.append(File.separator).append(pkgPath[i]);
}
outfile = new File(sb.toString(), javafile.getName());
}
outfile.getParentFile().mkdirs();
}
OutputStream output = new FileOutputStream(outfile);
if (verbose) {
System.out.printf("Writing %s%n", outfile);
}
src.write(output);
output.close();
} catch (IOException e) {
System.err.println("Problem while writing file " + outfile);
e.printStackTrace();
System.exit(1);
}
}
}
/**
* Given a Java file name, creates a Source, or returns null.
*
* @param javaFileName a Java file name
* @return a Source for the Java file, or null
*/
private static Source fileToSource(String javaFileName) {
Source src;
// Get the source file, and use it to obtain parse trees.
try {
src = new Source(javaFileName);
return src;
} catch (Source.CompilerException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Primary sort criterion: put declaration annotations (which go on a separate line) last, so that
* they *precede* type annotations when inserted.
*
* <p>Secondary sort criterion: for determinism, put annotations in reverse alphabetic order (so
* that they are alphabetized when inserted).
*/
private static Comparator<Insertion> insertionSorter =
new Comparator<Insertion>() {
@Override
public int compare(Insertion i1, Insertion i2) {
boolean separateLine1 = i1.isSeparateLine();
boolean separateLine2 = i2.isSeparateLine();
if (separateLine1 && !separateLine2) {
return 1;
} else if (separateLine2 && !separateLine1) {
return -1;
} else {
return -i1.getText().compareTo(i2.getText());
}
}
};
/** Maps from binary class name to whether the class has any explicit constructor. */
public static Map<String, Boolean> hasExplicitConstructor = new HashMap<>();
/**
* Fills in the {@link hasExplicitConstructor} map.
*
* @param javaFiles the Java files that were passed on the command line
*/
static void computeConstructors(List<String> javaFiles) {
for (String javaFile : javaFiles) {
Source src = fileToSource(javaFile);
if (src == null) {
continue;
}
for (CompilationUnitTree cut : src.parse()) {
TreePathScanner<Void, Void> constructorsScanner =
new TreePathScanner<Void, Void>() {
@Override
public Void visitClass(ClassTree ct, Void p) {
String className = TreePathUtil.getBinaryName(getCurrentPath());
hasExplicitConstructor.put(className, TreePathUtil.hasConstructor(ct));
return super.visitClass(ct, p);
}
};
constructorsScanner.scan(cut, null);
}
}
}
/** A regular expression for classes in the java.lang package. */
private static Pattern javaLangClassPattern = Pattern.compile("^java\\.lang\\.[A-Za-z0-9_]+$");
/**
* Return true iff the class is a top-level class in the java.lang package.
*
* @param classname the class to test
* @return true iff the class is a top-level class in the java.lang package
*/
private static boolean isJavaLangClass(String classname) {
Matcher m = javaLangClassPattern.matcher(classname);
return m.matches();
}
/**
* Filters out classes in the java.lang package from the given collection.
*
* @param classnames a collection of class names
* @return the class names that are not in the java.lang package
*/
private static Collection<String> nonJavaLangClasses(Collection<String> classnames) {
// Don't side-effect the argument
List<String> result = new ArrayList<>();
for (String classname : classnames) {
if (!isJavaLangClass(classname)) {
result.add(classname);
}
}
return result;
}
/**
* Return the representation of the leaf of the path.
*
* @param path a path whose leaf to format
* @return the representation of the leaf of the path
*/
public static String leafString(TreePath path) {
if (path == null) {
return "null path";
}
return treeToString(path.getLeaf());
}
/**
* Return the first 80 characters of the tree's printed representation, on one line.
*
* @param node a tree to format with truncation
* @return the first 80 characters of the tree's printed representation, on one line
*/
public static String treeToString(Tree node) {
String asString = node.toString();
String oneLine = first80(asString);
if (oneLine.endsWith(" ")) {
oneLine = oneLine.substring(0, oneLine.length() - 1);
}
// return "\"" + oneLine + "\"";
return oneLine;
}
/**
* Return the first non-empty line of the string, adding an ellipsis (...) if the string was
* truncated.
*
* @param s a string to truncate
* @return the first non-empty line of the argument
*/
public static String firstLine(String s) {
while (s.startsWith("\n")) {
s = s.substring(1);
}
int newlineIndex = s.indexOf('\n');
if (newlineIndex == -1) {
return s;
} else {
return s.substring(0, newlineIndex) + "...";
}
}
/**
* Return the first 80 characters of the string, adding an ellipsis (...) if the string was
* truncated.
*
* @param s a string to truncate
* @return the first 80 characters of the string
*/
public static String first80(String s) {
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
i++;
}
while (i < s.length() && sb.length() < 80) {
if (s.charAt(i) == '\n') {
i++;
while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
i++;
}
sb.append(' ');
}
if (i < s.length()) {
sb.append(s.charAt(i));
}
i++;
}
if (i < s.length()) {
sb.append("...");
}
return sb.toString();
}
/**
* Separates the annotation class from its arguments.
*
* @param s the string representation of an annotation
* @return given <code>@foo(bar)</code> it returns the pair <code>{ @foo, (bar) }</code>
*/
public static Pair<String, String> removeArgs(String s) {
int pidx = s.indexOf("(");
return (pidx == -1)
? Pair.of(s, (String) null)
: Pair.of(s.substring(0, pidx), s.substring(pidx));
}
} |
package edu.vu.isis.ammo.api;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Iterator;
import java.util.NoSuchElementException;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.util.Log;
import edu.vu.isis.ammo.launch.constants.Constants;
public class AmmoContacts {
private static final String TAG = "AmmoContacts";
private ContentResolver mResolver;
public AmmoContacts() {
mResolver = null;
}
private AmmoContacts(Context context) {
this.mResolver = context.getContentResolver();
}
public static AmmoContacts newInstance(Context context) {
return new AmmoContacts(context);
}
// Contact class
static public class Contact {
public Contact() { }
private String lookup;
public String getLookup() {
return this.lookup;
}
public Contact setLookup(String val) {
this.lookup = val;
return this;
}
private String name;
public String getName() {
return this.name;
}
public Contact setName(String val) {
this.name = val;
return this;
}
private String middle_initial;
public String getMiddleName() {
return this.middle_initial;
}
public Contact setMiddleName(String val) {
this.middle_initial = val;
return this;
}
private String lastname;
public String getLastName() {
return this.lastname;
}
public Contact setLastName(String val) {
this.lastname = val;
return this;
}
private String rank;
public String getRank() {
return this.rank;
}
public Contact setRank(String val) {
this.rank = val;
return this;
}
private String callsign;
public String getCallSign() {
return this.callsign;
}
public Contact setCallSign(String val) {
this.callsign = val;
return this;
}
private String branch;
public String getBranch() {
return this.branch;
}
public Contact setBranch(String val) {
this.branch = val;
return this;
}
private String unit;
public String getUnit() {
return this.unit;
}
public Contact setUnit(String val) {
this.unit = val;
return this;
}
private String unitDivision;
public String getUnitDivision() {
return this.unitDivision;
}
public Contact setUnitDivision(String val) {
this.unitDivision = val;
return this;
}
private String unitBrigade;
public String getUnitBrigade() {
return this.unitBrigade;
}
public Contact setUnitBrigade(String val) {
this.unitBrigade = val;
return this;
}
private String unitBattalion;
public String getUnitBattalion() {
return this.unitBattalion;
}
public Contact setUnitBattalion(String val) {
this.unitBattalion = val;
return this;
}
private String unitCompany;
public String getUnitCompany() {
return this.unitCompany;
}
public Contact setUnitCompany(String val) {
this.unitCompany = val;
return this;
}
private String unitPlatoon;
public String getUnitPlatoon() {
return this.unitPlatoon;
}
public Contact setUnitPlatoon(String val) {
this.unitPlatoon = val;
return this;
}
private String unitSquad;
public String getUnitSquad() {
return this.unitSquad;
}
public Contact setUnitSquad(String val) {
this.unitSquad = val;
return this;
}
private String email;
public String getEmail() {
return this.email;
}
public Contact setEmail(String val) {
this.email = val;
return this;
}
private String phone;
public String getPhone() {
return this.phone;
}
public Contact setPhone(String val) {
this.phone = val;
return this;
}
//private String tigrUid;
private String tigruid;
public String getTigrUid() {
return this.tigruid;
}
public Contact setTigrUid(String val) {
this.tigruid = val;
return this;
}
private String userIdNum;
public String getUserIdNumber() {
return this.userIdNum;
}
public Contact setUserIdNumber(String val) {
this.userIdNum = val;
return this;
}
private String designator;
public String getDesignator() {
return this.designator;
}
public char[] getDesignatorAsCharArray() {
return this.designator.toCharArray();
}
public Contact setDesignator(String val) {
// Designator is defined as only two characters -- enforce this
if (val.length() <= 2) {
this.designator = val;
} else {
this.designator = val.substring(0,1);
}
return this;
}
}
// updateContactEntry()
// Update (save changes to) an existing contact in the
// contacts storage provider.
public Uri updateContactEntry(Contact lw) {
Log.d(TAG,"updateContactEntry() ");
Log.d(TAG, "Updating person: " + lw.getName() + " "
+ lw.getLastName() + " ... " + lw.getTigrUid() );
ContentResolver cr = mResolver;
// First find existing record so we can modify it
Uri uriToModify = findExistingContact(lw);
// If the contact isn't found, add it ("upsert" functionality)
if (uriToModify == null) {
Log.d(TAG, " failed to find existing user, inserting new contact ");
return insertContactEntry(lw);
} else {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.d(TAG, " found existing user URI: " + uriToModify.toString());
}
}
// Parse the contact id out of the URI (we know it's the
// last segment of the URI just returned)
List<String> ps = uriToModify.getPathSegments();
int contactId = -1;
try {
contactId = Integer.parseInt(ps.get(ps.size() -1));
} catch(NumberFormatException nfe) {
Log.e(TAG, "Could not parse " + nfe);
return null;
}
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.d(TAG, " contact id = " + String.valueOf(contactId));
}
if (!(contactId > 0)) return null;
// Then make a ContentProviderOperation to update this contact
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String callsign = lw.getCallSign();
if (callsign == null) callsign = "";
if (callsign.length() > 0) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] {String.valueOf(contactId), Constants.MIME_CALLSIGN,})
.withValue(ContactsContract.Data.DATA1, callsign)
.build());
}
// userid is a special case -- don't allow updates (but keep this snippet for future use)
/*
String userId = lw.getTigrUid();
if (userId == null) userId = "";
if (userId.length() > 0) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] {String.valueOf(contactId), Constants.MIME_USERID,})
.withValue(ContactsContract.Data.DATA1, userId)
.build());
}
*/
String userIdNum = lw.getUserIdNumber();
if (userIdNum == null) userIdNum = "";
if (userIdNum.length() > 0) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] {String.valueOf(contactId), Constants.MIME_USERID_NUM,})
.withValue(ContactsContract.Data.DATA1, userIdNum)
.build());
}
String rank = lw.getRank();
if (rank == null) rank = "";
if (rank != null && rank.length() > 0) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] {String.valueOf(contactId), Constants.MIME_RANK,})
.withValue(ContactsContract.Data.DATA1, rank)
.build());
}
String designator = lw.getDesignator();
if (designator == null) designator = "";
if (designator != null && designator.length() > 0) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] {String.valueOf(contactId), Constants.MIME_DESIGNATOR,})
.withValue(ContactsContract.Data.DATA1, designator)
.build());
}
// Structured name
ContentProviderOperation.Builder snb = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] {String.valueOf(contactId),
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,});
String firstname = lw.getName();
if (firstname == null) firstname = "";
if (firstname.length() > 0) {
snb.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, firstname);
}
String lastname = lw.getLastName();
if (lastname == null) lastname = "";
if (lastname.length() > 0) {
snb.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, lastname);
}
String middlename = lw.getMiddleName();
if (middlename == null) middlename = "";
if (middlename.length() > 0) {
snb.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, middlename);
}
ops.add(snb.build());
// Unit info
String unit = lw.getUnit();
if (unit == null) unit = "";
if (unit.length() > 0)
{
ContentProviderOperation.Builder opbld = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
opbld.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] {String.valueOf(contactId), Constants.MIME_UNIT_NAME });
opbld.withValue(ContactsContract.Data.DATA1, unit);
String division = lw.getUnitDivision();
if (division == null) division = "";
if (division.length() > 0)
{
opbld.withValue(ContactsContract.Data.DATA2, division);
}
String brigade = lw.getUnitBrigade();
if (brigade == null) brigade = "";
if (brigade.length() > 0)
{
opbld.withValue(ContactsContract.Data.DATA3, brigade);
}
String battalion = lw.getUnitBattalion();
if (battalion == null) battalion = "";
if (battalion.length() > 0)
{
opbld.withValue(ContactsContract.Data.DATA4, battalion);
}
String company = lw.getUnitCompany();
if (company == null) company = "";
if (company.length() > 0)
{
opbld.withValue(ContactsContract.Data.DATA5, company);
}
String platoon = lw.getUnitPlatoon();
if (platoon == null) platoon = "";
if (platoon.length() > 0)
{
opbld.withValue(ContactsContract.Data.DATA6, platoon);
}
String squad = lw.getUnitSquad();
if (squad == null) squad = "";
if (squad.length() > 0)
{
opbld.withValue(ContactsContract.Data.DATA7, squad);
}
ops.add(opbld.build());
}
// Apply the content provider operations
try {
ContentProviderResult[] cpres = cr.applyBatch(ContactsContract.AUTHORITY, ops);
uriToModify = cpres[0].uri;
} catch (Exception ex) {
Log.e(TAG, "Exception encoutered while updating contact: " + ex.toString());
return null;
}
return uriToModify;
}
// insertContactEntry()
// Add a new contact to the contacts storage provider.
public Uri insertContactEntry(Contact lw) {
Log.d(TAG,"insertContactEntry() ");
Log.d(TAG, "Adding person: " + lw.getName() + " " + lw.getLastName() + " ... " + lw.getTigrUid() );
ContentResolver cr = mResolver;
/**
* Prepare contact creation request
* Note: We use RawContacts because this data must be associated with a particular account.
* The system will aggregate this with any other data for this contact and create a
* corresponding entry in the ContactsContract.Contacts provider for us.
*/
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, Constants.AMMO_ACCOUNT_TYPE)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, Constants.AMMO_DEFAULT_ACCOUNT_NAME)
.build());
String callsign = lw.getCallSign();
if (callsign == null) callsign = "";
if (callsign.length() > 0)
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, Constants.MIME_CALLSIGN)
.withValue(ContactsContract.Data.DATA1, callsign)
.build());
String phone = lw.getPhone();
if (phone == null) phone = "";
String email = lw.getEmail();
if (email == null) email = "";
if (email.length() > 0)
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE,
ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.build());
String unit = lw.getUnit();
if (unit == null) unit = "";
if (unit.length() > 0)
{
ContentProviderOperation.Builder opbld = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
opbld.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
opbld.withValue(ContactsContract.Data.MIMETYPE, Constants.MIME_UNIT_NAME);
opbld.withValue(ContactsContract.Data.DATA1, unit);
String division = lw.getUnitDivision();
if (division == null) division = "";
if (division.length() > 0)
{
opbld.withValue(ContactsContract.Data.DATA2, division);
}
String brigade = lw.getUnitBrigade();
if (brigade == null) brigade = "";
if (brigade.length() > 0)
{
opbld.withValue(ContactsContract.Data.DATA3, brigade);
}
String battalion = lw.getUnitBattalion();
if (battalion == null) battalion = "";
if (battalion.length() > 0)
{
opbld.withValue(ContactsContract.Data.DATA4, battalion);
}
String company = lw.getUnitCompany();
if (company == null) company = "";
if (company.length() > 0)
{
opbld.withValue(ContactsContract.Data.DATA5, company);
}
String platoon = lw.getUnitPlatoon();
if (platoon == null) platoon = "";
if (platoon.length() > 0)
{
opbld.withValue(ContactsContract.Data.DATA6, platoon);
}
String squad = lw.getUnitSquad();
if (squad == null) squad = "";
if (squad.length() > 0)
{
opbld.withValue(ContactsContract.Data.DATA7, squad);
}
ops.add(opbld.build());
}
String userId = lw.getTigrUid();
if (userId == null) userId = "";
if (userId.length() > 0)
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, Constants.MIME_USERID)
.withValue(ContactsContract.Data.DATA1, userId)
.build());
String userIdNum = lw.getUserIdNumber();
if (userIdNum == null) userIdNum = "";
if (userIdNum.length() > 0)
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, Constants.MIME_USERID_NUM)
.withValue(ContactsContract.Data.DATA1, userIdNum)
.build());
String designator = lw.getDesignator();
if (designator == null) designator = "";
if (designator.length() > 0)
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, Constants.MIME_DESIGNATOR)
.withValue(ContactsContract.Data.DATA1, designator)
.build());
String rank = lw.getRank();
if (rank == null) rank = "";
if (rank != null && rank.length() > 0)
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, Constants.MIME_RANK)
.withValue(ContactsContract.Data.DATA1, rank)
.build());
ContentProviderOperation.Builder snb = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
String firstname = lw.getName();
if (firstname == null) firstname = "";
if (firstname.length() > 0)
snb.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, firstname);
String lastname = lw.getLastName();
if (lastname == null) lastname = "";
if (lastname.length() > 0)
snb.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, lastname);
String middlename = lw.getMiddleName();
if (middlename == null) middlename = "";
if (middlename.length() > 0)
snb.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, middlename);
// Set the display name. Use, in order of preference, either the callsign or the full name.
// (In future we should prob. change this to include rank, role, etc.)
String displayName = "";
if (displayName.length() < 1) {
if (callsign != null && callsign.length() > 0) {
displayName = callsign;
}
}
if (displayName.length() < 1) {
if (firstname.length() > 0) {
displayName += firstname;
}
if (lastname != null && lastname.length() > 0) {
displayName += (displayName.length() > 0 ? " ":"") + lastname;
}
}
if (displayName.length() > 0) {
snb.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
}
ops.add(snb.build());
// Ask the Contact provider to create a new contact
Log.d(TAG,"Selected account: " + "ammo" + " (" + "ammo" + ")");
Log.d(TAG,"Creating contact: " + displayName);
try {
if (cr != null) {
ContentProviderResult[] cpres = cr.applyBatch(ContactsContract.AUTHORITY, ops);
return cpres[0].uri;
} else {
Log.w(TAG, "Content resolver is null -- will not add contact");
}
} catch (Exception ex) {
Log.e(TAG,"Exception encoutered while inserting contact: " + ex);
}
return null;
}
// deleteContactEntry()
// Delete an existing contact in the local contacts storage.
public Uri deleteContactEntry(Contact lw) {
return null;
}
// searchForContact()
public ArrayList<Contact> searchForContact(String searchTerm) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.d(TAG,"searchForContact() ");
}
Uri filterUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, searchTerm);
String contactId = "";
String displayName = "";
String lookupKey = "";
// Container to store search results
ArrayList<Contact> results = new ArrayList<Contact>();
// Perform a query
Cursor c = null;
String[] projection = {Contacts._ID, Contacts.DISPLAY_NAME, Contacts.LOOKUP_KEY};
try {
c = mResolver.query(filterUri, projection, null,null,null);
if (c == null) {
return null;
}
} catch (Throwable e) {
Log.e(TAG, "Exception: " + e.getMessage());
e.printStackTrace();
return null;
}
// Get data from the returned cursor
try {
int count = c.getCount();
if (count <= 0) {
return null;
}
for (int i = 0; i < count; i++) {
c.moveToNext();
contactId = c.getString(0);
displayName = c.getString(1);
lookupKey = c.getString(2);
Log.d(TAG,"Found contact: [" + contactId + "] " + displayName + " " + lookupKey);
// Populate results container
AmmoContacts.Contact lw = new AmmoContacts.Contact();
String[] names = displayName.split(" ");
lw.setName(names[0]);
lw.setLastName(names[1]);
lw.setLookup(lookupKey);
// Get "other" data for this contact, i.e. with data query
String[] dataProjection = {"mimetype","data1","data2","data3","data4"};
ArrayList<HashMap<String, String>> extraData = getDataForContact(contactId, dataProjection);
if (extraData != null) {
// If the data query failed (null), just keep what we've
// got so far (name and lookup) and go on to the next row.
// Otherwise get data, put in container.
populateContactData(extraData, lw);
}
results.add(lw);
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "IllegalArgumentException: " + e.getMessage());
e.printStackTrace();
return null;
} catch (CursorIndexOutOfBoundsException e) {
Log.e(TAG, "Cursor out of bounds: " + e.getMessage());
e.printStackTrace();
return null;
} catch (Throwable e) {
Log.e(TAG, "Exception: " + e.getMessage());
e.printStackTrace();
return null;
} finally {
c.close();
}
// Return the container of results
return results;
}
// populateContactData()
private void populateContactData(ArrayList<HashMap<String, String>> extraData,
AmmoContacts.Contact lw) {
Iterator<HashMap<String, String>> it = extraData.iterator();
while (it.hasNext()) {
try {
HashMap<String, String> f = it.next();
if (f != null) {
/*
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.d(TAG, " ITERATOR: " + String.valueOf(f.size()));
for (String d : f.keySet()) {
Log.d(TAG, " " + d + "= " + f.get(d));
}
}
*/
if (Constants.MIME_CALLSIGN.equals(f.get("mimetype"))) {
lw.setCallSign(f.get("data1") );
}
if (Constants.MIME_RANK.equals(f.get("mimetype"))) {
lw.setRank(f.get("data1") );
}
if (Constants.MIME_UNIT_NAME.equals(f.get("mimetype"))) {
lw.setUnit(f.get("data1") );
}
if (Constants.MIME_USERID.equals(f.get("mimetype"))) {
lw.setTigrUid(f.get("data1") );
}
if (Constants.MIME_USERID_NUM.equals(f.get("mimetype"))) {
lw.setUserIdNumber(f.get("data1") );
}
if (Constants.MIME_DESIGNATOR.equals(f.get("mimetype"))) {
lw.setDesignator(f.get("data1") );
}
if (StructuredName.CONTENT_ITEM_TYPE.equals(f.get("mimetype"))) {
lw.setName(f.get("data2"));
lw.setLastName(f.get("data3"));
}
}
} catch (NoSuchElementException e) {
Log.e(TAG, "NoSuchElementException: " + e.getMessage());
e.printStackTrace();
continue;
}
}
}
// getDataForContact()
private ArrayList<HashMap<String, String>> getDataForContact(String contactId,
String[] projection) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.d(TAG, "getDataForContact() ");
}
// Form the data URI for this contact
Uri dataUri = Uri.withAppendedPath(Uri.withAppendedPath(Contacts.CONTENT_URI, contactId), "data");
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.d(TAG, "data uri = " + dataUri.toString());
}
// Perform the query
Cursor c = mResolver.query(dataUri, projection, null,null,null);
if (c == null) {
Log.e(TAG, "getDataForContact() -- cursor is null");
return null;
}
// Debugging
/*
Log.d(TAG, " rows = " + String.valueOf(c.getCount()));
for (String d : c.getColumnNames()) {
Log.d(TAG, " got column: " + d + " ... index = " + c.getColumnIndex(d));
}
*/
if (projection != null) {
ArrayList<HashMap<String, String>> rows = new ArrayList<HashMap<String, String>>();
try {
int count = c.getCount();
for (int i = 0; i < count; i++) {
c.moveToNext();
HashMap<String, String> queryData = new HashMap<String,String>();
for (String proj : projection) {
int idx = c.getColumnIndexOrThrow(proj);
//Log.d(TAG, " storing " + proj + " idx=" + String.valueOf(idx));
queryData.put(proj, c.getString(idx));
}
rows.add(queryData);
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "IllegalArgumentException: " + e.getMessage());
e.printStackTrace();
return null;
}
return rows;
} else {
return null;
}
}
// getAllContacts()
public ArrayList<Contact> getAllContacts() {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.d(TAG,"getAllContacts() ");
}
Uri contactsUri = Contacts.CONTENT_URI;
// Container to store found contacts
ArrayList<Contact> results = new ArrayList<Contact>();
// Perform a query
String[] projection = {Contacts._ID, Contacts.DISPLAY_NAME, Contacts.LOOKUP_KEY};
Cursor c = mResolver.query(contactsUri, projection, null,null,null);
if (c == null) {
return null;
}
// Populate container with stuff from query
try {
int count = c.getCount();
if (count <= 0) {
return null;
}
String contactId = "";
String displayName = "";
String lookupKey = "";
for (int i = 0; i < count; i++) {
c.moveToNext();
contactId = c.getString(0);
displayName = c.getString(1);
lookupKey = c.getString(2);
//Log.d(TAG,"Found contact: [" + contactId + "] " + displayName + " " + lookupKey);
// Populate results container
AmmoContacts.Contact lw = new AmmoContacts.Contact();
if (displayName != null) {
String[] names = displayName.split(" ");
if (names.length > 0) {
if (names[0] != null) {
lw.setName(names[0]);
}
}
if (names.length > 1) {
if (names[1] != null) {
lw.setLastName(names[1]);
}
}
} else {
Log.e(TAG, "Error retrieving name for contact " + contactId);
continue;
}
lw.setLookup(lookupKey);
String[] dataProjection = {"mimetype","data1","data2","data3","data4"};
ArrayList<HashMap<String, String>> extraData = getDataForContact(contactId, dataProjection);
if (extraData != null) {
// populate other portions of Contact object
populateContactData(extraData, lw);
}
results.add(lw);
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "IllegalArgumentException: " + e.getMessage());
e.printStackTrace();
return null;
} catch (CursorIndexOutOfBoundsException e) {
Log.e(TAG, "Cursor out of bounds: " + e.getMessage());
e.printStackTrace();
return null;
} catch (Throwable e) {
Log.e(TAG, "Exception: " + e.getMessage());
e.printStackTrace();
return null;
} finally {
c.close();
}
return results;
}
// getContactByLookupKey()
public Contact getContactByLookupKey(String lookupKey) {
// Retrieve contact with provided uri
Log.d(TAG,"getContactByLookupKey() ");
ContentResolver cr = mResolver;
Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey);
Cursor c = cr.query(lookupUri, new String[]{Contacts.DISPLAY_NAME,Contacts._ID}, null,null,null);
AmmoContacts.Contact lw = new AmmoContacts.Contact();
try {
Log.d(TAG, " rows = " + String.valueOf(c.getCount()));
c.moveToFirst();
String displayName = c.getString(0);
if (displayName != null) {
String[] names = displayName.split(" ");
if (names.length > 0) {
if (names[0] != null) {
lw.setName(names[0]);
}
}
if (names.length > 1) {
if (names[1] != null) {
lw.setLastName(names[1]);
}
}
} else {
Log.e(TAG, "Error retrieving name for contact: display name is null");
}
String contactId = c.getString(1);
Log.d(TAG,"Found contact: " + displayName + " id=" + contactId);
// Get other data for this contact, i.e. with data query
String[] dataProjection = {"mimetype","data1","data2","data3","data4"};
ArrayList<HashMap<String, String>> extraData = getDataForContact(contactId, dataProjection);
if (extraData != null) {
populateContactData(extraData, lw);
}
} finally {
c.close();
}
return lw;
}
// getContactByIdNumber()
public Contact getContactByIdNumber(long idNumber) {
// Retrieve contact with provided unique ID number
Log.d(TAG,"getContactByIdNumber() ");
ContentResolver cr = mResolver;
Uri dataUri = Data.CONTENT_URI;
Log.d(TAG, "data uri = " + dataUri.toString());
String[] projection = {Data.RAW_CONTACT_ID, Data.DATA1};
String selection=Data.MIMETYPE+"=? AND " + Data.DATA1+"=?";
String[] selectionArgs={Constants.MIME_USERID_NUM, String.valueOf(idNumber)};
// Query the contacts content provider
Cursor c = null;
try {
c = cr.query(dataUri, projection, selection, selectionArgs,null);
if (c == null) {
Log.e(TAG, "getContactByIdNumber() -- cursor is null");
return null;
}
} catch (Throwable e) {
Log.e(TAG, "Exception: " + e.getMessage());
e.printStackTrace();
return null;
}
// Process the query's output
try {
int count = c.getCount();
//Log.d(TAG, "getContactByIdNumber() -- returned " + String.valueOf(count) + " rows");
if (count < 1) {
return null;
}
c.moveToFirst();
String contactId = c.getString(0);
AmmoContacts.Contact lw = new AmmoContacts.Contact();
lw.setUserIdNumber(c.getString(1) );
// Get other data for this contact
String[] dataProjection = {"mimetype","data1","data2","data3","data4"};
ArrayList<HashMap<String, String>> otherData = getDataForContact(contactId, dataProjection);
if (otherData != null) {
populateContactData(otherData, lw);
}
return lw;
} catch (IllegalArgumentException e) {
Log.e(TAG, "IllegalArgumentException: " + e.getMessage());
e.printStackTrace();
return null;
} catch (CursorIndexOutOfBoundsException e) {
Log.e(TAG, "Cursor out of bounds: " + e.getMessage());
e.printStackTrace();
return null;
} catch (Throwable e) {
Log.e(TAG, "Exception: " + e.getMessage());
e.printStackTrace();
return null;
} finally {
c.close();
}
}
// getContactByUserId()
public Contact getContactByUserId(String userId) {
Log.d(TAG,"getContactByUserId() ");
return null;
}
// findExistingContact()
// Internal utility function to get the URI for an existing
// contact in the database.
private Uri findExistingContact(Contact lw) {
Uri rval = null;
Log.d(TAG, "findExistingContact");
// Not the nice way to do this...
Uri f = Uri.parse("content://" + ContactsContract.AUTHORITY
+ "/data/userid/filter/" + lw.getTigrUid());
Log.d(TAG, " searching for uri = " + f.toString());
int contactId = -1;
try {
String[] projection = {"contact_id", "lookup"}; // more...
Cursor cursor = mResolver.query(f, projection, null, null, null);
if (cursor != null) {
// <DEBUG>
Log.d(TAG, " cursor size = " + String.valueOf(cursor.getCount()) );
Log.d(TAG, " -- examine cursor -- ");
for (String proj : cursor.getColumnNames() ) {
Log.d(TAG, " has column = " + proj + " -- index = "
+ cursor.getColumnIndex(proj) );
}
int dc = cursor.getCount();
Log.d(TAG, " cursor rows: " + String.valueOf(dc));
if (dc > 0) {
while (cursor.moveToNext() && (cursor.getPosition() < dc) ) {
Log.d(TAG, " row " + String.valueOf(cursor.getPosition()));
// Thing of interest
contactId = cursor.getInt(cursor.getColumnIndex("contact_id"));
Log.d(TAG, " contact id: " + String.valueOf(contactId));
}
}
// </DEBUG>
} else {
Log.d(TAG, "null");
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "IllegalArgumentException caught: " + e.getMessage());
e.printStackTrace();
return null;
} catch (Throwable e) {
Log.e(TAG, "An exception occurred: " + e.getMessage());
e.printStackTrace();
return null;
}
if (contactId > 0) {
rval = Uri.parse("content://com.android.contacts/raw_contacts/" + String.valueOf(contactId));
}
if (rval != null) {
Log.d(TAG, " existing contact uri: " + rval.toString());
}
return rval;
}
} |
package com.peer1.internetmap;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationUtils;
import android.widget.*;
import junit.framework.Assert;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.ScaleGestureDetector;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.support.v4.view.GestureDetectorCompat;
import android.util.Log;
import com.peer1.internetmap.ASNRequest.ASNResponseHandler;
import com.peer1.internetmap.SearchPopup.SearchNode;
import net.hockeyapp.android.CrashManager;
import net.hockeyapp.android.UpdateManager;
public class InternetMap extends Activity implements SurfaceHolder.Callback {
private static String TAG = "InternetMap";
private final String APP_ID = "9a3f1d8d25e8728007a8abf2d420beb9"; //HockeyApp id
private GestureDetectorCompat mGestureDetector;
private ScaleGestureDetector mScaleDetector;
private RotateGestureDetector mRotateDetector;
private MapControllerWrapper mController;
private Handler mHandler; //handles threadsafe messages
private VisualizationPopupWindow mVisualizationPopup;
private InfoPopup mInfoPopup;
private SearchPopup mSearchPopup;
private NodePopup mNodePopup;
private int mUserNodeIndex = -1; //cache user's node from "you are here"
private JSONObject mTimelineHistory; //history data for timeline
private ArrayList<String> mTimelineYears; //sorted year mapping
private int m2013Index; //index of 2013 in mTimelineYears
public int mCurrentVisualization; //cached for the visualization popup
private boolean mInTimelineMode; //true if we're showing the timeline
private CallbackHandler mCameraResetHandler;
private TimelinePopup mTimelinePopup;
public ArrayList<SearchNode> mAllSearchNodes; //cache of nodes for search
public boolean mDoneLoading;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
Log.i(TAG, "onCreate()");
//check HockeyApp for updates (comment this out for release)
UpdateManager.register(this, APP_ID);
//try to get into the best orientation before initializing the backend
forceOrientation();
nativeOnCreate(isSmallScreen());
setContentView(R.layout.main);
final SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
surfaceView.getHolder().addCallback(this);
//init a bunch of pointers
mGestureDetector = new GestureDetectorCompat(this, new MyGestureListener());
mScaleDetector = new ScaleGestureDetector(this, new ScaleListener());
mRotateDetector = new RotateGestureDetector(this, new RotateListener());
mController = new MapControllerWrapper();
mHandler = new Handler();
SeekBar timelineBar = (SeekBar) findViewById(R.id.timelineSeekBar);
timelineBar.setOnSeekBarChangeListener(new TimelineListener());
//fade out logo a bit after
ImageView logo = (ImageView) findViewById(R.id.peerLogo);
AlphaAnimation anim = new AlphaAnimation(1, 0.3f);
anim.setDuration(1000);
anim.setStartTime(AnimationUtils.currentAnimationTimeMillis()+4000);
anim.setFillAfter(true);
anim.setFillEnabled(true);
logo.setAnimation(anim);
}
void onBackendLoaded() {
//turn off loading feedback
ProgressBar loader = (ProgressBar) findViewById(R.id.loadingSpinner);
loader.setVisibility(View.GONE);
//possibly show first-run slides
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getBoolean("firstrun", true)) {
showHelp();
prefs.edit().putBoolean("firstrun", false).commit();
}
//reset all the togglebuttons that android helpfully restores for us :P
ToggleButton button = (ToggleButton) findViewById(R.id.searchButton);
button.setChecked(false);
button = (ToggleButton) findViewById(R.id.visualizationsButton);
button.setChecked(false);
button = (ToggleButton) findViewById(R.id.timelineButton);
button.setChecked(false);
button = (ToggleButton) findViewById(R.id.infoButton);
button.setChecked(false);
//start loading the search nodes
mHandler.post(new Runnable() {
public void run() {
NodeWrapper[] rawNodes = mController.allNodes();
Log.d(TAG, String.format("loaded %d nodes", rawNodes.length));
//initial search results: use all the nodes!
mAllSearchNodes = new ArrayList<SearchNode>(rawNodes.length);
for (int i = 0; i < rawNodes.length; i++) {
if (rawNodes[i] != null) {
mAllSearchNodes.add(new SearchNode(rawNodes[i]));
} else {
//Log.d(TAG, "caught null node"); //FIXME catch this in jni
}
}
Log.d(TAG, String.format("converted %d nodes", mAllSearchNodes.size()));
}
});
mDoneLoading = true;
}
public void showHelp() {
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.help, null);
HelpPopup popup = new HelpPopup(this, popupView);
//show it
View mainView = findViewById(R.id.mainLayout);
Assert.assertNotNull(mainView);
popup.setWidth(mainView.getWidth());
popup.setHeight(mainView.getHeight());
int gravity = Gravity.BOTTOM; //to avoid offset issues
popup.showAtLocation(mainView, gravity, 0, 0);
}
public void forceOrientation() {
Configuration config = getResources().getConfiguration();
int screenSize = config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
Log.d(TAG, String.format("Size: %d", screenSize));
int orientation = (screenSize <= Configuration.SCREENLAYOUT_SIZE_NORMAL) ?
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
setRequestedOrientation(orientation);
}
public byte[] readFileAsBytes(String filePath) throws java.io.IOException {
Log.i(TAG, String.format("Reading %s", filePath));
InputStream input = getAssets().open(filePath);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
return buffer;
}
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "onRestart()");
//force again in case the user was playing with an orientation app
forceOrientation();
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
//check HockeyApp for crashes. comment this out for release
CrashManager.register(this, APP_ID);
nativeOnResume();
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause()");
nativeOnPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
UpdateManager.unregister();
nativeOnDestroy();
}
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
android.view.Display display = getWindowManager().getDefaultDisplay();
int width, height;
//getSize is only available from api 13
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
} else {
width = display.getWidth();
height = display.getHeight();
}
Log.i(TAG, String.format("screen %d %d ", width, height, getResources().getDisplayMetrics().density));
Log.i(TAG, String.format("surface %d %d %.2f", w, h, getResources().getDisplayMetrics().density));
nativeSetSurface(holder.getSurface(), getResources().getDisplayMetrics().density);
}
public void surfaceCreated(SurfaceHolder holder) {
View loader = findViewById(R.id.loadingSpinner);
if (mDoneLoading && loader.getVisibility() != View.GONE) {
//something went weird, reset the UI
Log.d(TAG, "resetting loader and button state");
loader.setVisibility(View.GONE);
ToggleButton button = (ToggleButton) findViewById(R.id.searchButton);
button.setChecked(false);
button = (ToggleButton) findViewById(R.id.visualizationsButton);
button.setChecked(false);
button = (ToggleButton) findViewById(R.id.timelineButton);
button.setChecked(false);
button = (ToggleButton) findViewById(R.id.infoButton);
button.setChecked(false);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG, "surface destroyed");
nativeSetSurface(null, 1.0f);
}
//UI stuff
@Override
public boolean onTouchEvent(MotionEvent event){
//handle assorted gestures
mScaleDetector.onTouchEvent(event);
mRotateDetector.onTouchEvent(event);
mGestureDetector.onTouchEvent(event);
//ensure we clean up when the touch ends
if (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP) {
//Log.d(TAG, "touch end");
mController.setAllowIdleAnimation(true);
mController.unhoverNode();
}
return super.onTouchEvent(event);
}
public void visualizationsButtonPressed(View view) {
dismissPopups();
//make the button change sooner, and don't let them toggle the button while we're loading
final ToggleButton button = (ToggleButton)findViewById(R.id.visualizationsButton);
button.setChecked(true);
if (mVisualizationPopup == null) {
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.visualizationview, null);
mVisualizationPopup = new VisualizationPopupWindow(this, mController, popupView);
mVisualizationPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
public void onDismiss() {
mVisualizationPopup = null;
button.setChecked(false);
}
});
mVisualizationPopup.showAsDropDown(findViewById(R.id.visualizationsButton));
}
}
public void setVisualization(final int index) {
//note: assuming all popups are gone because the visualization popup just finished.
mCameraResetHandler = new CallbackHandler(){
public void handle() {
mCurrentVisualization = index;
mController.setVisualization(index);
}
};
mController.resetZoomAndRotationAnimated(isSmallScreen());
}
public void infoButtonPressed(View view) {
dismissPopups();
//make the button change sooner, and don't let them toggle the button while we're loading
final ToggleButton button = (ToggleButton)findViewById(R.id.infoButton);
button.setChecked(true);
if (mInfoPopup == null) {
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.visualizationview, null);
mInfoPopup = new InfoPopup(this, mController, popupView);
mInfoPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
public void onDismiss() {
mInfoPopup = null;
button.setChecked(false);
}
});
mInfoPopup.showAsDropDown(findViewById(R.id.infoButton));
}
}
public void searchButtonPressed(View view) {
dismissPopups();
//make the button change sooner, and don't let them toggle the button while we're loading
final ToggleButton button = (ToggleButton)findViewById(R.id.searchButton);
button.setChecked(true);
if (mSearchPopup == null) {
//this can be slow to load, so delay it until the UI updates the button
mHandler.post(new Runnable(){
public void run(){
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.searchview, null);
mSearchPopup = new SearchPopup(InternetMap.this, mController, popupView);
mSearchPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
public void onDismiss() {
mSearchPopup = null;
button.setChecked(false);
}
});
mSearchPopup.showAsDropDown(findViewById(R.id.searchButton));
}
});
}
}
public void findHost(final String host) {
Log.d(TAG, String.format("find host: %s", host));
if (!haveConnectivity()) {
return;
}
//TODO animate
final ProgressBar progress = (ProgressBar) findViewById(R.id.searchProgressBar);
final Button button = (Button) findViewById(R.id.searchButton);
progress.setVisibility(View.VISIBLE);
button.setVisibility(View.INVISIBLE);
//asn requests are unreliable sometimes, so set a backup timeout
final Runnable backupTimer = new Runnable() {
public void run() {
Log.d(TAG, "backup timer hit");
showError(getString(R.string.asnAssociationFail));
//stop animating
progress.setVisibility(View.INVISIBLE);
button.setVisibility(View.VISIBLE);
}
};
mHandler.postDelayed(backupTimer, 10000);
//dns lookup in the background
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String addrString;
try {
InetAddress address = InetAddress.getByName(host);
addrString = address.getHostAddress();
} catch (UnknownHostException e) {
addrString = "";
}
return addrString;
}
protected void onPostExecute(String addrString) {
if (addrString.isEmpty()) {
showError(String.format(getString(R.string.invalidHost), host));
//stop animating
progress.setVisibility(View.INVISIBLE);
button.setVisibility(View.VISIBLE);
mHandler.removeCallbacks(backupTimer);
} else {
Log.d(TAG, addrString);
ASNRequest.fetchASNForIP(addrString, new ASNResponseHandler() {
public void onStart() {
Log.d(TAG, "asnrequest2 start");
//nothing to do; already animating
}
public void onFinish() {
Log.d(TAG, "asnrequest2 finish");
//stop animating
progress.setVisibility(View.INVISIBLE);
button.setVisibility(View.VISIBLE);
mHandler.removeCallbacks(backupTimer);
}
public void onSuccess(JSONObject response) {
selectNodeByASN(response, false);
}
public void onFailure(Throwable e, String response) {
//tell the user
String message = getString(R.string.asnAssociationFail);
showError(message);
Log.d(TAG, message);
}
});
}
}
}.execute();
}
public void dismissSearchPopup(View unused) {
mSearchPopup.dismiss();
}
public void youAreHereButtonPressed() {
//check internet status
boolean isConnected = haveConnectivity();
if (!isConnected) {
return;
}
//asn requests are unreliable sometimes, so set a backup timeout
final Runnable backupTimer = new Runnable() {
public void run() {
Log.d(TAG, "backup timer hit");
showError(getString(R.string.currentASNFail));
//stop animating
ProgressBar progress = (ProgressBar) findViewById(R.id.searchProgressBar);
Button button = (Button) findViewById(R.id.searchButton);
progress.setVisibility(View.INVISIBLE);
button.setVisibility(View.VISIBLE);
}
};
mHandler.postDelayed(backupTimer, 10000);
//do an ASN request to get the user's ASN
ASNRequest.fetchCurrentASNWithResponseHandler(new ASNResponseHandler() {
public void onStart() {
Log.d(TAG, "asnrequest start");
//animate
ProgressBar progress = (ProgressBar) findViewById(R.id.searchProgressBar);
Button button = (Button) findViewById(R.id.searchButton);
progress.setVisibility(View.VISIBLE);
button.setVisibility(View.INVISIBLE);
}
public void onFinish() {
Log.d(TAG, "asnrequest finish");
//stop animating
ProgressBar progress = (ProgressBar) findViewById(R.id.searchProgressBar);
Button button = (Button) findViewById(R.id.searchButton);
progress.setVisibility(View.INVISIBLE);
button.setVisibility(View.VISIBLE);
mHandler.removeCallbacks(backupTimer);
}
public void onSuccess(JSONObject response) {
selectNodeByASN(response, true);
}
public void onFailure(Throwable e, String response) {
//tell the user
String message = getString(R.string.currentASNFail);
showError(message);
Log.d(TAG, message);
}
});
}
public void timelineButtonPressed(View view) {
Log.d(TAG, "timeline");
if (mInTimelineMode) {
dismissPopups(); //leave timeline mode
} else {
dismissPopups();
mController.resetZoomAndRotationAnimated(isSmallScreen());
SeekBar timelineBar = (SeekBar) findViewById(R.id.timelineSeekBar);
if (mTimelineHistory == null) {
//load history data & init the timeline bounds
try {
mTimelineHistory = new JSONObject(new String(readFileAsBytes("data/history.json")));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//get seekbar -> year mapping
mTimelineYears = new ArrayList<String>();
Iterator<?> it = mTimelineHistory.keys();
while(it.hasNext()){
String year = (String)it.next();
mTimelineYears.add(year);
}
Assert.assertTrue("Timeline must have at least two years", mTimelineYears.size() > 1);
timelineBar.setMax(mTimelineYears.size() - 1);
Collections.sort(mTimelineYears);
m2013Index = mTimelineYears.indexOf("2013");
Assert.assertTrue("Can't find 2013 in timeline data", m2013Index != -1);
}
timelineBar.setProgress(m2013Index);
timelineBar.setVisibility(View.VISIBLE);
timelineBar.requestLayout(); //hack to work around SurfaceView bug on some phones
mInTimelineMode = true;
//reset the node popup, the lazy way
if (mNodePopup != null) mNodePopup.dismiss();
//get the timeline popup up (even if the slider didn't change)
createTimelinePopup();
showTimelinePopup(timelineBar, timelineBar.getProgress());
}
}
public void dismissPopups() {
if (mInTimelineMode) {
SeekBar timelineBar = (SeekBar) findViewById(R.id.timelineSeekBar);
timelineBar.setVisibility(View.INVISIBLE);
resetViewAndSetTimeline(m2013Index);
mInTimelineMode = false;
ToggleButton button = (ToggleButton)findViewById(R.id.timelineButton);
button.setChecked(false);
}
if (mNodePopup != null) {
mNodePopup.dismiss();
}
//search and visualization popups dismiss themselves, we can ignore them here
}
void createTimelinePopup() {
Assert.assertNull(mTimelinePopup);
mTimelinePopup = new TimelinePopup(this);
}
void showTimelinePopup(SeekBar seekBar, int progress) {
Assert.assertNotNull(mTimelinePopup);
String year = mTimelineYears.get(progress);
mTimelinePopup.setData(year, mTimelineHistory.optString(year));
Log.d(TAG, year);
//update size/position
int offset, arrowOffset;
boolean needsUpdate;
if (isSmallScreen()) {
offset = 0;
arrowOffset = 0;
needsUpdate = ! mTimelinePopup.isShowing();
} else {
//calculate offset to line up with the timelineBar
int barWidth = seekBar.getWidth();
int maxProgress = seekBar.getMax();
int popupWidth = mTimelinePopup.getMeasuredWidth();
Drawable thumb = getResources().getDrawable(R.drawable.seek_thumb_normal);
float thumbOffset = (float) (thumb.getIntrinsicWidth() / 2.0);
//now get the distance from the screen edge to min. thumb centre
float barOffset = thumbOffset + seekBar.getPaddingLeft();
float innerBarWidth = barWidth - barOffset*2; //measure from the center of the thumb at its max/min
float progressRelativeXCenter = (innerBarWidth * (float)progress / maxProgress);
float progressXCenter = progressRelativeXCenter + barOffset;
offset = (int)(progressXCenter - popupWidth/2.0); //center over the thumb
//get the arrow in the right place even at the edges
//note: I'm assuming barWidth == screenWidth
//also, we now need to keep the popup on-screen manually.
int end = barWidth - popupWidth;
if (offset < 0) {
arrowOffset = offset;
offset = 0;
} else if (offset > end) {
arrowOffset = offset - end;
offset = end;
} else {
arrowOffset = 0;
}
needsUpdate = true;
}
if (needsUpdate) {
mTimelinePopup.showWithOffsets(offset, arrowOffset);
}
}
private class TimelineListener implements SeekBar.OnSeekBarChangeListener{
public void onStartTrackingTouch(SeekBar seekBar) {
if (mTimelinePopup == null) {
createTimelinePopup();
}
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (mTimelinePopup == null) {
//Log.d(TAG, "ignoring progresschange");
return;
}
showTimelinePopup(seekBar, progress);
}
public void onStopTrackingTouch(SeekBar seekBar) {
resetViewAndSetTimeline(seekBar.getProgress());
}
}
public void resetViewAndSetTimeline(final int yearIndex) {
if (mNodePopup != null) {
mNodePopup.dismiss();
}
//Assert.assertNotNull(mTimelinePopup);
if (mTimelinePopup != null) {
mTimelinePopup.showLoadingText();
}
mCameraResetHandler = new CallbackHandler(){
public void handle() {
String year = mTimelineYears.get(yearIndex);
mController.setTimelinePoint(year);
if (mTimelinePopup != null) {
mTimelinePopup.dismiss();
mTimelinePopup = null;
}
}
};
mController.resetZoomAndRotationAnimated(isSmallScreen());
}
//for handling the camera reset callback
private interface CallbackHandler {
public void handle();
}
public boolean haveConnectivity(){
//check Internet status
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = (activeNetwork == null) ? false : activeNetwork.isConnectedOrConnecting();
if (!isConnected) {
showError(getString(R.string.noInternet));
return false;
} else {
return true;
}
}
public void showError(String message) {
//TODO: I'm not sure if a dialog or a toast is most appropriate for errors.
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
public void selectNodeByASN(JSONObject response, boolean cacheIndex) {
//expected response format: {"payload":"ASxxxx"}
try {
String asnWithAS = response.getString("payload");
String asnString = asnWithAS.substring(2);
Log.d(TAG, String.format("2asn: %s", asnString));
//yay, an ASN! turn it into a node so we can target it.
NodeWrapper node = mController.nodeByAsn(asnString);
if (node != null) {
if (cacheIndex) {
mUserNodeIndex = node.index;
}
mController.updateTargetForIndex(node.index);
} else {
showError(getString(R.string.asnAssociationFail));
}
} catch (Exception e) {
Log.d(TAG, String.format("can't parse response: %s", response.toString()));
showError(getString(R.string.asnAssociationFail));
}
}
public boolean isSmallScreen() {
Configuration config = getResources().getConfiguration();
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//if the user forces a phone to landscape mode, the big-screen UI fits better.
return false;
}
int screenSize = config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
Log.d(TAG, String.format("size: %d", screenSize));
return screenSize <= Configuration.SCREENLAYOUT_SIZE_NORMAL;
}
//called from c++ via threadsafeShowNodePopup
public void showNodePopup() {
Log.d(TAG, "showNodePopup");
//get the current node
int index = mController.targetNodeIndex();
Log.d(TAG, String.format("node at index %d", index));
NodeWrapper node = mController.nodeAtIndex(index);
if (node == null) {
Log.d(TAG, "is null");
if (mNodePopup != null) {
mNodePopup.dismiss();
}
} else {
//node is ok; show the popup
Log.d(TAG, String.format("has index %d and asn %s", node.index, node.asn));
if (mNodePopup == null) {
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView;
if (mInTimelineMode) {
popupView = layoutInflater.inflate(R.layout.nodetimelineview, null);
} else {
popupView = layoutInflater.inflate(R.layout.nodeview, null);
if (isSmallScreen()) {
popupView.findViewById(R.id.leftArrow).setVisibility(View.GONE);
}
}
mNodePopup = new NodePopup(this, popupView, mInTimelineMode);
mNodePopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
public void onDismiss() {
mNodePopup = null;
mController.deselectCurrentNode();
mController.resetZoomAndRotationAnimated(isSmallScreen());
}
});
}
boolean isUserNode = (node.index == mUserNodeIndex);
mNodePopup.setNode(node, isUserNode);
//update size/position
View mainView = findViewById(R.id.surfaceview);
int gravity, width;
//note: PopupWindow appears to ignore gravity width/height hints
//and most of its size setters only take absolute numbers; setWindowLayoutMode is the exception
//but, setWindowLayoutMode doesn't properly handle absolute numbers either, so we may have to call *both*.
if (mInTimelineMode) {
gravity = Gravity.CENTER;
width = mainView.getWidth();
if (! isSmallScreen()) {
//full width looks odd on tablets
width = width / 2;
}
} else if (isSmallScreen()) {
gravity = Gravity.BOTTOM;
width = LayoutParams.MATCH_PARENT;
} else {
gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT;
width = mainView.getWidth() / 2;
}
mNodePopup.setWindowLayoutMode(width, LayoutParams.WRAP_CONTENT);
mNodePopup.setWidth(width);
int height = mNodePopup.getMeasuredHeight();
mNodePopup.setHeight(height); //work around weird bugs
//now that the height is calculated, we can calculate any offset
int offset;
if (mInTimelineMode) {
//move it up by half the height
offset = -height/2;
} else {
offset = 0;
}
if (gravity != Gravity.BOTTOM) {
//account for the top bar
int location[] = new int[2];
mainView.getLocationOnScreen(location);
int top = location[1];
offset += top / 2;
}
mNodePopup.showAtLocation(mainView, gravity, 0, offset);
//Log.d(TAG, String.format("showing : %d", mNodePopup.getHeight()));
}
}
//callbacks from the nodePopup UI
public void dismissNodePopup(View unused) {
mNodePopup.dismiss();
}
public void runTraceroute(View unused) throws JSONException, UnsupportedEncodingException{
Log.d(TAG, "TODO: traceroute");
//check internet status
boolean isConnected = haveConnectivity();
if (!isConnected) {
return;
}
String asn = "AS15169";
ASNRequest.fetchIPsForASN(asn, new ASNResponseHandler() {
public void onStart() {
}
public void onFinish() {
}
public void onSuccess(JSONObject response) {
try {
//Try and get legit payload here
Log.d(TAG, String.format("payload: %s", response));
} catch (Exception e) {
Log.d(TAG, String.format("Can't parse response: %s", response.toString()));
showError(getString(R.string.tracerouteStartIPFail));
}
}
public void onFailure(Throwable e, String response) {
String message = getString(R.string.tracerouteStartIPFail);
showError(message);
Log.d(TAG, message);
}
});
}
//native wrappers
public native void nativeOnCreate(boolean smallScreen);
public native void nativeOnResume();
public native void nativeOnPause();
public native void nativeOnDestroy();
public native void nativeSetSurface(Surface surface, float density);
//threadsafe callbacks for c++
public void threadsafeShowNodePopup() {
mHandler.post(new Runnable() {
public void run() {
showNodePopup();
}
});
}
public void threadsafeCameraResetCallback() {
mHandler.post(new Runnable() {
public void run() {
if (mCameraResetHandler != null) {
mCameraResetHandler.handle();
mCameraResetHandler = null;
}
}
});
}
public void threadsafeLoadFinishedCallback() {
mHandler.post(new Runnable() {
public void run() {
onBackendLoaded();
}
});
}
static {
System.loadLibrary("internetmaprenderer");
}
//simple one-finger gestures (eg. pan)
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private float distance2radians(float distance) {
return -0.01f * distance;
}
private float velocityAdjust(float velocity) {
return 0.002f * velocity;
}
@Override
public boolean onDown(MotionEvent event) {
float x = event.getX();
float y = event.getY();
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
int location[] = new int[2];
surfaceView.getLocationOnScreen(location);
int top = location[1];
int left = location[0];
//Log.d(TAG, String.format("onDown %f %f %d %d", x, y, top, left));
mController.setAllowIdleAnimation(false);
mController.handleTouchDownAtPoint(x - left, y - top);
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
//Log.d(TAG, String.format("onScroll: x %f y %f", distanceX, distanceY));
mController.rotateRadiansXY(distance2radians(distanceX), distance2radians(distanceY));
return true;
}
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
//Log.d(TAG, String.format("onFling: vx %f vy %f", velocityX, velocityY));
mController.startMomentumPanWithVelocity(velocityAdjust(velocityX), velocityAdjust(velocityY));
return true;
}
@Override
//note: if double tap is used this should probably s/Up/Confirmed
public boolean onSingleTapUp(MotionEvent e) {
//Log.d(TAG, "tap!");
boolean selected = mController.selectHoveredNode();
if (!selected && mNodePopup != null) {
mNodePopup.dismiss();
}
return true;
}
}
//zoom gesture
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
float scale = detector.getScaleFactor() - 1;
//Log.d(TAG, String.format("scale: %f", scale));
mController.zoomByScale(scale);
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
float scale = detector.getScaleFactor() - 1;
//Log.d(TAG, String.format("scaleEnd: %f", scale));
mController.startMomentumZoomWithVelocity(scale * 50);
}
}
//2-finger rotate gesture
private class RotateListener extends RotateGestureDetector.SimpleOnRotateGestureListener {
@Override
public boolean onRotate(RotateGestureDetector detector) {
float rotate = detector.getRotateFactor();
//Log.d(TAG, String.format("!!rotate: %f", rotate));
mController.rotateRadiansZ(-rotate);
return true;
}
@Override
public void onRotateEnd(RotateGestureDetector detector) {
float velocity = detector.getRotateFactor(); //FIXME not actually velocity. always seems to be 0
//Log.d(TAG, String.format("!!!!rotateEnd: %f", velocity));
mController.startMomentumRotationWithVelocity(velocity * 50);
}
}
} |
package sbt;
import org.scalatools.testing.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
public class ForkMain {
static class SubclassFingerscan implements TestFingerprint, Serializable {
private boolean isModule;
private String superClassName;
SubclassFingerscan(SubclassFingerprint print) {
isModule = print.isModule();
superClassName = print.superClassName();
}
public boolean isModule() { return isModule; }
public String superClassName() { return superClassName; }
}
static class AnnotatedFingerscan implements AnnotatedFingerprint, Serializable {
private boolean isModule;
private String annotationName;
AnnotatedFingerscan(AnnotatedFingerprint print) {
isModule = print.isModule();
annotationName = print.annotationName();
}
public boolean isModule() { return isModule; }
public String annotationName() { return annotationName; }
}
public static class ForkTestDefinition implements Serializable {
public String name;
public Fingerprint fingerprint;
public ForkTestDefinition(String name, Fingerprint fingerprint) {
this.name = name;
if (fingerprint instanceof SubclassFingerprint) {
this.fingerprint = new SubclassFingerscan((SubclassFingerprint) fingerprint);
} else {
this.fingerprint = new AnnotatedFingerscan((AnnotatedFingerprint) fingerprint);
}
}
}
static class ForkError extends Exception implements Serializable {
private String originalMessage;
private StackTraceElement[] originalStackTrace;
private ForkError cause;
ForkError(Throwable t) {
originalMessage = t.getMessage();
originalStackTrace = t.getStackTrace();
if (t.getCause() != null) cause = new ForkError(t.getCause());
}
public String getMessage() { return originalMessage; }
public StackTraceElement[] getStackTrace() { return originalStackTrace; }
public Exception getCause() { return cause; }
}
static class ForkEvent implements Event, Serializable {
private String testName;
private String description;
private Result result;
private Throwable error;
ForkEvent(Event e) {
testName = e.testName();
description = e.description();
result = e.result();
if (e.error() != null) error = new ForkError(e.error());
}
public String testName() { return testName; }
public String description() { return description; }
public Result result() { return result; }
public Throwable error() { return error; }
}
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getByName(null), Integer.valueOf(args[0]));
final ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
final ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
try {
new Run().run(is, os);
} finally {
is.close();
os.close();
}
}
private static class Run {
boolean matches(Fingerprint f1, Fingerprint f2) {
if (f1 instanceof SubclassFingerprint && f2 instanceof SubclassFingerprint) {
final SubclassFingerprint sf1 = (SubclassFingerprint) f1;
final SubclassFingerprint sf2 = (SubclassFingerprint) f2;
return sf1.isModule() == sf2.isModule() && sf1.superClassName().equals(sf2.superClassName());
} else if (f1 instanceof AnnotatedFingerprint && f2 instanceof AnnotatedFingerprint) {
AnnotatedFingerprint af1 = (AnnotatedFingerprint) f1;
AnnotatedFingerprint af2 = (AnnotatedFingerprint) f2;
return af1.isModule() == af2.isModule() && af1.annotationName().equals(af2.annotationName());
}
return false;
}
class RunAborted extends RuntimeException {
RunAborted(Exception e) { super(e); }
}
void write(ObjectOutputStream os, Object obj) {
try {
os.writeObject(obj);
os.flush();
} catch (IOException e) {
throw new RunAborted(e);
}
}
void runTests(ObjectInputStream is, final ObjectOutputStream os) throws Exception {
final boolean ansiCodesSupported = is.readBoolean();
final ForkTestDefinition[] tests = (ForkTestDefinition[]) is.readObject();
int nFrameworks = is.readInt();
Logger[] loggers = {
new Logger() {
public boolean ansiCodesSupported() { return ansiCodesSupported; }
public void error(String s) { write(os, new Object[]{ForkTags.Error, s}); }
public void warn(String s) { write(os, new Object[]{ForkTags.Warn, s}); }
public void info(String s) { write(os, new Object[]{ForkTags.Info, s}); }
public void debug(String s) { write(os, new Object[]{ForkTags.Debug, s}); }
public void trace(Throwable t) { write(os, t); }
}
};
for (int i = 0; i < nFrameworks; i++) {
final String implClassName = (String) is.readObject();
final String[] frameworkArgs = (String[]) is.readObject();
final Framework framework;
try {
framework = (Framework) Class.forName(implClassName).newInstance();
} catch (ClassNotFoundException e) {
write(os, new Object[]{ForkTags.Error, "Framework implementation '" + implClassName + "' not present."});
continue;
}
ArrayList<ForkTestDefinition> filteredTests = new ArrayList<ForkTestDefinition>();
for (Fingerprint testFingerprint : framework.tests()) {
for (ForkTestDefinition test : tests) {
if (matches(testFingerprint, test.fingerprint)) filteredTests.add(test);
}
}
final org.scalatools.testing.Runner runner = framework.testRunner(getClass().getClassLoader(), loggers);
for (ForkTestDefinition test : filteredTests) {
final List<ForkEvent> events = new ArrayList<ForkEvent>();
EventHandler handler = new EventHandler() { public void handle(Event e){ events.add(new ForkEvent(e)); } };
if (runner instanceof Runner2) {
((Runner2) runner).run(test.name, test.fingerprint, handler, frameworkArgs);
} else if (test.fingerprint instanceof TestFingerprint) {
runner.run(test.name, (TestFingerprint) test.fingerprint, handler, frameworkArgs);
} else {
write(os, new Object[]{ForkTags.Error, "Framework '" + framework + "' does not support test '" + test.name + "'"});
}
write(os, new Object[]{test.name, events.toArray(new ForkEvent[events.size()])});
}
}
write(os, ForkTags.Done);
is.readObject();
}
void run(ObjectInputStream is, final ObjectOutputStream os) throws Exception {
try {
runTests(is, os);
} catch (RunAborted e) {
System.err.println("Internal error when running tests: " + e.getMessage());
}
}
}
} |
package org.apollo.game.model.settings;
/**
* An enumeration representing the different privacy states for public, private and trade chat. This enumeration relies
* on the ordering of the elements within, which should be as follows: {@code ON}, {@code HIDE}, {@code FRIENDS},
* {@code OFF}, {@code FILTERABLE}.
*
* @author Kyle Stevenson
*/
public enum PrivacyState {
/**
* Represents the 'on' state, when all messages are displayed.
*/
ON(0),
/**
* Represents the 'hidden' state, when all public chat text is displayed over the heads of players, but not in the
* chat interface. This state only applies to public chat.
*/
HIDE(1),
/**
* Represents the 'friends' state, when only messages from friends and moderators are displayed.
*/
FRIENDS(2),
/**
* Represents the 'off' state, when only messages from moderators are displayed.
*/
OFF(3),
/**
* Represents the 'filterable' state - a custom state that filters 'unnecessary' server messages. This state only
* applies to public chat.
*/
FILTERABLE(4);
public static PrivacyState valueOf(int value, boolean chat) {
PrivacyState[] values = values();
if (!chat && value != 0) {
value++;
}
if (value < 0 || value >= values.length) {
throw new IllegalArgumentException("Invalid privacy option integer value specified: " + value + ".");
}
return values[value];
}
/**
* The numerical value used by the client.
*/
private final int value;
/**
* Creates the privacy state.
*
* @param value The numerical value.
*/
private PrivacyState(int value) {
this.value = value;
}
/**
* Converts this privacy state to an integer.
*
* @return The numerical value used by the client.
*/
public int toInteger(boolean chat) {
return chat ? value : (value == 0 ? 0 : value - 1);
}
} |
package pylos.view;
import java.util.List;
import pylos.Config;
import pylos.Pylos;
import pylos.controller.Controller;
import pylos.controller.screen.MainScreenController;
import pylos.model.Ball;
import pylos.model.Model;
import pylos.model.Position;
import pylos.view.appstate.ActionManager;
import pylos.view.appstate.FPSDisplayer;
import pylos.view.ball.PositionBallGraphics;
import com.jme3.app.SimpleApplication;
import com.jme3.asset.plugins.FileLocator;
import com.jme3.input.ChaseCamera;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import com.jme3.niftygui.NiftyJmeDisplay;
import com.jme3.scene.Node;
import com.jme3.system.AppSettings;
import com.jme3.system.Timer;
import com.jme3.util.SkyFactory;
import de.lessvoid.nifty.Nifty;
public class View extends SimpleApplication implements ActionListener {
static final String Quit = "Quit";
public BoardGraphics board;
public Lights lights;
ChaseCamera chaseCam;
CameraTarget cameraTarget;
public Node balls = new Node("Balls");
public Node positionBalls = new Node("Position Balls");
public Node positionsToMountBall = new Node("Positions to mount Ball");
Nifty nifty;
public MainScreenController screenController;
public View() {
super();
showSettings = false;
settings = new AppSettings(true);
settings.setResolution(Config.RESOLUTION[0], Config.RESOLUTION[1]);
settings.setTitle("Pylos");
}
@Override
public void simpleInitApp() {
assetManager.registerLocator(Pylos.assetsPath, FileLocator.class);
initKeys();
initCamera();
startNifty();
}
// simpleUpdate() is empty, everything is in AppState
void initKeys() {
inputManager.clearMappings();
inputManager.addMapping(Quit, new KeyTrigger(KeyInput.KEY_Q), new KeyTrigger(KeyInput.KEY_ESCAPE));
inputManager.addListener(this, Quit);
}
void initCamera() {
flyCam.setEnabled(false);
cameraTarget = new CameraTarget(this);
rootNode.attachChild(cameraTarget.geometry);
chaseCam = new ChaseCamera(cam, cameraTarget.geometry, inputManager);
chaseCam.setInvertVerticalAxis(true);
chaseCam.setDefaultHorizontalRotation(-FastMath.PI / 6);
chaseCam.setDefaultVerticalRotation(FastMath.PI / 4);
chaseCam.setMaxDistance(500);
}
void startNifty() {
guiNode.detachAllChildren();
NiftyJmeDisplay niftyDisplay = new NiftyJmeDisplay(assetManager, inputManager, audioRenderer, guiViewPort);
nifty = niftyDisplay.getNifty();
try {
nifty.fromXml(Pylos.assetsPath + "/Interface/NiftyUI.xml", "start_screen");
} catch (Exception e) {
e.printStackTrace();
}
guiViewPort.addProcessor(niftyDisplay);
}
void initBalls() {
for (Ball ball : Model.board.balls) {
ball.graphics.create(this);
balls.attachChild(ball.graphics);
}
board.drawBalls();
}
public void initGame() {
nifty.gotoScreen("main_screen");
rootNode.attachChild(balls);
board = new BoardGraphics(this);
rootNode.attachChild(board.getSpatial());
lights = new Lights(rootNode);
initBalls();
// AppState
stateManager.attach(new ActionManager());
stateManager.attach(new FPSDisplayer());
setStatus("Welcome to Pylos !");
Controller.initTurn();
}
// simpleUpdate() is empty, everything is in AppState
public void show() {
start();
}
public void updatePositionBalls() {
updateNodeFromPositions(positionBalls, Model.getPositionBalls());
}
public void updatePositionsToMount(Ball ball) {
updateNodeFromPositions(positionsToMountBall, Model.getPositionsToMount(ball));
}
public void updateNodeFromPositions(Node node, List<Position> positions) {
node.detachAllChildren();
for (Position position : positions) {
PositionBallGraphics graphics = new PositionBallGraphics(position);
board.place(graphics, position);
node.attachChild(graphics);
}
rootNode.attachChild(SkyFactory.createSky(assetManager,
assetManager.loadTexture("Models/Board/Texture/sky/Stellar_Layout_west.png"),
assetManager.loadTexture("Models/Board/Texture/sky/Stellar_Layout_east.png"),
assetManager.loadTexture("Models/Board/Texture/sky/Stellar_Layout_north.png"),
assetManager.loadTexture("Models/Board/Texture/sky/Stellar_Layout_south.png"),
assetManager.loadTexture("Models/Board/Texture/sky/Stellar_Layout_up.png"),
assetManager.loadTexture("Models/Board/Texture/sky/Stellar_Layout_down.png"),
new Vector3f(1, 1, 1)));
}
public Timer getTimer() {
return timer;
}
public void registerScreenController(MainScreenController screenController) {
this.screenController = screenController;
}
public void setStatus(String status) {
screenController.setStatus(status);
}
public void onAction(String action, boolean isPressed, float tpf) {
if (action == Quit)
Pylos.stop();
}
} |
package org.bouncycastle.jce.examples;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;
import org.bouncycastle.asn1.DERBMPString;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.jce.PrincipalUtil;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.x509.X509V1CertificateGenerator;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure;
import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure;
/**
* Example of how to set up a certificiate chain and a PKCS 12 store for
* a private individual - obviously you'll need to generate your own keys,
* and you may need to add a NetscapeCertType extension or add a key
* usage extension depending on your application, but you should get the
* idea! As always this is just an example...
*/
public class PKCS12Example
{
static char[] passwd = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' };
static X509V1CertificateGenerator v1CertGen = new X509V1CertificateGenerator();
static X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
/**
* we generate the CA's certificate
*/
public static Certificate createMasterCert(
PublicKey pubKey,
PrivateKey privKey)
throws Exception
{
// signers name
String issuer = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy Primary Certificate";
// subjects name - the same as we are self signed.
String subject = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy Primary Certificate";
// create the certificate - version 1
v1CertGen.setSerialNumber(BigInteger.valueOf(1));
v1CertGen.setIssuerDN(new X509Principal(issuer));
v1CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
v1CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)));
v1CertGen.setSubjectDN(new X509Principal(subject));
v1CertGen.setPublicKey(pubKey);
v1CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
X509Certificate cert = v1CertGen.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)cert;
// this is actually optional - but if you want to have control
// over setting the friendly name this is the way to do it...
bagAttr.setBagAttribute(
PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
new DERBMPString("Bouncy Primary Certificate"));
return cert;
}
/**
* we generate an intermediate certificate signed by our CA
*/
public static Certificate createIntermediateCert(
PublicKey pubKey,
PrivateKey caPrivKey,
X509Certificate caCert)
throws Exception
{
// subject name table.
Hashtable attrs = new Hashtable();
Vector order = new Vector();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.OU, "Bouncy Intermediate Certificate");
attrs.put(X509Principal.EmailAddress, "feedback-crypto@bouncycastle.org");
order.addElement(X509Principal.C);
order.addElement(X509Principal.O);
order.addElement(X509Principal.OU);
order.addElement(X509Principal.EmailAddress);
// create the certificate - version 3
v3CertGen.reset();
v3CertGen.setSerialNumber(BigInteger.valueOf(2));
v3CertGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)));
v3CertGen.setSubjectDN(new X509Principal(order, attrs));
v3CertGen.setPublicKey(pubKey);
v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
// extensions
v3CertGen.addExtension(
X509Extensions.SubjectKeyIdentifier,
false,
new SubjectKeyIdentifierStructure(pubKey));
v3CertGen.addExtension(
X509Extensions.AuthorityKeyIdentifier,
false,
new AuthorityKeyIdentifierStructure(caCert));
v3CertGen.addExtension(
X509Extensions.BasicConstraints,
true,
new BasicConstraints(0));
X509Certificate cert = v3CertGen.generate(caPrivKey);
cert.checkValidity(new Date());
cert.verify(caCert.getPublicKey());
PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)cert;
// this is actually optional - but if you want to have control
// over setting the friendly name this is the way to do it...
bagAttr.setBagAttribute(
PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
new DERBMPString("Bouncy Intermediate Certificate"));
return cert;
}
/**
* we generate a certificate signed by our CA's intermediate certficate
*/
public static Certificate createCert(
PublicKey pubKey,
PrivateKey caPrivKey,
PublicKey caPubKey)
throws Exception
{
// signers name table.
Hashtable sAttrs = new Hashtable();
Vector sOrder = new Vector();
sAttrs.put(X509Principal.C, "AU");
sAttrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
sAttrs.put(X509Principal.OU, "Bouncy Intermediate Certificate");
sAttrs.put(X509Principal.EmailAddress, "feedback-crypto@bouncycastle.org");
sOrder.addElement(X509Principal.C);
sOrder.addElement(X509Principal.O);
sOrder.addElement(X509Principal.OU);
sOrder.addElement(X509Principal.EmailAddress);
// subjects name table.
Hashtable attrs = new Hashtable();
Vector order = new Vector();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.CN, "Eric H. Echidna");
attrs.put(X509Principal.EmailAddress, "feedback-crypto@bouncycastle.org");
order.addElement(X509Principal.C);
order.addElement(X509Principal.O);
order.addElement(X509Principal.L);
order.addElement(X509Principal.CN);
order.addElement(X509Principal.EmailAddress);
// create the certificate - version 3
v3CertGen.reset();
v3CertGen.setSerialNumber(BigInteger.valueOf(3));
v3CertGen.setIssuerDN(new X509Principal(sOrder, sAttrs));
v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)));
v3CertGen.setSubjectDN(new X509Principal(order, attrs));
v3CertGen.setPublicKey(pubKey);
v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
// add the extensions
v3CertGen.addExtension(
X509Extensions.SubjectKeyIdentifier,
false,
new SubjectKeyIdentifierStructure(pubKey));
v3CertGen.addExtension(
X509Extensions.AuthorityKeyIdentifier,
false,
new AuthorityKeyIdentifierStructure(caPubKey));
X509Certificate cert = v3CertGen.generate(caPrivKey);
cert.checkValidity(new Date());
cert.verify(caPubKey);
PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)cert;
// this is also optional - in the sense that if you leave this
// out the keystore will add it automatically, note though that
// for the browser to recognise the associated private key this
// you should at least use the pkcs_9_localKeyId OID and set it
// to the same as you do for the private key's localKeyId.
bagAttr.setBagAttribute(
PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
new DERBMPString("Eric's Key"));
bagAttr.setBagAttribute(
PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
new SubjectKeyIdentifierStructure(pubKey));
return cert;
}
public static void main(
String[] args)
throws Exception
{
Security.addProvider(new BouncyCastleProvider());
// personal keys
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16));
RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec(
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16),
new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16),
new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16),
new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16),
new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16),
new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16),
new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));
// intermediate keys.
RSAPublicKeySpec intPubKeySpec = new RSAPublicKeySpec(
new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16),
new BigInteger("ffff", 16));
RSAPrivateCrtKeySpec intPrivKeySpec = new RSAPrivateCrtKeySpec(
new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16),
new BigInteger("ffff", 16),
new BigInteger("7deb1b194a85bcfd29cf871411468adbc987650903e3bacc8338c449ca7b32efd39ffc33bc84412fcd7df18d23ce9d7c25ea910b1ae9985373e0273b4dca7f2e0db3b7314056ac67fd277f8f89cf2fd73c34c6ca69f9ba477143d2b0e2445548aa0b4a8473095182631da46844c356f5e5c7522eb54b5a33f11d730ead9c0cff", 16),
new BigInteger("ef4cede573cea47f83699b814de4302edb60eefe426c52e17bd7870ec7c6b7a24fe55282ebb73775f369157726fcfb988def2b40350bdca9e5b418340288f649", 16),
new BigInteger("97c7737d1b9a0088c3c7b528539247fd2a1593e7e01cef18848755be82f4a45aa093276cb0cbf118cb41117540a78f3fc471ba5d69f0042274defc9161265721", 16),
new BigInteger("6c641094e24d172728b8da3c2777e69adfd0839085be7e38c7c4a2dd00b1ae969f2ec9d23e7e37090fcd449a40af0ed463fe1c612d6810d6b4f58b7bfa31eb5f", 16),
new BigInteger("70b7123e8e69dfa76feb1236d0a686144b00e9232ed52b73847e74ef3af71fb45ccb24261f40d27f98101e230cf27b977a5d5f1f15f6cf48d5cb1da2a3a3b87f", 16),
new BigInteger("e38f5750d97e270996a286df2e653fd26c242106436f5bab0f4c7a9e654ce02665d5a281f2c412456f2d1fa26586ef04a9adac9004ca7f913162cb28e13bf40d", 16));
// ca keys
RSAPublicKeySpec caPubKeySpec = new RSAPublicKeySpec(
new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16),
new BigInteger("11", 16));
RSAPrivateCrtKeySpec caPrivKeySpec = new RSAPrivateCrtKeySpec(
new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16),
new BigInteger("11", 16),
new BigInteger("92e08f83cc9920746989ca5034dcb384a094fb9c5a6288fcc4304424ab8f56388f72652d8fafc65a4b9020896f2cde297080f2a540e7b7ce5af0b3446e1258d1dd7f245cf54124b4c6e17da21b90a0ebd22605e6f45c9f136d7a13eaac1c0f7487de8bd6d924972408ebb58af71e76fd7b012a8d0e165f3ae2e5077a8648e619", 16),
new BigInteger("f75e80839b9b9379f1cf1128f321639757dba514642c206bbbd99f9a4846208b3e93fbbe5e0527cc59b1d4b929d9555853004c7c8b30ee6a213c3d1bb7415d03", 16),
new BigInteger("b892d9ebdbfc37e397256dd8a5d3123534d1f03726284743ddc6be3a709edb696fc40c7d902ed804c6eee730eee3d5b20bf6bd8d87a296813c87d3b3cc9d7947", 16),
new BigInteger("1d1a2d3ca8e52068b3094d501c9a842fec37f54db16e9a67070a8b3f53cc03d4257ad252a1a640eadd603724d7bf3737914b544ae332eedf4f34436cac25ceb5", 16),
new BigInteger("6c929e4e81672fef49d9c825163fec97c4b7ba7acb26c0824638ac22605d7201c94625770984f78a56e6e25904fe7db407099cad9b14588841b94f5ab498dded", 16),
new BigInteger("dae7651ee69ad1d081ec5e7188ae126f6004ff39556bde90e0b870962fa7b926d070686d8244fe5a9aa709a95686a104614834b0ada4b10f53197a5cb4c97339", 16));
// set up the keys
KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
PrivateKey caPrivKey = fact.generatePrivate(caPrivKeySpec);
PublicKey caPubKey = fact.generatePublic(caPubKeySpec);
PrivateKey intPrivKey = fact.generatePrivate(intPrivKeySpec);
PublicKey intPubKey = fact.generatePublic(intPubKeySpec);
PrivateKey privKey = fact.generatePrivate(privKeySpec);
PublicKey pubKey = fact.generatePublic(pubKeySpec);
Certificate[] chain = new Certificate[3];
chain[2] = createMasterCert(caPubKey, caPrivKey);
chain[1] = createIntermediateCert(intPubKey, caPrivKey, (X509Certificate)chain[2]);
chain[0] = createCert(pubKey, intPrivKey, intPubKey);
// add the friendly name for the private key
PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey;
// this is also optional - in the sense that if you leave this
// out the keystore will add it automatically, note though that
// for the browser to recognise which certificate the private key
// is associated with you should at least use the pkcs_9_localKeyId
// OID and set it to the same as you do for the private key's
// corresponding certificate.
bagAttr.setBagAttribute(
PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
new DERBMPString("Eric's Key"));
bagAttr.setBagAttribute(
PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
new SubjectKeyIdentifierStructure(pubKey));
// store the key and the certificate chain
KeyStore store = KeyStore.getInstance("PKCS12", "BC");
store.load(null, null);
// if you haven't set the friendly name and local key id above
// the name below will be the name of the key
store.setKeyEntry("Eric's Key", privKey, null, chain);
FileOutputStream fOut = new FileOutputStream("id.p12");
store.store(fOut, passwd);
fOut.close();
}
} |
package org.exist.xquery.value;
import org.exist.dom.AVLTreeNodeSet;
import org.exist.dom.NodeProxy;
import org.exist.dom.NodeSet;
import org.exist.memtree.DocumentImpl;
import org.exist.memtree.NodeImpl;
import org.exist.numbering.NodeId;
import org.exist.util.FastQSort;
import org.exist.xquery.Constants;
import org.exist.xquery.OrderSpec;
import org.exist.xquery.XPathException;
import org.exist.xquery.util.ExpressionDumper;
import org.w3c.dom.Node;
/**
* A sequence that sorts its entries in the order specified by the order specs of
* an "order by" clause. Used by {@link org.exist.xquery.ForExpr}.
*
* Contrary to class {@link org.exist.xquery.value.PreorderedValueSequence},
* all order expressions are evaluated once for each item in the sequence
* <b>while</b> items are added.
*
* @author wolf
*/
public class OrderedValueSequence extends AbstractSequence {
private OrderSpec orderSpecs[];
private Entry[] items = null;
private int count = 0;
private int state = 0;
// used to keep track of the type of added items.
private int itemType = Type.ANY_TYPE;
public OrderedValueSequence(OrderSpec orderSpecs[], int size) {
this.orderSpecs = orderSpecs;
if (size == 0)
size = 1;
this.items = new Entry[size];
}
/* (non-Javadoc)
* @see org.exist.xquery.value.Sequence#iterate()
*/
public SequenceIterator iterate() throws XPathException {
return new OrderedValueSequenceIterator();
}
/* (non-Javadoc)
* @see org.exist.xquery.value.AbstractSequence#unorderedIterator()
*/
public SequenceIterator unorderedIterator() throws XPathException {
return new OrderedValueSequenceIterator();
}
/* (non-Javadoc)
* @see org.exist.xquery.value.Sequence#getLength()
*/
public int getItemCount() {
return (items == null) ? 0 : count;
}
public boolean isEmpty() {
return isEmpty;
}
public boolean hasOne() {
return hasOne;
}
/* (non-Javadoc)
* @see org.exist.xquery.value.Sequence#add(org.exist.xquery.value.Item)
*/
public void add(Item item) throws XPathException {
if (hasOne)
hasOne = false;
if (isEmpty)
hasOne = true;
isEmpty = false;
if(count == 0 && items.length == 1) {
items = new Entry[2];
} else if (count == items.length) {
Entry newItems[] = new Entry[count * 2];
System.arraycopy(items, 0, newItems, 0, count);
items = newItems;
}
items[count++] = new Entry(item);
checkItemType(item.getType());
setHasChanged();
}
/* (non-Javadoc)
* @see org.exist.xquery.value.AbstractSequence#addAll(org.exist.xquery.value.Sequence)
*/
public void addAll(Sequence other) throws XPathException {
if(other.hasOne())
add(other.itemAt(0));
else if(!other.isEmpty()) {
for(SequenceIterator i = other.iterate(); i.hasNext(); ) {
Item next = i.nextItem();
if(next != null)
add(next);
}
}
}
public void sort() {
FastQSort.sort(items, 0, count - 1);
}
/* (non-Javadoc)
* @see org.exist.xquery.value.Sequence#itemAt(int)
*/
public Item itemAt(int pos) {
if(items != null && pos > -1 && pos < count)
return items[pos].item;
else
return null;
}
private void checkItemType(int type) {
if(itemType == Type.NODE || itemType == type)
return;
if(itemType == Type.ANY_TYPE)
itemType = type;
else
itemType = Type.NODE;
}
/* (non-Javadoc)
* @see org.exist.xquery.value.Sequence#getItemType()
*/
public int getItemType() {
return itemType;
}
/* (non-Javadoc)
* @see org.exist.xquery.value.Sequence#toNodeSet()
*/
public NodeSet toNodeSet() throws XPathException {
//return early
if (isEmpty())
return NodeSet.EMPTY_SET;
// for this method to work, all items have to be nodes
if(itemType != Type.ANY_TYPE && Type.subTypeOf(itemType, Type.NODE)) {
//Was ExtArrayNodeset() which orders the nodes in document order
//The order seems to change between different invocations !!!
NodeSet set = new AVLTreeNodeSet();
//We can't make it from an ExtArrayNodeSet (probably because it is sorted ?)
//NodeSet set = new ArraySet(100);
for (int i = 0; i < items.length; i++) {
//TODO : investigate why we could have null here
if (items[i] != null) {
NodeValue v = (NodeValue)items[i].item;
if(v.getImplementationType() != NodeValue.PERSISTENT_NODE) {
// found an in-memory document
org.exist.memtree.DocumentImpl doc = ((NodeImpl)v).getDocument();
if (doc==null) {
continue;
}
// make this document persistent: doc.makePersistent()
// returns a map of all root node ids mapped to the corresponding
// persistent node. We scan the current sequence and replace all
// in-memory nodes with their new persistent node objects.
DocumentImpl expandedDoc = doc.expandRefs(null);
org.exist.dom.DocumentImpl newDoc = expandedDoc.makePersistent();
if (newDoc != null) {
NodeId rootId = newDoc.getBrokerPool().getNodeFactory().createInstance();
for (int j = i; j < count; j++) {
v = (NodeValue) items[j].item;
if(v.getImplementationType() != NodeValue.PERSISTENT_NODE) {
NodeImpl node = (NodeImpl) v;
if (node.getDocument() == doc) {
node = expandedDoc.getNode(node.getNodeNumber());
NodeId nodeId = node.getNodeId();
if (nodeId == null)
throw new XPathException("Internal error: nodeId == null");
if (node.getNodeType() == Node.DOCUMENT_NODE)
nodeId = rootId;
else
nodeId = rootId.append(nodeId);
NodeProxy p = new NodeProxy(newDoc, nodeId, node.getNodeType());
if (p != null) {
// replace the node by the NodeProxy
items[j].item = p;
}
}
}
}
}
set.add((NodeProxy) items[i].item);
} else {
set.add((NodeProxy)v);
}
}
}
return set;
} else
throw new XPathException("Type error: the sequence cannot be converted into" +
" a node set. Item type is " + Type.getTypeName(itemType));
}
/* (non-Javadoc)
* @see org.exist.xquery.value.Sequence#isPersistentSet()
*/
public boolean isPersistentSet() {
if(count == 0)
return true;
if(itemType != Type.ANY_TYPE && Type.subTypeOf(itemType, Type.NODE)) {
NodeValue v;
for (int i = 0; i < count; i++) {
v = (NodeValue)items[i].item;
if(v.getImplementationType() != NodeValue.PERSISTENT_NODE)
return false;
}
return true;
}
return false;
}
public MemoryNodeSet toMemNodeSet() throws XPathException {
if(count == 0)
return MemoryNodeSet.EMPTY;
if(itemType == Type.ANY_TYPE || !Type.subTypeOf(itemType, Type.NODE)) {
throw new XPathException("Type error: the sequence cannot be converted into" +
" a node set. Item type is " + Type.getTypeName(itemType));
}
NodeValue v;
for (int i = 0; i < count; i++) {
v = (NodeValue)items[i].item;
if(v.getImplementationType() == NodeValue.PERSISTENT_NODE)
return null;
}
return new ValueSequence(this);
}
/* (non-Javadoc)
* @see org.exist.xquery.value.Sequence#removeDuplicates()
*/
public void removeDuplicates() {
// TODO: is this ever relevant?
}
private void setHasChanged() {
state = (state == Integer.MAX_VALUE ? state = 0 : state + 1);
}
public int getState() {
return state;
}
public boolean hasChanged(int previousState) {
return state != previousState;
}
public boolean isCacheable() {
return true;
}
private class Entry implements Comparable {
Item item;
AtomicValue values[];
public Entry(Item item) throws XPathException {
this.item = item;
values = new AtomicValue[orderSpecs.length];
for(int i = 0; i < orderSpecs.length; i++) {
Sequence seq = orderSpecs[i].getSortExpression().eval(null);
values[i] = AtomicValue.EMPTY_VALUE;
if(seq.hasOne()) {
values[i] = seq.itemAt(0).atomize();
} else if(seq.hasMany())
throw new XPathException("expected a single value for order expression " +
ExpressionDumper.dump(orderSpecs[i].getSortExpression()) +
" ; found: " + seq.getItemCount());
}
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Object o) {
Entry other = (Entry)o;
int cmp = 0;
AtomicValue a, b;
for(int i = 0; i < values.length; i++) {
try {
a = values[i];
b = other.values[i];
boolean aIsEmpty = (a.isEmpty() || (Type.subTypeOf(a.getType(), Type.NUMBER) && ((NumericValue) a).isNaN()));
boolean bIsEmpty = (b.isEmpty() || (Type.subTypeOf(b.getType(), Type.NUMBER) && ((NumericValue) b).isNaN()));
if (aIsEmpty) {
if (bIsEmpty)
// both values are empty
return Constants.EQUAL;
else if ((orderSpecs[i].getModifiers() & OrderSpec.EMPTY_LEAST) != 0)
cmp = Constants.INFERIOR;
else
cmp = Constants.SUPERIOR;
} else if (bIsEmpty) {
// we don't need to check for equality since we know a is not empty
if ((orderSpecs[i].getModifiers() & OrderSpec.EMPTY_LEAST) != 0)
cmp = Constants.SUPERIOR;
else
cmp = Constants.INFERIOR;
} else if (a == AtomicValue.EMPTY_VALUE && b != AtomicValue.EMPTY_VALUE) {
if((orderSpecs[i].getModifiers() & OrderSpec.EMPTY_LEAST) != 0)
cmp = Constants.INFERIOR;
else
cmp = Constants.SUPERIOR;
} else if (b == AtomicValue.EMPTY_VALUE && a != AtomicValue.EMPTY_VALUE) {
if((orderSpecs[i].getModifiers() & OrderSpec.EMPTY_LEAST) != 0)
cmp = Constants.SUPERIOR;
else
cmp = Constants.INFERIOR;
} else
cmp = a.compareTo(orderSpecs[i].getCollator(), b);
if((orderSpecs[i].getModifiers() & OrderSpec.DESCENDING_ORDER) != 0)
cmp = cmp * -1;
if(cmp != Constants.EQUAL)
break;
} catch (XPathException e) {
}
}
return cmp;
}
}
private class OrderedValueSequenceIterator implements SequenceIterator {
int pos = 0;
/* (non-Javadoc)
* @see org.exist.xquery.value.SequenceIterator#hasNext()
*/
public boolean hasNext() {
return pos < count;
}
/* (non-Javadoc)
* @see org.exist.xquery.value.SequenceIterator#nextItem()
*/
public Item nextItem() {
if(pos < count) {
return items[pos++].item;
}
return null;
}
}
} |
package org.griphyn.cPlanner.selector.replica;
import org.griphyn.cPlanner.classes.ReplicaLocation;
import org.griphyn.cPlanner.selector.ReplicaSelector;
import org.griphyn.cPlanner.common.LogManager;
import org.griphyn.cPlanner.common.PegasusProperties;
import org.griphyn.cPlanner.common.PegRandom;
import org.griphyn.common.catalog.ReplicaCatalogEntry;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
/**
* This replica selector only prefers replicas from the local host and that
* start with a file: URL scheme. It is useful, when you want to stagin
* files to a remote site from your submit host using the Condor file transfer
* mechanism.
*
* <p>
* In order to use the replica selector implemented by this class,
* <pre>
* - the property pegasus.selector.replica must be set to value Local
* </pre>
*
*
* @see org.griphyn.cPlanner.transfer.implementation.Condor
*
* @author Karan Vahi
* @version $Revision$
*/
public class Local implements ReplicaSelector {
/**
* A short description of the replica selector.
*/
private static String mDescription = "Local from submit host";
/**
* The scheme name for file url.
*/
protected static final String FILE_URL_SCHEME = "file:";
/**
* The handle to the logging object that is used to log the various debug
* messages.
*/
protected LogManager mLogger;
/**
* The properties object containing the properties passed to the planner.
*/
protected PegasusProperties mProps;
/**
* The overloaded constructor, that is called by load method.
*
* @param properties the <code>PegasusProperties</code> object containing all
* the properties required by Pegasus.
*
*
*/
public Local( PegasusProperties properties ){
mProps = properties;
mLogger = LogManager.getInstance();
}
/**
* Selects a random replica from all the replica's that have their
* site handle set to local and the pfn's start with a file url scheme.
*
* @param rl the <code>ReplicaLocation</code> object containing all
* the pfn's associated with that LFN.
* @param preferredSite the preffered site for picking up the replicas.
*
* @return <code>ReplicaCatalogEntry</code> corresponding to the location selected.
*
* @see org.griphyn.cPlanner.classes.ReplicaLocation
*/
public ReplicaCatalogEntry selectReplica( ReplicaLocation rl,
String preferredSite ){
ReplicaCatalogEntry rce;
ArrayList prefPFNs = new ArrayList();
int locSelected;
String site = null;
// mLogger.log("Selecting a pfn for lfn " + lfn + "\n amongst" + locations ,
// LogManager.DEBUG_MESSAGE_LEVEL);
for ( Iterator it = rl.pfnIterator(); it.hasNext(); ) {
rce = ( ReplicaCatalogEntry ) it.next();
site = rce.getResourceHandle();
if( site == null ){
//skip to next replica
continue;
}
//check if has pool attribute as local, and at same time
//start with a file url scheme
if( site.equals( "local" ) && rce.getPFN().startsWith( FILE_URL_SCHEME ) ){
prefPFNs.add( rce );
}
}
if ( prefPFNs.isEmpty() ) {
//select a random location from
//all the matching locations
//in all likelihood all the urls were file urls and none
//were associated with the preference pool.
throw new RuntimeException( "Unable to select any location on local site from " +
"the list passed for lfn " + rl.getLFN() );
} else {
//select a random location
//amongst the locations
//on the preference pool
int length = prefPFNs.size();
//System.out.println("No of locations found at pool " + prefPool + " are " + length);
locSelected = PegRandom.getInteger( length - 1 );
rce = ( ReplicaCatalogEntry ) prefPFNs.get( locSelected );
}
return rce;
}
/**
* This chooses a location amongst all the locations returned by the
* Replica Mechanism. If a location is found with re/pool attribute same
* as the preference pool, it is taken. This returns all the locations which
* match to the preference pool. This function is called to determine if a
* file does exist on the output pool or not beforehand. We need all the
* location to ensure that we are able to make a match if it so exists.
* Else a random location is selected and returned
*
* @param rl the <code>ReplicaLocation</code> object containing all
* the pfn's associated with that LFN.
* @param preferredSite the preffered site for picking up the replicas.
*
* @return <code>ReplicaLocation</code> corresponding to the replicas selected.
*
* @see org.griphyn.cPlanner.classes.ReplicaLocation
*/
public ReplicaLocation selectReplicas( ReplicaLocation rl,
String preferredSite ){
String lfn = rl.getLFN();
ReplicaLocation result = new ReplicaLocation();
result.setLFN( rl.getLFN() );
ReplicaCatalogEntry rce;
String site;
int noOfLocs = 0;
for ( Iterator it = rl.pfnIterator(); it.hasNext(); ) {
noOfLocs++;
rce = ( ReplicaCatalogEntry ) it.next();
site = rce.getResourceHandle();
if ( site != null && site.equals( preferredSite )) {
result.addPFN( rce );
}
else if ( site == null ){
mLogger.log(
" pool attribute not specified for the location objects" +
" in the Replica Catalog", LogManager.WARNING_MESSAGE_LEVEL);
}
}
if ( result.getPFNCount() == 0 ) {
//means we have to choose a random location between 0 and (noOfLocs -1)
int locSelected = PegRandom.getInteger( noOfLocs - 1 );
rce = ( ReplicaCatalogEntry ) rl.getPFN(locSelected );
result.addPFN( rce );
}
return result;
}
/**
* Returns a short description of the replica selector.
*
* @return string corresponding to the description.
*/
public String description(){
return mDescription;
}
} |
package org.intellij.ibatis;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiLiteralExpression;
import com.intellij.psi.javadoc.PsiDocTagValue;
import com.intellij.psi.filters.*;
import com.intellij.psi.filters.position.NamespaceFilter;
import com.intellij.psi.filters.position.ParentElementFilter;
import com.intellij.psi.impl.source.resolve.reference.PsiReferenceProvider;
import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.JavaClassReferenceProvider;
import com.intellij.psi.xml.XmlTag;
import org.intellij.ibatis.provider.*;
import org.intellij.ibatis.util.IbatisConstants;
import org.jetbrains.annotations.NotNull;
public class IbatisReferenceProvider implements ProjectComponent {
private Project project;
private ReferenceProvidersRegistry registry;
private NamespaceFilter ibatisSqlMapConfigNamespaceFilter;
private NamespaceFilter ibatisSqlMapNamespaceFilter;
public IbatisReferenceProvider(Project project) {
ibatisSqlMapConfigNamespaceFilter = new NamespaceFilter(IbatisConstants.CONFIGURATION_DTDS);
ibatisSqlMapNamespaceFilter = new NamespaceFilter(IbatisConstants.SQLMAP_DTDS);
this.project = project;
registry = ReferenceProvidersRegistry.getInstance(project);
}
public void initComponent() {
//statement id reference
registry.registerReferenceProvider(new SqlClientElementFilter(), PsiLiteralExpression.class, new StatementIdReferenceProvider());
JavaClassReferenceProvider classReferenceProvider = new JavaClassReferenceProvider();
IbatisClassShortcutsReferenceProvider classShortcutsReferenceProvider = new IbatisClassShortcutsReferenceProvider();
FieldAccessMethodReferenceProvider fieldAccessMethodReferenceProvider = new FieldAccessMethodReferenceProvider();
ResultMapReferenceProvider resultMapReferenceProvider = new ResultMapReferenceProvider();
ParameterMapReferenceProvider parameterMapReferenceProvider = new ParameterMapReferenceProvider();
SqlReferenceProvider sqlReferenceProvider = new SqlReferenceProvider();
TableColumnReferenceProvider tableColumnReferenceProvider = new TableColumnReferenceProvider();
//java class
registerXmlAttributeValueReferenceProvider(ibatisSqlMapConfigNamespaceFilter, "typeAlias", new String[]{"type"}, classReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "typeAlias", new String[]{"type"}, classReferenceProvider);
//ibatis class with shortcuts and type alias
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "parameterMap", new String[]{"class"}, classShortcutsReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "resultMap", new String[]{"class"}, classShortcutsReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "statement", new String[]{"parameterClass", "resultClass"}, classShortcutsReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "insert", new String[]{"parameterClass"}, classShortcutsReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "update", new String[]{"parameterClass"}, classShortcutsReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "delete", new String[]{"parameterClass"}, classShortcutsReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "select", new String[]{"parameterClass", "resultClass"}, classShortcutsReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "procedure", new String[]{"parameterClass", "resultClass"}, classShortcutsReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "selectKey", new String[]{"resultClass"}, classShortcutsReferenceProvider);
//field access method reference
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "result", new String[]{"property"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "parameter", new String[]{"property"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "isEqual", new String[]{"property", "compareProperty"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "isNotEqual", new String[]{"property", "compareProperty"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "isGreaterThan", new String[]{"property", "compareProperty"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "isGreaterEqual", new String[]{"property", "compareProperty"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "isLessThan", new String[]{"property", "compareProperty"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "isLessEuqal", new String[]{"property", "compareProperty"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "isPropertyAvailable", new String[]{"property"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "isNull", new String[]{"property"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "isNotNull", new String[]{"property"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "isEmpty", new String[]{"property"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "isNotEmpty", new String[]{"property"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "iterate", new String[]{"property"}, fieldAccessMethodReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "selectKey", new String[]{"keyProperty"}, fieldAccessMethodReferenceProvider);
//result map reference provider
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "statement", new String[]{"resultMap"}, resultMapReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "select", new String[]{"resultMap"}, resultMapReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "procedure", new String[]{"resultMap"}, resultMapReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "result", new String[]{"resultMap"}, resultMapReferenceProvider);
//parameter map reference provider
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "statement", new String[]{"parameterMap"}, parameterMapReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "insert", new String[]{"parameterMap"}, parameterMapReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "update", new String[]{"parameterMap"}, parameterMapReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "delete", new String[]{"parameterMap"}, parameterMapReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "select", new String[]{"parameterMap"}, parameterMapReferenceProvider);
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "procedure", new String[]{"parameterMap"}, parameterMapReferenceProvider);
//sql reference provider
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "include", new String[]{"refid"}, sqlReferenceProvider);
//table column reference provider
registerXmlAttributeValueReferenceProvider(ibatisSqlMapNamespaceFilter, "result", new String[]{"column"}, tableColumnReferenceProvider);
}
public void disposeComponent() {
}
@NotNull public String getComponentName() {
return "iBATIS Reference Provider";
}
public void projectOpened() {
}
public void projectClosed() {
}
private void registerXmlAttributeValueReferenceProvider(NamespaceFilter namespaceFilter, String tagName, String attributeNames[], PsiReferenceProvider referenceProvider) {
registry.registerXmlAttributeValueReferenceProvider(attributeNames, new ScopeFilter(new ParentElementFilter(new AndFilter(new ClassFilter(XmlTag.class), new AndFilter(new OrFilter(new TextFilter(tagName)), namespaceFilter)), 2)), referenceProvider);
}
} |
package org.nschmidt.ldparteditor.data;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
class VM11HideShow extends VM10Selector {
private HashMap<String, ArrayList<Boolean>> state = new HashMap<String, ArrayList<Boolean>>();
protected VM11HideShow(DatFile linkedDatFile) {
super(linkedDatFile);
}
public synchronized void showHidden() {
for (GData gd : dataToHide) {
gd.show();
}
dataToHide.clear();
}
public void hideSelection() {
for (GData1 data : selectedSubfiles) {
hide(data);
}
for (GData2 data : selectedLines) {
hide(data);
}
for (GData3 data : selectedTriangles) {
hide(data);
}
for (GData4 data : selectedQuads) {
hide(data);
}
for (GData5 data : selectedCondlines) {
hide(data);
}
for (Vertex vert : selectedVertices) {
Set<VertexManifestation> m = vertexLinkedToPositionInFile.get(vert);
boolean isHidden = true;
if (m == null) continue;
for (VertexManifestation vm : m) {
if (vm.getGdata().type() != 0 && vm.getGdata().visible) {
isHidden = false;
break;
}
}
if (isHidden)
hiddenVertices.add(vert);
}
clearSelection();
}
private void hide(GData gdata) {
gdata.hide();
hiddenData.add(gdata);
}
public void showAll() {
cleanupHiddenData();
for (GData ghost : hiddenData) {
ghost.show();
}
hiddenVertices.clear();
hiddenData.clear();
}
public HashMap<String, ArrayList<Boolean>> backupHideShowState() {
state.clear();
if (hiddenData.size() > 0) {
backup(linkedDatFile.getDrawChainStart(), state, 0, 0);
return state;
}
return new HashMap<String, ArrayList<Boolean>>();
}
public HashMap<String, ArrayList<Boolean>> backupHideShowState(HashMap<String, ArrayList<Boolean>> s) {
if (hiddenData.size() > 0) {
backup(linkedDatFile.getDrawChainStart(), s, 0, 0);
return s;
}
return new HashMap<String, ArrayList<Boolean>>();
}
private void backup(GData g, HashMap<String, ArrayList<Boolean>> s, int depth, int currentLine) {
final ArrayList<Boolean> st = new ArrayList<Boolean>();
int lineNumber = 1;
++depth;
final String key;
if (depth == 1) {
key = "TOP"; //$NON-NLS-1$
} else {
GData1 g1 = ((GDataInit) g).getParent();
key = depth + "|" + currentLine + " " + g1.shortName; //$NON-NLS-1$ //$NON-NLS-2$
}
s.put(key, st);
st.add(g.visible);
while ((g = g.getNext()) != null) {
final int type = g.type();
if (type > 0 && type < 6) {
st.add(g.visible);
if (type == 1) {
backup(((GData1) g).myGData, s, depth, lineNumber);
}
lineNumber++;
}
}
}
public HashMap<String, ArrayList<Boolean>> backupSelectedDataState(HashMap<String, ArrayList<Boolean>> s) {
if (selectedData.size() > 0) {
backup2(linkedDatFile.getDrawChainStart(), s, 0, 0);
return s;
}
return new HashMap<String, ArrayList<Boolean>>();
}
private void backup2(GData g, HashMap<String, ArrayList<Boolean>> s, int depth, int currentLine) {
final ArrayList<Boolean> st = new ArrayList<Boolean>();
int lineNumber = 1;
++depth;
final String key;
if (depth == 1) {
key = "TOP"; //$NON-NLS-1$
} else {
GData1 g1 = ((GDataInit) g).getParent();
key = depth + "|" + currentLine + " " + g1.shortName; //$NON-NLS-1$ //$NON-NLS-2$
}
s.put(key, st);
st.add(selectedData.contains(g));
while ((g = g.getNext()) != null) {
final int type = g.type();
if (type > 0 && type < 6) {
st.add(selectedData.contains(g));
if (type == 1) {
backup2(((GData1) g).myGData, s, depth, lineNumber);
}
lineNumber++;
}
}
}
public void backupHideShowAndSelectedState(HashMap<String, ArrayList<Boolean>> s1, HashMap<String, ArrayList<Boolean>> s2) {
backup3(linkedDatFile.getDrawChainStart(), s1, s2, 0, 0);
}
private void backup3(GData g, HashMap<String, ArrayList<Boolean>> s1, HashMap<String, ArrayList<Boolean>> s2, int depth, int currentLine) {
final ArrayList<Boolean> st1 = new ArrayList<Boolean>();
final ArrayList<Boolean> st2 = new ArrayList<Boolean>();
int lineNumber = 1;
++depth;
final String key;
if (depth == 1) {
key = "TOP"; //$NON-NLS-1$
} else {
GData1 g1 = ((GDataInit) g).getParent();
key = depth + "|" + currentLine + " " + g1.shortName; //$NON-NLS-1$ //$NON-NLS-2$
}
s1.put(key, st1);
s2.put(key, st2);
st1.add(g.visible);
st2.add(selectedData.contains(g));
while ((g = g.getNext()) != null) {
final int type = g.type();
if (type > 0 && type < 6) {
st1.add(g.visible);
st2.add(selectedData.contains(g));
if (type == 1) {
backup3(((GData1) g).myGData, s1, s2, depth, lineNumber);
}
lineNumber++;
}
}
}
public void restoreHideShowState() {
if (state.size() > 0) {
restore(linkedDatFile.getDrawChainStart(), state, 0, 0);
state.clear();
}
}
public void restoreHideShowState(HashMap<String, ArrayList<Boolean>> s) {
state.clear();
state.putAll(s);
restoreHideShowState();
}
private void restore(GData g, HashMap<String, ArrayList<Boolean>> s, int depth, int currentLine) {
int lineNumber = 1;
++depth;
final String key;
if (depth == 1) {
key = "TOP"; //$NON-NLS-1$
} else {
GData1 g1 = ((GDataInit) g).getParent();
key = depth + "|" + currentLine + " " + g1.shortName; //$NON-NLS-1$ //$NON-NLS-2$
}
ArrayList<Boolean> nl = new ArrayList<Boolean>();
nl.add(true);
s.putIfAbsent(key, nl);
final ArrayList<Boolean> st = s.get(key);
final int size = st.size();
g.visible = st.get(0);
if (!g.visible) hiddenData.add(g);
while ((g = g.getNext()) != null) {
final int type = g.type();
if (type > 0 && type < 6) {
if (lineNumber < size) {
g.visible = st.get(lineNumber);
} else {
g.visible = true;
}
if (!g.visible) hiddenData.add(g);
if (type == 1) {
restore(((GData1) g).myGData, s, depth, lineNumber);
}
lineNumber++;
}
}
}
public void restoreSelectedDataState(HashMap<String, ArrayList<Boolean>> s) {
if (s.size() > 0) {
restore2(linkedDatFile.getDrawChainStart(), s, 0, 0);
}
}
private void restore2(GData g, HashMap<String, ArrayList<Boolean>> s, int depth, int currentLine) {
int lineNumber = 1;
++depth;
final String key;
if (depth == 1) {
key = "TOP"; //$NON-NLS-1$
} else {
GData1 g1 = ((GDataInit) g).getParent();
key = depth + "|" + currentLine + " " + g1.shortName; //$NON-NLS-1$ //$NON-NLS-2$
}
ArrayList<Boolean> nl = new ArrayList<Boolean>();
nl.add(true);
s.putIfAbsent(key, nl);
final ArrayList<Boolean> st = s.get(key);
final int size = st.size();
if (st.get(0)) {
selectedData.add(g);
switch (g.type()) {
case 1:
selectedSubfiles.add((GData1) g);
break;
case 2:
selectedLines.add((GData2) g);
break;
case 3:
selectedTriangles.add((GData3) g);
break;
case 4:
selectedQuads.add((GData4) g);
break;
case 5:
selectedCondlines.add((GData5) g);
break;
default:
break;
}
}
while ((g = g.getNext()) != null) {
final int type = g.type();
if (type > 0 && type < 6) {
if (lineNumber < size) {
if (st.get(lineNumber)) {
selectedData.add(g);
switch (type) {
case 1:
selectedSubfiles.add((GData1) g);
break;
case 2:
selectedLines.add((GData2) g);
break;
case 3:
selectedTriangles.add((GData3) g);
break;
case 4:
selectedQuads.add((GData4) g);
break;
case 5:
selectedCondlines.add((GData5) g);
break;
default:
break;
}
}
}
if (type == 1) {
restore2(((GData1) g).myGData, s, depth, lineNumber);
}
lineNumber++;
}
}
}
} |
package org.plantuml.idea.rendering;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.plantuml.idea.util.ImageWithUrlData;
import java.io.File;
import java.util.Arrays;
import java.util.Map;
public class RenderCacheItem {
private Integer version;
private final String sourceFilePath;
/**
* source is also cached in imagesWithData
*/
private final String source;
private final File baseDir;
private final int zoom;
private int page;
private final Map<File, Long> includedFiles;
private final RenderResult imageResult;
private final ImageWithUrlData[] imagesWithData;
public RenderCacheItem(String sourceFilePath, String source, File baseDir, int zoom, int page, Map<File, Long> includedFiles, RenderResult imageResult, ImageWithUrlData[] imagesWithData, Integer version) {
this.sourceFilePath = sourceFilePath;
this.source = source;
this.baseDir = baseDir;
this.zoom = zoom;
this.page = page;
this.includedFiles = includedFiles;
this.imageResult = imageResult;
this.imagesWithData = imagesWithData;
this.version = version;
}
public boolean renderRequired(Project project, String source, int page) {
if (!this.source.equals(source)) {
return true;
}
if (imageMissing(page)) {
return true;
}
if (imageSourceChanged(page, source)) {
return true;
}
return includedFilesChanged(project);
}
private boolean imageSourceChanged(int page, String source) {
if (page == -1) {
for (int i = 0; i < imagesWithData.length; i++) {
ImageWithUrlData imageWithUrlData = imagesWithData[i];
if (imageWithUrlData != null && !source.equals(imageWithUrlData.getSource())) {
return true;
}
}
} else {
if (imagesWithData.length > page && !imagesWithData[page].getSource().equals(source)) {
return true;
}
}
return false;
}
private boolean imageMissing(int page) {
if (page == -1) {
for (int i = 0; i < imagesWithData.length; i++) {
ImageWithUrlData imageWithUrlData = imagesWithData[i];
if (imageWithUrlData == null) {
return true;
}
}
} else {
if (imagesWithData.length > page && imagesWithData[page] == null) {
return true;
}
}
return false;
}
public String getSourceFilePath() {
return sourceFilePath;
}
public String getSource() {
return source;
}
public File getBaseDir() {
return baseDir;
}
public RenderResult getImageResult() {
return imageResult;
}
public ImageWithUrlData[] getImagesWithData() {
return imagesWithData;
}
public boolean isIncludedFileChanged(VirtualFile file) {
File key = new File(file.getPath());
Long aLong = includedFiles.get(key);
if (aLong != null) {
FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
boolean changed = RenderCache.isChanged(fileDocumentManager, key, aLong, fileDocumentManager.getDocument(file));
if (changed) {
return true;
}
}
return false;
}
private boolean includedFilesChanged(Project project) {
boolean result = false;
Editor selectedTextEditor = FileEditorManager.getInstance(project).getSelectedTextEditor();
if (selectedTextEditor != null) {
FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
VirtualFile file = fileDocumentManager.getFile(selectedTextEditor.getDocument());
if (file != null) {
String path = file.getPath();
if (includedFiles != null) {
File key = new File(path);
Long timestamp = includedFiles.get(key);
if (timestamp != null && RenderCache.isChanged(fileDocumentManager, key, timestamp, selectedTextEditor.getDocument())) {
result = true;
}
}
}
}
return result;
}
public boolean isIncludedFile(VirtualFile file) {
File key = new File(file.getPath());
Long aLong = includedFiles.get(key);
return aLong != null;
}
public void setVersion(int version) {
this.version = version;
}
public Integer getVersion() {
return version;
}
public int getZoom() {
return zoom;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("version", version)
.append("sourceFilePath", sourceFilePath)
.append("baseDir", baseDir)
.append("zoom", zoom)
.append("page", page)
.append("includedFiles", includedFiles)
.append("imageResult", imageResult)
.append("imagesWithData", Arrays.toString(imagesWithData))
.toString();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.