answer
stringlengths
17
10.2M
package eu.ydp.empiria.player.client.module.selection.view; import java.util.ArrayList; import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.peterfranza.gwt.jaxb.client.parser.utils.XMLContent; import eu.ydp.empiria.player.client.controller.body.InlineBodyGeneratorSocket; import eu.ydp.empiria.player.client.gin.factory.SelectionModuleFactory; import eu.ydp.empiria.player.client.module.selection.model.UserAnswerType; import eu.ydp.empiria.player.client.resources.StyleNameConstants; import eu.ydp.gwtutil.client.event.factory.EventHandlerProxy; import eu.ydp.gwtutil.client.event.factory.UserInteractionHandlerFactory; public class SelectionModuleViewImpl implements SelectionModuleView{ public static final int ROWS_RESERVED_FOR_COLUMN_HEADER = 1; public static final int COLUMNS_RESERVED_FOR_ROW_HEADER = 1; @Inject private StyleNameConstants styleNameConstants; @Inject private SelectionModuleFactory selectionModuleFactory; @Inject private UserInteractionHandlerFactory userInteractionHandlerFactory; private List<List<SelectionChoiceButton>> choiceButtons; private InlineBodyGeneratorSocket inlineBodyGeneratorSocket; @UiField Panel mainPanel; @UiField Widget promptWidget; @UiField Grid selectionGrid; @UiTemplate("SelectionModuleView.ui.xml") interface SelectionModuleUiBinder extends UiBinder<Widget, SelectionModuleViewImpl> { }; @Override public void initialize(int amountOfItems, int amountOfChoices, InlineBodyGeneratorSocket inlineBodyGeneratorSocket){ this.inlineBodyGeneratorSocket = inlineBodyGeneratorSocket; SelectionModuleUiBinder uiBinder = GWT.create(SelectionModuleUiBinder.class); uiBinder.createAndBindUi(this); selectionGrid.resize(amountOfItems+1, amountOfChoices+1); choiceButtons = new ArrayList<List<SelectionChoiceButton>>(); } @Override public void setItemDisplayedName(XMLContent itemName, int itemNumber){ Widget itemTextLabel = inlineBodyGeneratorSocket.generateInlineBody(itemName.getValue(), true); itemTextLabel.setStyleName(styleNameConstants.QP_SELECTION_ITEM_LABEL()); itemTextLabel.addStyleName(styleNameConstants.QP_MARKANSWERS_LABEL_INACTIVE()); Panel itemContainer = new FlowPanel(); itemContainer.setStyleName(styleNameConstants.QP_SELECTION_ITEM()); itemContainer.addStyleName(styleNameConstants.QP_MARKANSWERS_MARKER_INACTIVE()); itemContainer.add(itemTextLabel); selectionGrid.setWidget(itemNumber + ROWS_RESERVED_FOR_COLUMN_HEADER, 0, itemContainer); } @Override public void setChoiceOptionDisplayedName(XMLContent choiceName, int choiceNumber){ Widget choiseTextWidget = inlineBodyGeneratorSocket.generateInlineBody(choiceName.getValue()); choiseTextWidget.setStyleName(styleNameConstants.QP_SELECTION_CHOICE()); selectionGrid.setWidget(0, choiceNumber+COLUMNS_RESERVED_FOR_ROW_HEADER, choiseTextWidget); } @Override public void createButtonForItemChoicePair(int itemNumber, int choiceNumber, String moduleStyleName){ SelectionChoiceButton choiceButton = selectionModuleFactory.createSelectionChoiceButton(moduleStyleName); Panel buttonPanel = new FlowPanel(); buttonPanel.setStyleName(styleNameConstants.QP_MARKANSWERS_BUTTON_INACTIVE()); buttonPanel.add(choiceButton); selectionGrid.setWidget( itemNumber+ROWS_RESERVED_FOR_COLUMN_HEADER, choiceNumber+COLUMNS_RESERVED_FOR_ROW_HEADER, buttonPanel); addNewChoiceButton(choiceButton, itemNumber); addMouseOverHandler(choiceButton); } private void addMouseOverHandler(final SelectionChoiceButton button) { EventHandlerProxy userOverHandler = userInteractionHandlerFactory.createUserOverHandler(new ChoiceButtonMouseInteractionCommand(button, true)); userOverHandler.apply(button); EventHandlerProxy userOutHandler = userInteractionHandlerFactory.createUserOutHandler(new ChoiceButtonMouseInteractionCommand(button, false)); userOutHandler.apply(button); } private void addNewChoiceButton(SelectionChoiceButton choiceButton, int itemNumber) { List<SelectionChoiceButton> buttonsOfItem; if(buttonsOfItemNotExists(itemNumber)){ buttonsOfItem = new ArrayList<SelectionChoiceButton>(); choiceButtons.add(buttonsOfItem); }else{ buttonsOfItem = choiceButtons.get(itemNumber); } buttonsOfItem.add(choiceButton); } private boolean buttonsOfItemNotExists(int itemNumber) { return choiceButtons.isEmpty() || itemNumber >= choiceButtons.size(); } @Override public void addClickHandlerToButton(int itemNumber, int choiceNumber, ClickHandler clickHandler){ final SelectionChoiceButton button = getButton(itemNumber, choiceNumber); button.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { button.setSelected(!button.isSelected()); button.updateStyle(); } }); button.addClickHandler(clickHandler); } @Override public void selectButton(int itemNumber, int choiceNumber){ SelectionChoiceButton selectionChoiceButton = getButton(itemNumber, choiceNumber); selectionChoiceButton.select(); } @Override public void unselectButton(int itemNumber, int choiceNumber) { SelectionChoiceButton selectionChoiceButton = getButton(itemNumber, choiceNumber); selectionChoiceButton.unselect(); } private SelectionChoiceButton getButton(int itemNumber, int choiceNumber) { List<SelectionChoiceButton> buttonsOfItem; String exceptionMessage = "Cannot select button of itemNumber: "+itemNumber+", choiceNumber:"+choiceNumber+" that is not existing!"; try{ buttonsOfItem = choiceButtons.get(itemNumber); }catch(ArrayIndexOutOfBoundsException e){ throw new RuntimeException(exceptionMessage); } SelectionChoiceButton selectionChoiceButton; try{ selectionChoiceButton = buttonsOfItem.get(choiceNumber); }catch(ArrayIndexOutOfBoundsException e){ throw new RuntimeException(exceptionMessage); } return selectionChoiceButton; } @Override public void lockButton(boolean lock, int itemNumber, int choiceNumber){ SelectionChoiceButton button = getButton(itemNumber, choiceNumber); button.setButtonEnabled(!lock); } @Override public void updateButtonStyle(int itemNumber, int choiceNumber, UserAnswerType styleState){ SelectionChoiceButton button = getButton(itemNumber, choiceNumber); Widget parentPanel = button.getParent(); switch (styleState) { case CORRECT: parentPanel.setStyleName(styleNameConstants.QP_MARKANSWERS_BUTTON_CORRECT()); break; case WRONG: parentPanel.setStyleName(styleNameConstants.QP_MARKANSWERS_BUTTON_WRONG()); break; case DEFAULT: parentPanel.setStyleName(styleNameConstants.QP_MARKANSWERS_BUTTON_INACTIVE()); break; case NONE: parentPanel.setStyleName(styleNameConstants.QP_MARKANSWERS_BUTTON_NONE()); break; default: break; } button.updateStyle(); } @Override public Widget asWidget() { return mainPanel; } }
package org.rstudio.studio.client.application.ui.impl; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.ImageElement; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.dom.client.Style.Position; import com.google.gwt.dom.client.Style.TextDecoration; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.CloseEvent; import com.google.gwt.event.logical.shared.CloseHandler; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.ui.*; import com.google.inject.Inject; import com.google.inject.Provider; import org.rstudio.core.client.BrowseCap; import org.rstudio.core.client.command.*; import org.rstudio.core.client.command.impl.WebMenuCallback; import org.rstudio.core.client.theme.res.ThemeResources; import org.rstudio.core.client.theme.res.ThemeStyles; import org.rstudio.core.client.widget.HyperlinkLabel; import org.rstudio.core.client.widget.MessageDialogLabel; import org.rstudio.core.client.widget.ToolbarButton; import org.rstudio.core.client.widget.ToolbarLabel; import org.rstudio.core.client.widget.ToolbarSeparator; import org.rstudio.core.client.widget.events.GlassVisibilityEvent; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.application.Desktop; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.application.events.LogoutRequestedEvent; import org.rstudio.studio.client.application.ui.ApplicationHeader; import org.rstudio.studio.client.application.ui.GlobalToolbar; import org.rstudio.studio.client.application.ui.ProjectPopupMenu; import org.rstudio.studio.client.application.ui.impl.header.HeaderPanel; import org.rstudio.studio.client.application.ui.impl.header.MenubarPanel; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.dialog.WebDialogBuilderFactory; import org.rstudio.studio.client.workbench.codesearch.CodeSearch; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.events.SessionInitEvent; import org.rstudio.studio.client.workbench.events.SessionInitHandler; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.SessionInfo; public class WebApplicationHeader extends Composite implements ApplicationHeader, WebApplicationHeaderOverlay.Context { public WebApplicationHeader() { RStudioGinjector.INSTANCE.injectMembers(this); } @Inject public void initialize( final Commands commands, EventBus eventBus, GlobalDisplay globalDisplay, ThemeResources themeResources, final Session session, Provider<CodeSearch> pCodeSearch) { commands_ = commands; eventBus_ = eventBus; globalDisplay_ = globalDisplay; overlay_ = new WebApplicationHeaderOverlay(); // Use the outer panel to just aggregate the menu bar/account area, // with the logo. The logo can't be inside the HorizontalPanel because // it needs to overflow out of the top of the panel, and it was much // easier to do this with absolute positioning. outerPanel_ = new FlowPanel(); outerPanel_.getElement().getStyle().setPosition(Position.RELATIVE); // large logo logoLarge_ = new Image(ThemeResources.INSTANCE.rstudio()); ((ImageElement)logoLarge_.getElement().cast()).setAlt("RStudio"); logoLarge_.getElement().getStyle().setBorderWidth(0, Unit.PX); // small logo logoSmall_ = new Image(ThemeResources.INSTANCE.rstudio_small()); ((ImageElement)logoSmall_.getElement().cast()).setAlt("RStudio"); logoSmall_.getElement().getStyle().setBorderWidth(0, Unit.PX); // link target for logo logoAnchor_ = new Anchor(); Style style = logoAnchor_.getElement().getStyle(); style.setPosition(Position.ABSOLUTE); style.setTop(5, Unit.PX); style.setLeft(18, Unit.PX); style.setTextDecoration(TextDecoration.NONE); style.setOutlineWidth(0, Unit.PX); // header container headerBarPanel_ = new HorizontalPanel() ; headerBarPanel_.setStylePrimaryName(themeResources.themeStyles().header()); headerBarPanel_.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); headerBarPanel_.setWidth("100%"); if (BrowseCap.INSTANCE.suppressBrowserForwardBack()) suppressBrowserForwardBack(); // override Cmd+W keybaord shortcut for Chrome if (BrowseCap.isChrome()) { int modifiers = (BrowseCap.hasMetaKey() ? KeyboardShortcut.META : KeyboardShortcut.CTRL) | KeyboardShortcut.ALT; AppCommand closeSourceDoc = commands.closeSourceDoc(); closeSourceDoc.setShortcut(new KeyboardShortcut(modifiers, 'W')); ShortcutManager.INSTANCE.register( modifiers, 'W', closeSourceDoc, "", "", ""); } // main menu advertiseEditingShortcuts(globalDisplay, commands); WebMenuCallback menuCallback = new WebMenuCallback(); commands.mainMenu(menuCallback); mainMenu_ = menuCallback.getMenu(); mainMenu_.setAutoHideRedundantSeparators(false); fixup(mainMenu_); mainMenu_.addStyleName(themeResources.themeStyles().mainMenu()); AppMenuBar.addSubMenuVisibleChangedHandler(new SubMenuVisibleChangedHandler() { public void onSubMenuVisibleChanged(SubMenuVisibleChangedEvent event) { // When submenus of the main menu appear, glass over any iframes // so that mouse clicks can make the menus disappear if (event.isVisible()) eventBus_.fireEvent(new GlassVisibilityEvent(true)); else eventBus_.fireEvent(new GlassVisibilityEvent(false)); } }); headerBarPanel_.add(mainMenu_); // commands panel (no widgets added until after session init) headerBarCommandsPanel_ = new HorizontalPanel(); headerBarCommandsPanel_.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); headerBarCommandsPanel_.setWidth("100%"); headerBarPanel_.add(headerBarCommandsPanel_); headerBarPanel_.setCellWidth(headerBarCommandsPanel_, "100%"); headerBarPanel_.setCellHorizontalAlignment(headerBarCommandsPanel_, HorizontalPanel.ALIGN_RIGHT); eventBus.addHandler(SessionInitEvent.TYPE, new SessionInitHandler() { public void onSessionInit(SessionInitEvent sie) { SessionInfo sessionInfo = session.getSessionInfo(); // complete toolbar initialization toolbar_.completeInitialization(sessionInfo); // add project tools to main menu projectMenuSeparator_ = createCommandSeparator(); headerBarPanel_.add(projectMenuSeparator_); projectMenuButton_ = new ProjectPopupMenu(sessionInfo, commands).getToolbarButton(); projectMenuButton_.addStyleName( ThemeStyles.INSTANCE.webHeaderBarCommandsProjectMenu()); headerBarPanel_.add(projectMenuButton_); showProjectMenu(!toolbar_.isVisible()); // record logo target url (if any) logoTargetUrl_ = sessionInfo.getUserHomePageUrl(); if (logoTargetUrl_ != null) { logoAnchor_.setHref(logoTargetUrl_); logoAnchor_.setTitle("RStudio Server Home"); logoLarge_.setResource(ThemeResources.INSTANCE.rstudio_home()); logoSmall_.setResource(ThemeResources.INSTANCE.rstudio_home_small()); } else { // no link, so ensure this doesn't get styled as clickable logoAnchor_.getElement().getStyle().setCursor(Cursor.DEFAULT); } // init commands panel in server mode if (!Desktop.isDesktop()) initCommandsPanel(sessionInfo); // notify overlay of global toolbar state overlay_.setGlobalToolbarVisible(WebApplicationHeader.this, toolbar_.isVisible()); } }); // create toolbar toolbar_ = new GlobalToolbar(commands, eventBus, pCodeSearch); toolbar_.addStyleName(themeResources.themeStyles().webGlobalToolbar()); // create host for project commands projectBarCommandsPanel_ = new HorizontalPanel(); toolbar_.addRightWidget(projectBarCommandsPanel_); // initialize widget initWidget(outerPanel_); } public void showToolbar(boolean showToolbar) { outerPanel_.clear(); if (showToolbar) { logoAnchor_.getElement().removeAllChildren(); logoAnchor_.getElement().appendChild(logoLarge_.getElement()); outerPanel_.add(logoAnchor_); HeaderPanel headerPanel = new HeaderPanel(headerBarPanel_, toolbar_); outerPanel_.add(headerPanel); mainMenu_.getElement().getStyle().setMarginLeft(18, Unit.PX); preferredHeight_ = 65; showProjectMenu(false); } else { logoAnchor_.getElement().removeAllChildren(); logoAnchor_.getElement().appendChild(logoSmall_.getElement()); outerPanel_.add(logoAnchor_); MenubarPanel menubarPanel = new MenubarPanel(headerBarPanel_); outerPanel_.add(menubarPanel); mainMenu_.getElement().getStyle().setMarginLeft(0, Unit.PX); preferredHeight_ = 45; showProjectMenu(true); } overlay_.setGlobalToolbarVisible(this, showToolbar); } public boolean isToolbarVisible() { return !projectMenuButton_.isVisible(); } public void focusGoToFunction() { toolbar_.focusGoToFunction(); } private void showProjectMenu(boolean show) { projectMenuSeparator_.setVisible(show); projectMenuButton_.setVisible(show); } private native final void suppressBrowserForwardBack() /*-{ try { var outerWindow = $wnd.parent; if (outerWindow.addEventListener) { var handler = function(evt) { if ((evt.keyCode == 37 || evt.keyCode == 39) && (evt.metaKey && !evt.ctrlKey && !evt.shiftKey && !evt.altKey)) { evt.preventDefault(); evt.stopPropagation(); } }; outerWindow.addEventListener('keydown', handler, false); $wnd.addEventListener('keydown', handler, false); } } catch(err) {} }-*/; private void advertiseEditingShortcuts(final GlobalDisplay display, final Commands commands) { int mod = BrowseCap.hasMetaKey() ? KeyboardShortcut.META : KeyboardShortcut.CTRL; commands.undoDummy().setShortcut(new KeyboardShortcut(mod, 'Z')); commands.redoDummy().setShortcut(new KeyboardShortcut(mod| KeyboardShortcut.SHIFT, 'Z')); commands.cutDummy().setShortcut(new KeyboardShortcut(mod, 'X')); commands.copyDummy().setShortcut(new KeyboardShortcut(mod, 'C')); commands.pasteDummy().setShortcut(new KeyboardShortcut(mod, 'V')); CommandHandler useKeyboardNotification = new CommandHandler() { public void onCommand(AppCommand command) { MessageDialogLabel label = new MessageDialogLabel(); label.setHtml("Your browser does not allow access to your<br/>" + "computer's clipboard. As a result you must<br/>" + "use keyboard shortcuts for:" + "<br/><br/><table cellpadding=0 cellspacing=0 border=0>" + makeRow(commands.undoDummy()) + makeRow(commands.redoDummy()) + makeRow(commands.cutDummy()) + makeRow(commands.copyDummy()) + makeRow(commands.pasteDummy()) + "</table>" ); new WebDialogBuilderFactory().create( GlobalDisplay.MSG_WARNING, "Use Keyboard Shortcut", label).showModal(); } private String makeRow(AppCommand cmd) { String textAlign = BrowseCap.hasMetaKey() ? "text-align: right" : ""; return "<tr><td>" + cmd.getMenuLabel(false) + "</td>" + "<td style='padding-left: 12px; " + textAlign + "'>" + cmd.getShortcutPrettyHtml() + "</td></tr>"; } }; commands.undoDummy().addHandler(useKeyboardNotification); commands.redoDummy().addHandler(useKeyboardNotification); commands.cutDummy().addHandler(useKeyboardNotification); commands.copyDummy().addHandler(useKeyboardNotification); commands.pasteDummy().addHandler(useKeyboardNotification); } public int getPreferredHeight() { return preferredHeight_; } /** * Without this fixup, the main menu doesn't properly deselect its items * when the mouse takes focus away. */ private void fixup(final AppMenuBar mainMenu) { mainMenu.addCloseHandler(new CloseHandler<PopupPanel>() { public void onClose(CloseEvent<PopupPanel> popupPanelCloseEvent) { // Only dismiss the selection if the panel that just closed belongs // to the currently selected item. Otherwise, the selected item // has already changed and we don't want to mess with it. (This is // NOT an edge case, it is very common.) MenuItem menuItem = mainMenu.getSelectedItem(); if (menuItem != null) { MenuBar subMenu = menuItem.getSubMenu(); if (subMenu != null && popupPanelCloseEvent.getTarget() != null && subMenu.equals(popupPanelCloseEvent.getTarget().getWidget())) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { mainMenu.selectItem(null); } }); } } } }); } private void initCommandsPanel(final SessionInfo sessionInfo) { // add username if (sessionInfo.getShowIdentity()) { ToolbarLabel usernameLabel = new ToolbarLabel(); usernameLabel.getElement().getStyle().setMarginRight(2, Unit.PX); if (!BrowseCap.isFirefox()) usernameLabel.getElement().getStyle().setMarginTop(2, Unit.PX); String userIdentity = sessionInfo.getUserIdentity(); usernameLabel.setTitle(userIdentity); userIdentity = userIdentity.split("@")[0]; usernameLabel.setText(userIdentity); headerBarCommandsPanel_.add(usernameLabel); ToolbarButton signOutButton = new ToolbarButton(RESOURCES.signOut(), new ClickHandler() { public void onClick(ClickEvent event) { eventBus_.fireEvent(new LogoutRequestedEvent()); } }); signOutButton.setTitle("Sign out"); headerBarCommandsPanel_.add(signOutButton); headerBarCommandsPanel_.add( signOutSeparator_ = createCommandSeparator()); } overlay_.addCommands(this); headerBarCommandsPanel_.add(commands_.quitSession().createToolbarButton()); } private Widget createCommandSeparator() { ToolbarSeparator sep = new ToolbarSeparator(); Style style = sep.getElement().getStyle(); style.setMarginTop(2, Unit.PX); style.setMarginLeft(3, Unit.PX); return sep; } private Widget createCommandLink(String caption, ClickHandler clickHandler) { HyperlinkLabel link = new HyperlinkLabel(caption, clickHandler); return link; } @Override public void addCommand(Widget widget) { headerBarCommandsPanel_.add(widget); } @Override public Widget addCommandSeparator() { Widget separator = createCommandSeparator(); headerBarCommandsPanel_.add(separator); return separator; } @Override public void addLeftCommand(Widget widget) { addLeftCommand(widget, null); } @Override public void addLeftCommand(Widget widget, String width) { headerBarCommandsPanel_.insert(widget, 0); if (width != null) { headerBarCommandsPanel_.setCellWidth(widget, width); } } @Override public void addRightCommand(Widget widget) { headerBarPanel_.add(widget); } @Override public Widget addRightCommandSeparator() { Widget separator = createCommandSeparator(); headerBarPanel_.add(separator); return separator; } @Override public void addProjectCommand(Widget widget) { projectBarCommandsPanel_.add(widget); } @Override public Widget addProjectCommandSeparator() { Widget separator = createCommandSeparator(); projectBarCommandsPanel_.add(separator); return separator; } @Override public void addProjectRightCommand(Widget widget) { toolbar_.addRightWidget(widget); } @Override public Widget addProjectRightCommandSeparator() { return toolbar_.addRightSeparator(); } @Override public AppMenuBar getMainMenu() { return mainMenu_; } public Widget asWidget() { return this; } interface Resources extends ClientBundle { ImageResource signOut(); } private static final Resources RESOURCES = (Resources) GWT.create(Resources.class); private int preferredHeight_; private FlowPanel outerPanel_; private Anchor logoAnchor_; private Image logoLarge_; private Image logoSmall_; private String logoTargetUrl_ = null; private HorizontalPanel headerBarPanel_; private HorizontalPanel headerBarCommandsPanel_; private HorizontalPanel projectBarCommandsPanel_; private Widget signOutSeparator_; private Widget projectMenuSeparator_; private ToolbarButton projectMenuButton_; private AppMenuBar mainMenu_; private GlobalToolbar toolbar_; private EventBus eventBus_; private GlobalDisplay globalDisplay_; private Commands commands_; private WebApplicationHeaderOverlay overlay_; }
package org.rstudio.studio.client.common.mathjax; import java.util.ArrayList; import java.util.List; import org.rstudio.studio.client.common.mathjax.display.MathJaxPopupPanel; import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range; import org.rstudio.studio.client.workbench.views.source.editors.text.events.CursorChangedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.events.CursorChangedHandler; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.logical.shared.AttachEvent; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Event.NativePreviewEvent; import com.google.gwt.user.client.Event.NativePreviewHandler; public class MathJaxBackgroundRenderer { public MathJaxBackgroundRenderer(MathJax mathjax, MathJaxPopupPanel popup, DocDisplay docDisplay) { mathjax_ = mathjax; popup_ = popup; docDisplay_ = docDisplay; handlers_ = new ArrayList<HandlerRegistration>(); renderTimer_ = new Timer() { @Override public void run() { Range range = MathJaxUtil.getLatexRange(docDisplay_); if (range == null) return; mathjax_.renderLatex(range, true); } }; mouseIdleTimer_ = new Timer() { @Override public void run() { Position position = docDisplay_.screenCoordinatesToDocumentPosition(pageX_, pageY_); Range range = MathJaxUtil.getLatexRange(docDisplay_, position); if (range == null) return; mathjax_.renderLatex(range, true); } }; handlers_.add(docDisplay_.addFocusHandler(new FocusHandler() { @Override public void onFocus(FocusEvent event) { beginMonitoring(); } })); handlers_.add(docDisplay_.addBlurHandler(new BlurHandler() { @Override public void onBlur(BlurEvent event) { endMonitoring(); } })); handlers_.add(docDisplay_.addAttachHandler(new AttachEvent.Handler() { @Override public void onAttachOrDetach(AttachEvent event) { if (!event.isAttached()) onDetach(); } })); } private void beginMonitoring() { endMonitoring(); String id = docDisplay_.getModeId(); if (!id.equals("mode/rmarkdown")) return; previewHandler_ = Event.addNativePreviewHandler(new NativePreviewHandler() { @Override public void onPreviewNativeEvent(NativePreviewEvent preview) { if (preview.getTypeInt() != Event.ONMOUSEMOVE) { mouseIdleTimer_.cancel(); return; } NativeEvent event = preview.getNativeEvent(); pageX_ = event.getClientX(); pageY_ = event.getClientY(); mouseIdleTimer_.schedule(700); } }); cursorChangedHandler_ = docDisplay_.addCursorChangedHandler(new CursorChangedHandler() { @Override public void onCursorChanged(CursorChangedEvent event) { int delayMs = 700; if (MathJaxUtil.isSelectionWithinLatexChunk(docDisplay_)) delayMs = 200; else if (popup_.isShowing()) delayMs = 200; renderTimer_.schedule(delayMs); } }); } private void endMonitoring() { if (previewHandler_ != null) { previewHandler_.removeHandler(); previewHandler_ = null; } if (cursorChangedHandler_ != null) { cursorChangedHandler_.removeHandler(); cursorChangedHandler_ = null; } } private void onDetach() { endMonitoring(); for (HandlerRegistration handler : handlers_) handler.removeHandler(); handlers_.clear(); } private final MathJax mathjax_; private final MathJaxPopupPanel popup_; private final DocDisplay docDisplay_; private final List<HandlerRegistration> handlers_; private final Timer renderTimer_; private HandlerRegistration previewHandler_; private HandlerRegistration cursorChangedHandler_; private int pageX_; private int pageY_; private final Timer mouseIdleTimer_; }
package lo.wolo.pokerclient; import java.util.UUID; import java.util.List; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import android.text.InputType; import android.util.Log; import android.view.inputmethod.EditorInfo; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; /*** * Activity that handles the listview for received text, the edit field for text to * send and the send button. * <p> * There is nothing c3 specific here. */ public class ChatActivity extends AbstractServiceUsingActivity { ChatAdapter cadapter; ListView lview; TextView currentRoleView = null; TextView currentMoneyView = null; private Button raiseButton = null; private Button foldButton = null; private Button checkButton = null; private Button callButton = null; private Button allinButton = null; private Button betButton = null; private ImageView card1Image = null; private ImageView card2Image = null; int card1 = -1; int card2 = -1; int curbet = 0; int minbet = 1; int money = 10; int amount = 0; static final int cardDrawables[] = { R.drawable.card_00, R.drawable.card_01, R.drawable.card_02, R.drawable.card_03, R.drawable.card_04, R.drawable.card_05, R.drawable.card_06, R.drawable.card_07, R.drawable.card_08, R.drawable.card_09, R.drawable.card_10, R.drawable.card_11, R.drawable.card_12, R.drawable.card_13, R.drawable.card_14, R.drawable.card_15, R.drawable.card_16, R.drawable.card_17, R.drawable.card_18, R.drawable.card_19, R.drawable.card_20, R.drawable.card_21, R.drawable.card_22, R.drawable.card_23, R.drawable.card_24, R.drawable.card_25, R.drawable.card_26, R.drawable.card_27, R.drawable.card_28, R.drawable.card_29, R.drawable.card_30, R.drawable.card_31, R.drawable.card_32, R.drawable.card_33, R.drawable.card_34, R.drawable.card_35, R.drawable.card_36, R.drawable.card_37, R.drawable.card_38, R.drawable.card_39, R.drawable.card_40, R.drawable.card_41, R.drawable.card_42, R.drawable.card_43, R.drawable.card_44, R.drawable.card_45, R.drawable.card_46, R.drawable.card_47, R.drawable.card_48, R.drawable.card_49, R.drawable.card_50, R.drawable.card_51 }; static enum roles { NONE, SMALLBLIND, BIGBLIND, DEALER }; roles role = roles.NONE; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chat); currentMoneyView = (TextView)findViewById(R.id.currentMoney); updateMoney(); currentRoleView = (TextView)findViewById(R.id.currentRole); updateRole(); card1Image = (ImageView)findViewById(R.id.leftCardImage); card2Image = (ImageView)findViewById(R.id.rightCardImage); lview = (ListView)findViewById(R.id.chat_history); cadapter = new ChatAdapter(getApplicationContext()); lview.setAdapter(cadapter); raiseButton = (Button)findViewById(R.id.raiseButton); raiseButton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { raiseDialog(); } }); foldButton = (Button)findViewById(R.id.foldButton); foldButton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { writeLine("fold"); } }); checkButton = (Button)findViewById(R.id.checkButton); checkButton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { writeLine("check"); } }); callButton = (Button)findViewById(R.id.callButton); callButton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { writeLine("call"); } }); allinButton = (Button)findViewById(R.id.allinButton); allinButton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { writeLine("allin"); } }); betButton = (Button)findViewById(R.id.betButton); betButton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { writeLine("bet"); } }); } private void processRaise() { if (amount <= 0) { Toast.makeText(getApplicationContext(), "Invalid amount", Toast.LENGTH_LONG).show(); // TODO toast: amount is not a natural number return; } if (amount > money) { // TODO toast: not enough money return; } if (amount <= curbet) { // TODO toast: raise is too low return; } writeLine("raise "+amount); } private void processBet() { if (amount <= 0) { Toast.makeText(getApplicationContext(), "Invalid amount", Toast.LENGTH_LONG).show(); // TODO toast: amount is not a natural number return; } if (amount > money) { // TODO toast: not enough money return; } writeLine("bet "+amount); } @Override public void onBackPressed() { //To disconnect the connection rather than closing the app. chatService.remoteDisconnect(); super.onBackPressed(); } private void raiseDialog() { final AlertDialog.Builder alert = new AlertDialog.Builder(this); final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_NUMBER); alert.setView(input); alert.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { amount = Integer.parseInt(input.getText().toString()); dialog.dismiss(); processRaise(); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { amount = 0; dialog.cancel(); } }); alert.show(); } private void betDialog() { final AlertDialog.Builder alert = new AlertDialog.Builder(this); final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_NUMBER); alert.setView(input); alert.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { amount = Integer.parseInt(input.getText().toString()); dialog.dismiss(); processBet(); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { amount = 0; dialog.cancel(); } }); alert.show(); } private void updateRole() { switch (role) { case NONE: currentRoleView.setText(R.string.role_none); break; case DEALER: currentRoleView.setText(R.string.role_dealer); break; case SMALLBLIND: currentRoleView.setText(R.string.role_smallblind); break; case BIGBLIND: currentRoleView.setText(R.string.role_bigblind); break; } } private void updateMoney() { currentMoneyView.setText("$ " + money); int color = (money > 0) ? Color.GREEN : Color.RED; currentMoneyView.setTextColor(color); } private void parseLine(String line) { String[] lines = line.split(";"); for (String l : lines) { l = l.replace(";", ""); Log.d("Client", l); if (l.startsWith("cmds ")) { String msg = l.substring(5); int cmds = Integer.parseInt(msg); raiseButton.setEnabled((cmds & Constants.RAISE) != 0); foldButton .setEnabled((cmds & Constants.FOLD ) != 0); checkButton.setEnabled((cmds & Constants.CHECK) != 0); callButton .setEnabled((cmds & Constants.CALL ) != 0); allinButton.setEnabled((cmds & Constants.ALLIN) != 0); betButton .setEnabled((cmds & Constants.BET ) != 0); } else if (l.startsWith("cards ")) { String msg = l.substring(6); String[] cards = msg.split(" "); card1 = Integer.parseInt(cards[0]); card2 = Integer.parseInt(cards[1]); if (card1 < 0) card1Image.setImageResource(R.drawable.card_back); else card1Image.setImageResource(cardDrawables[card1]); if (card2 < 0) card2Image.setImageResource(R.drawable.card_back); else card2Image.setImageResource(cardDrawables[card2]); } else if (l.startsWith("curbet ")) { String msg = l.substring(7); curbet = Integer.parseInt(msg); } else if (l.startsWith("minbet ")) { String msg = l.substring(7); minbet = Integer.parseInt(msg); } else if (l.startsWith("money ")) { String msg = l.substring(6); money = Integer.parseInt(msg); updateMoney(); } else if (l.startsWith("role ")) { String msg = l.substring(5); if (msg.equals("none")) role = roles.NONE; else if (msg.equals("smallBlind")) role = roles.SMALLBLIND; else if (msg.equals("bigBlind")) role = roles.BIGBLIND; else if (msg.equals("dealer")) role = roles.DEALER; else return; updateRole(); } } } @Override public void lineReceived(int line) { myHandler.post(new Runnable() { public void run() { List<String> lines = chatService.getLines(); String l = lines.get(lines.size()-1); cadapter.setNewChatList(lines); cadapter.notifyDataSetChanged(); parseLine(l); } }); } @Override public void remoteDisconnect() { myHandler.post(new Runnable() { public void run() { Toast.makeText(ChatActivity.this, "Remote session disconnected.", Toast.LENGTH_SHORT).show(); finish(); } }); } public void writeLine(String str) { chatService.writeString(str); } @Override public void onStcLibPrepared() { myHandler.post(new Runnable() { public void run() { ListView lview = (ListView)findViewById(R.id.chat_history); lview.setAdapter(cadapter); cadapter.setNewChatList(chatService.getLines()); } }); } @Override public void sessionListChanged() { } @Override public void connected(boolean didConnect) { } @Override public void localSessionChanged() { } @Override public void inviteAlert(UUID inviterUuid, int inviteHandle, byte[] oobData) { } }
package ac.at.tuwien.infosys.visp.runtime.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Properties; @Configuration public class Datasourceconfig { private static final Logger LOG = LoggerFactory.getLogger(Datasourceconfig.class); @Bean public DataSource dataSource() { String IP = null; try { if (Files.exists(Paths.get("database.properties"))) { IP = new String(Files.readAllBytes(Paths.get("database.properties")), StandardCharsets.UTF_8); IP = IP.replaceAll("databaseIP=", "").trim(); IP = IP.replaceAll("database=", "").trim(); IP = IP.replaceAll("[\\r\\n]", "").trim(); LOG.info("Using database at IP " + IP); } } catch (IOException e) { LOG.error(e.getLocalizedMessage()); } if (IP == null) { IP = "127.0.0.1"; } String uri = "jdbc:mysql://" + IP + ":3306/visp?verifyServerCertificate=false&useSSL=false&requireSSL=false"; Properties prop = new Properties(); try { prop.load(getClass().getClassLoader().getResourceAsStream("credential.properties")); } catch (IOException e) { LOG.error("Could not load credential properties.", e); } DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create(); dataSourceBuilder.url(uri); dataSourceBuilder.username(prop.getProperty("spring.datasource.username")); dataSourceBuilder.password(prop.getProperty("spring.datasource.password")); return dataSourceBuilder.build(); } }
package com.conveyal.datatools.manager.models; import com.conveyal.datatools.manager.persistence.DataStore; import com.fasterxml.jackson.annotation.JsonView; import java.util.Collection; public class ExternalFeedSourceProperty extends Model { private static final long serialVersionUID = 1L; private static DataStore<ExternalFeedSourceProperty> propertyStore = new DataStore<>("externalFeedSourceProperties"); private FeedSource feedSource; // constructor for data dump load public ExternalFeedSourceProperty() {} public ExternalFeedSourceProperty(FeedSource feedSource, String resourceType, String name, String value) { this.id = feedSource.id + "_" + resourceType + "_" + name; this.feedSource = feedSource; this.resourceType = resourceType; this.name = name; this.value = value; } @JsonView(JsonViews.UserInterface.class) public String getFeedSourceId() { return feedSource.id; } public String resourceType; public String name; public String value; public void save () { save(true); } public void save (boolean commit) { if (commit) propertyStore.save(id, this); else propertyStore.saveWithoutCommit(id, this); } /** * Commit changes to the datastore */ public static void commit () { propertyStore.commit(); } public static ExternalFeedSourceProperty find(FeedSource source, String resourceType, String name) { return propertyStore.getById(source.id + "_" +resourceType + "_" + name); } public static ExternalFeedSourceProperty updateOrCreate(FeedSource source, String resourceType, String name, String value) { ExternalFeedSourceProperty prop = ExternalFeedSourceProperty.find(source, resourceType, name); if(prop == null) { prop = new ExternalFeedSourceProperty(source, resourceType, name, value); } else prop.value = value; prop.save(); return prop; } public static Collection<ExternalFeedSourceProperty> getAll () { return propertyStore.getAll(); } public void delete() { propertyStore.delete(this.id); } }
package com.fasterxml.jackson.databind.introspect; import java.util.Collection; import java.util.Map; import com.fasterxml.jackson.databind.AnnotationIntrospector; import com.fasterxml.jackson.databind.DeserializationConfig; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.SerializationConfig; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.fasterxml.jackson.databind.cfg.MapperConfig; import com.fasterxml.jackson.databind.type.SimpleType; import com.fasterxml.jackson.databind.util.ClassUtil; public class BasicClassIntrospector extends ClassIntrospector implements java.io.Serializable { private static final long serialVersionUID = 2L; private final static Class<?> CLS_OBJECT = Object.class; private final static Class<?> CLS_STRING = String.class; private final static Class<?> CLS_JSON_NODE = JsonNode.class; /* We keep a small set of pre-constructed descriptions to use for * common non-structured values, such as Numbers and Strings. * This is strictly performance optimization to reduce what is * usually one-time cost, but seems useful for some cases considering * simplicity. * * @since 2.4 */ protected final static BasicBeanDescription STRING_DESC; static { STRING_DESC = BasicBeanDescription.forOtherUse(null, SimpleType.constructUnsafe(String.class), AnnotatedClassResolver.createPrimordial(CLS_STRING)); } protected final static BasicBeanDescription BOOLEAN_DESC; static { BOOLEAN_DESC = BasicBeanDescription.forOtherUse(null, SimpleType.constructUnsafe(Boolean.TYPE), AnnotatedClassResolver.createPrimordial(Boolean.TYPE)); } protected final static BasicBeanDescription INT_DESC; static { INT_DESC = BasicBeanDescription.forOtherUse(null, SimpleType.constructUnsafe(Integer.TYPE), AnnotatedClassResolver.createPrimordial(Integer.TYPE)); } protected final static BasicBeanDescription LONG_DESC; static { LONG_DESC = BasicBeanDescription.forOtherUse(null, SimpleType.constructUnsafe(Long.TYPE), AnnotatedClassResolver.createPrimordial(Long.TYPE)); } protected final static BasicBeanDescription OBJECT_DESC; static { OBJECT_DESC = BasicBeanDescription.forOtherUse(null, SimpleType.constructUnsafe(Object.class), AnnotatedClassResolver.createPrimordial(CLS_OBJECT)); } public BasicClassIntrospector() { } @Override public ClassIntrospector copy() { return new BasicClassIntrospector(); } @Override public BasicBeanDescription forSerialization(SerializationConfig config, JavaType type, MixInResolver r) { // minor optimization: for some JDK types do minimal introspection BasicBeanDescription desc = _findStdTypeDesc(config, type); if (desc == null) { // As per [databind#550], skip full introspection for some of standard // structured types as well desc = _findStdJdkCollectionDesc(config, type); if (desc == null) { desc = BasicBeanDescription.forSerialization(collectProperties(config, type, r, true, "set")); } } return desc; } @Override public BasicBeanDescription forDeserialization(DeserializationConfig config, JavaType type, MixInResolver r) { // minor optimization: for some JDK types do minimal introspection BasicBeanDescription desc = _findStdTypeDesc(config, type); if (desc == null) { // As per [Databind#550], skip full introspection for some of standard // structured types as well desc = _findStdJdkCollectionDesc(config, type); if (desc == null) { desc = BasicBeanDescription.forDeserialization(collectProperties(config, type, r, false, "set")); } } return desc; } @Override public BasicBeanDescription forDeserializationWithBuilder(DeserializationConfig config, JavaType type, MixInResolver r) { // no std JDK types with Builders, so: return BasicBeanDescription.forDeserialization(collectPropertiesWithBuilder(config, type, r, false)); } @Override public BasicBeanDescription forCreation(DeserializationConfig config, JavaType type, MixInResolver r) { BasicBeanDescription desc = _findStdTypeDesc(config, type); if (desc == null) { // As per [databind#550], skip full introspection for some of standard // structured types as well desc = _findStdJdkCollectionDesc(config, type); if (desc == null) { desc = BasicBeanDescription.forDeserialization( collectProperties(config, type, r, false, "set")); } } return desc; } @Override public BasicBeanDescription forClassAnnotations(MapperConfig<?> config, JavaType type, MixInResolver r) { BasicBeanDescription desc = _findStdTypeDesc(config, type); if (desc == null) { desc = BasicBeanDescription.forOtherUse(config, type, _resolveAnnotatedClass(config, type, r)); } return desc; } @Override public BasicBeanDescription forDirectClassAnnotations(MapperConfig<?> config, JavaType type, MixInResolver r) { BasicBeanDescription desc = _findStdTypeDesc(config, type); if (desc == null) { desc = BasicBeanDescription.forOtherUse(config, type, _resolveAnnotatedWithoutSuperTypes(config, type, r)); } return desc; } protected POJOPropertiesCollector collectProperties(MapperConfig<?> config, JavaType type, MixInResolver r, boolean forSerialization, String mutatorPrefix) { return constructPropertyCollector(config, _resolveAnnotatedClass(config, type, r), type, forSerialization, mutatorPrefix); } protected POJOPropertiesCollector collectPropertiesWithBuilder(MapperConfig<?> config, JavaType type, MixInResolver r, boolean forSerialization) { AnnotatedClass ac = _resolveAnnotatedClass(config, type, r); AnnotationIntrospector ai = config.isAnnotationProcessingEnabled() ? config.getAnnotationIntrospector() : null; JsonPOJOBuilder.Value builderConfig = (ai == null) ? null : ai.findPOJOBuilderConfig(ac); String mutatorPrefix = (builderConfig == null) ? JsonPOJOBuilder.DEFAULT_WITH_PREFIX : builderConfig.withPrefix; return constructPropertyCollector(config, ac, type, forSerialization, mutatorPrefix); } /** * Overridable method called for creating {@link POJOPropertiesCollector} instance * to use; override is needed if a custom sub-class is to be used. */ protected POJOPropertiesCollector constructPropertyCollector(MapperConfig<?> config, AnnotatedClass ac, JavaType type, boolean forSerialization, String mutatorPrefix) { return new POJOPropertiesCollector(config, forSerialization, type, ac, mutatorPrefix); } /** * Method called to see if type is one of core JDK types * that we have cached for efficiency. */ protected BasicBeanDescription _findStdTypeDesc(MapperConfig<?> config, JavaType type) { Class<?> cls = type.getRawClass(); if (cls.isPrimitive()) { if (cls == Integer.TYPE) { return INT_DESC; } if (cls == Long.TYPE) { return LONG_DESC; } if (cls == Boolean.TYPE) { return BOOLEAN_DESC; } } else if (ClassUtil.isJDKClass(cls)) { if (cls == CLS_OBJECT) { return OBJECT_DESC; } if (cls == CLS_STRING) { return STRING_DESC; } if (cls == Integer.class) { return INT_DESC; } if (cls == Long.class) { return LONG_DESC; } if (cls == Boolean.class) { return BOOLEAN_DESC; } } else if (CLS_JSON_NODE.isAssignableFrom(cls)) { return BasicBeanDescription.forOtherUse(config, type, AnnotatedClassResolver.createPrimordial(cls)); } return null; } /** * Helper method used to decide whether we can omit introspection * for members (methods, fields, constructors); we may do so for * a limited number of container types JDK provides. */ protected boolean _isStdJDKCollection(JavaType type) { if (!type.isContainerType() || type.isArrayType()) { return false; } Class<?> raw = type.getRawClass(); if (ClassUtil.isJDKClass(raw)) { // 23-Sep-2014, tatu: Should we be conservative here (minimal number // of matches), or ambitious? Let's do latter for now. if (Collection.class.isAssignableFrom(raw) || Map.class.isAssignableFrom(raw)) { return true; } } return false; } protected BasicBeanDescription _findStdJdkCollectionDesc(MapperConfig<?> cfg, JavaType type) { if (_isStdJDKCollection(type)) { return BasicBeanDescription.forOtherUse(cfg, type, _resolveAnnotatedClass(cfg, type, cfg)); } return null; } /** * @since 2.9 */ protected AnnotatedClass _resolveAnnotatedClass(MapperConfig<?> config, JavaType type, MixInResolver r) { return AnnotatedClassResolver.resolve(config, type, r); } /** * @since 2.9 */ protected AnnotatedClass _resolveAnnotatedWithoutSuperTypes(MapperConfig<?> config, JavaType type, MixInResolver r) { return AnnotatedClassResolver.resolveWithoutSuperTypes(config, type, r); } }
package Characters; import AttackAndDefendBehavior.*; import java.util.*; import Item.*; import Inventory.*; public abstract class A_Character { private String name; private int health; private int maxHealth; private int strength; private int dexterity; private int level; private int experience; private Armor armor; private Weapon weapon; private boolean isDefeated; private int initiative; private ArmorType armorType; private WeaponType weaponType; protected Conditions conditions; protected Random rand; public A_Character(String name, int health, int strength, int dexterity, ArmorType armorType, Armor newArmor, WeaponType weaponType, Weapon newWeapon) { this.name = name; this.health = health; this.strength = strength; this.dexterity = dexterity; this.armor = newArmor; this.weapon = newWeapon; this.maxHealth = health; this.armorType = armorType; this.weaponType = weaponType; this.level = 1; this.experience = 0; isDefeated = false; rand = new Random(); conditions = new Conditions(getName()); } public abstract boolean takeAction(Party heroes, Party monsters); public void takeDamage(int total) { this.health -= total; if(health <= 0) { health = 0; this.isDefeated = true; } } public boolean canAttack(A_Character toAttack) { int attackBonus = 0; switch(weapon.getAttackType()) { case "dexterity": attackBonus = this.getDexterity(); break; case "strength": attackBonus = this.getStrength(); break; } attackBonus += weapon.getPower(); attackBonus += rand.nextInt(ConstantValues.ChanceToHit.getValue()); attackBonus = conditions.addAttack(attackBonus); attackBonus = conditions.calculateAttack(attackBonus); return attackBonus >= toAttack.totalDefense(); } public void attack(A_Character toAttack) { if(canAttack(toAttack)) { preformAttack(toAttack); } else { System.out.println(this.getName() + " attacked " + toAttack.getName() + " but missed!"); } } public void preformAttack(A_Character toAttack) { int totalDamage = 0; totalDamage += weapon.getPower(); totalDamage += getStrength(); totalDamage += rand.nextInt(ConstantValues.RandomDamage.getValue()); totalDamage = conditions.addDamage(totalDamage); totalDamage = conditions.calculateDamage(totalDamage); totalDamage = toAttack.conditions.reduceDamage(totalDamage); toAttack.takeDamage(totalDamage); System.out.println(this.getName() + " attacked " + toAttack.getName() + " for " + totalDamage + " damage!"); if(toAttack.getDefeated()) { System.out.println(this.getName() + " killed " + toAttack.getName() + "!"); } } public int getLevel() { return this.level; } private void levelUp() { strength += strengthIncrease(); dexterity += dexterityIncrease(); maxHealth += healthIncrease(); health = maxHealth; level++; experience = 0; } protected boolean canLevel() { return experience/(level*100) > 0; } public void gainExperience(int experience) { if(experience > 0) { this.experience += experience; } if(canLevel()) { levelUp(); } } public int strengthIncrease() { return 0; } public int dexterityIncrease() { return 0; } public int healthIncrease() { return 0; } public boolean canEquip(Armor armor) { return armorType == armor.getArmorType(); } public boolean canEquip(Weapon weapon) { return weaponType == weapon.getWeaponType(); } public Armor equip(Armor armor) { Armor temp = this.armor; this.armor = armor; return temp; } public Weapon equip(Weapon weapon) { Weapon temp = this.weapon; this.weapon = weapon; return temp; } public void heal(int amount) { System.out.println(getName() + " was healed for " + amount + " HP!"); health = Math.min(health + amount, maxHealth); removeDefeated(); } public void imbibe(Consumable consumable) { System.out.println(getName() + " imbibed a " + consumable + "!"); } @Override public String toString() { return "Name: " + getName() + "\tHealth: " + getHealth() + "\tStrength: " + getStrength() + "\tDexterity: " + getDexterity() + "\tArmor: "; } public String inventoryDisplay() { return "Name: " + getName() + " Health: " + getHealth() + " Armor: " + getArmor() + " Weapon: " + getWeapon(); } public String displayStats() { return "Name: " + getName() + " Level: " + getLevel() + " Health: " + getHealth() + " Strength: " + getStrength() + (strength != getStrength() ? ("(" + strength + ")"):"") + " Dexterity: " + getDexterity() + (dexterity != getDexterity() ? ("(" + dexterity + ")"):"") + " " + getArmor() + " " + getWeapon(); } public String battleDisplay() { String retString = "Name: " + getName() + " Health: " + getHealth(); if(conditions.hasBadCondition()) { retString += " bad condition"; } return retString; } private void setDefeated(boolean isDown) { isDefeated = isDown; } public void resetTurn() { conditions.startTurn(); } public void endTurn() { conditions.endTurn(); } public void removeDefeated() { isDefeated = false; } public void resetStats() { conditions.recoverConditions(); } public Conditions getConditions() { return conditions; } public boolean getDefeated() { return isDefeated; } public Weapon getWeapon() { return weapon; } public Armor getArmor() { return armor; } public String getName() { return name; } public int getHealth() { return health; } public int getStrength() { return strength; } public int getDexterity() { return dexterity; } public int getMaxHealth() { return maxHealth; } private int totalDefense() { int defense = armor.getPower(); defense += getDexterity(); return defense; } protected int getInitiative() { return this.initiative; } public void generateInitiative() { int randomValue; randomValue = rand.nextInt(ConstantValues.RandomInitiative.getValue()); initiative = randomValue + dexterity; } }
package com.github.lunatrius.imc.deserializer; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import cpw.mods.fml.common.registry.GameData; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagByte; import net.minecraft.nbt.NBTTagByteArray; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagDouble; import net.minecraft.nbt.NBTTagFloat; import net.minecraft.nbt.NBTTagInt; import net.minecraft.nbt.NBTTagIntArray; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagLong; import net.minecraft.nbt.NBTTagShort; import net.minecraft.nbt.NBTTagString; import java.lang.reflect.Type; public class NBTTagCompoundDeserializer implements JsonDeserializer<NBTTagCompound> { public static final String MEMBER_NAME = "name"; public static final String MEMBER_VALUE = "value"; public static final String DELIMITER = ":"; public static final String ID_TYPE_BLOCK = "block"; public static final String ID_TYPE_ITEM = "item"; public static final String TYPE_BOOLEAN = "boolean"; public static final String TYPE_BYTE = "byte"; public static final String TYPE_SHORT = "short"; public static final String TYPE_INT = "int"; public static final String TYPE_LONG = "long"; public static final String TYPE_FLOAT = "float"; public static final String TYPE_DOUBLE = "double"; public static final String TYPE_BYTE_ARRAY = "byte[]"; public static final String TYPE_STRING = "string"; public static final String TYPE_LIST = "list"; public static final String TYPE_COMPOUND = "compound"; public static final String TYPE_INT_ARRAY = "int[]"; @Override public NBTTagCompound deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!json.isJsonObject()) { return null; } JsonObject jsonObject = json.getAsJsonObject(); JsonElement value = jsonObject.get(MEMBER_VALUE); return getCompound(value.getAsJsonArray()); } private NBTBase getNBTTag(JsonObject jsonObject, String type, String name) { JsonElement value = jsonObject.get(MEMBER_VALUE); if (type.equalsIgnoreCase(TYPE_BOOLEAN)) { return new NBTTagByte((byte) (value.getAsBoolean() ? 1 : 0)); } else if (type.equalsIgnoreCase(TYPE_BYTE)) { return new NBTTagByte(value.getAsByte()); } else if (type.equalsIgnoreCase(TYPE_SHORT)) { NBTBase.NBTPrimitive primitive = getIdFromString(value, type); if (primitive != null) { return primitive; } return new NBTTagShort(value.getAsShort()); } else if (type.equalsIgnoreCase(TYPE_INT)) { NBTBase.NBTPrimitive primitive = getIdFromString(value, type); if (primitive != null) { return primitive; } return new NBTTagInt(value.getAsInt()); } else if (type.equalsIgnoreCase(TYPE_LONG)) { return new NBTTagLong(value.getAsLong()); } else if (type.equalsIgnoreCase(TYPE_FLOAT)) { return new NBTTagFloat(value.getAsFloat()); } else if (type.equalsIgnoreCase(TYPE_DOUBLE)) { return new NBTTagDouble(value.getAsDouble()); } else if (type.equalsIgnoreCase(TYPE_BYTE_ARRAY)) { return getByteArray(value.getAsJsonArray()); } else if (type.equalsIgnoreCase(TYPE_STRING)) { return new NBTTagString(value.getAsString()); } else if (type.equalsIgnoreCase(TYPE_LIST)) { return getList(value.getAsJsonArray()); } else if (type.equalsIgnoreCase(TYPE_COMPOUND)) { return getCompound(value.getAsJsonArray()); } else if (type.equalsIgnoreCase(TYPE_INT_ARRAY)) { return getIntArray(value.getAsJsonArray()); } return null; } private NBTBase.NBTPrimitive getIdFromString(JsonElement jsonElement, String type) { if (jsonElement.isJsonPrimitive()) { JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive(); if (jsonPrimitive.isString()) { String[] split = jsonPrimitive.getAsString().split(DELIMITER, 2); int id = -1; if (split.length == 2) { if (split[0].equalsIgnoreCase(ID_TYPE_BLOCK)) { id = GameData.getBlockRegistry().getId(split[1]); } else if (split[0].equalsIgnoreCase(ID_TYPE_ITEM)) { id = GameData.getItemRegistry().getId(split[1]); } } else { id = GameData.getBlockRegistry().getId(split[1]); if (id == -1) { id = GameData.getItemRegistry().getId(split[1]); } } if (id >= 0) { if (type.equalsIgnoreCase(TYPE_SHORT)) { return new NBTTagShort((short) id); } else if (type.equalsIgnoreCase(TYPE_INT)) { return new NBTTagInt(id); } } } } return null; } private NBTTagCompound getCompound(JsonArray jsonArray) { NBTTagCompound compound = new NBTTagCompound(); for (JsonElement jsonElement : jsonArray) { JsonObject jsonObject = jsonElement.getAsJsonObject(); String[] split = getSplit(jsonObject); if (split.length != 2) { continue; } NBTBase tag = getNBTTag(jsonObject, split[0], split[1]); if (tag != null) { compound.setTag(split[1], tag); } } return compound; } private NBTTagList getList(JsonArray jsonArray) { NBTTagList tagList = new NBTTagList(); for (JsonElement jsonElement : jsonArray) { JsonObject jsonObject = jsonElement.getAsJsonObject(); String[] split = getSplit(jsonObject); if (split.length != 2) { continue; } NBTBase tag = getNBTTag(jsonObject, split[0], split[1]); if (tag != null) { tagList.appendTag(tag); } } return tagList; } private String[] getSplit(JsonObject jsonObject) { return jsonObject.get(MEMBER_NAME).getAsString().split(DELIMITER, 2); } private NBTTagByteArray getByteArray(JsonArray jsonArray) { byte[] byteArray = new byte[jsonArray.size()]; for (int i = 0; i < jsonArray.size(); i++) { byteArray[i] = jsonArray.get(i).getAsByte(); } return new NBTTagByteArray(byteArray); } private NBTTagIntArray getIntArray(JsonArray jsonArray) { int[] intArray = new int[jsonArray.size()]; for (int i = 0; i < jsonArray.size(); i++) { intArray[i] = jsonArray.get(i).getAsInt(); } return new NBTTagIntArray(intArray); } }
package cn.edu.ruc.dao; import java.util.List; /** * * * @author Sunxg * */ public interface BaseDao { /** * 1, * @return true, * false */ boolean insertOnlyPoint(); /** * 2, * @return true, * false */ boolean insertMultiPoints(); List<Object> selectPointsByTime(); Object selectMaxByTimeAndDevice(); boolean updatePointByTime(); boolean deletePointsByTime(); }
package com.auth0; import com.auth0.client.auth.AuthAPI; import com.auth0.client.auth.AuthorizeUrlBuilder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Class to create and customize an Auth0 Authorize URL. * It's not reusable. */ @SuppressWarnings({"UnusedReturnValue", "WeakerAccess", "unused", "SameParameterValue"}) public class AuthorizeUrl { private static final String SCOPE_OPENID = "openid"; private HttpServletResponse response; private HttpServletRequest request; private final AuthorizeUrlBuilder builder; private final String responseType; private boolean legacySameSiteCookie = true; private String nonce; private String state; private boolean used; /** * Creates a new instance that can be used to build an Auth0 Authorization URL. * * Using this constructor with a non-null {@link HttpServletResponse} will store the state and nonce as * cookies when the {@link AuthorizeUrl#build()} method is called, with the appropriate SameSite attribute depending * on the responseType. State and nonce will also be stored in the {@link javax.servlet.http.HttpSession} as a fallback, * but this behavior will be removed in a future release, and only cookies will be used. * * @param client the Auth0 Authentication API client * @parem request the HTTP request. Used to store state and nonce as a fallback if cookies not set. * @param response the response where the state and nonce will be stored as cookies * @param redirectUrl the url to redirect to after authentication * @param responseType the response type to use */ AuthorizeUrl(AuthAPI client, HttpServletRequest request, HttpServletResponse response, String redirectUrl, String responseType) { this.request = request; this.response = response; this.responseType = responseType; this.builder = client.authorizeUrl(redirectUrl) .withResponseType(responseType) .withScope(SCOPE_OPENID); } /** * Creates a new instance that can be used to build an Auth0 Authorization URL. * * Using this constructor will store the state and nonce in the {@link javax.servlet.http.HttpSession}, and will be * deprecated and removed in the future, in favor of storing the state and nonce in Cookies. * * @param client the Auth0 Authentication API client * @param request the request where the state and nonce will be stored in the {@link javax.servlet.http.HttpSession} * @param redirectUrl the url to redirect to after authentication * @param responseType the response type to use */ // TODO - deprecate in minor version, remove in next major AuthorizeUrl(AuthAPI client, HttpServletRequest request, String redirectUrl, String responseType) { this(client, request, null, redirectUrl, responseType); this.legacySameSiteCookie = false; } /** * Sets the connection value. * * @param connection connection to set * @return the builder instance */ public AuthorizeUrl withConnection(String connection) { builder.withConnection(connection); return this; } /** * Sets whether a fallback cookie should be used for clients that do not support "SameSite=None". * Only applicable when this instance is created with {@link AuthorizeUrl#AuthorizeUrl(AuthAPI, HttpServletRequest, HttpServletResponse, String, String)}. * * @param legacySameSiteCookie whether or not to set fallback auth cookies for clients that do not support "SameSite=None" * @return the builder instance */ AuthorizeUrl withLegacySameSiteCookie(boolean legacySameSiteCookie) { this.legacySameSiteCookie = legacySameSiteCookie; return this; } /** * Sets the audience value. * * @param audience audience to set * @return the builder instance */ public AuthorizeUrl withAudience(String audience) { builder.withAudience(audience); return this; } /** * Sets the state value. * * @param state state to set * @return the builder instance */ public AuthorizeUrl withState(String state) { this.state = state; builder.withState(state); return this; } /** * Sets the nonce value. * * @param nonce nonce to set * @return the builder instance */ public AuthorizeUrl withNonce(String nonce) { this.nonce = nonce; builder.withParameter("nonce", nonce); return this; } /** * Sets the scope value. * * @param scope scope to set * @return the builder instance */ public AuthorizeUrl withScope(String scope) { builder.withScope(scope); return this; } /** * Sets an additional parameter. * * @param name name of the parameter * @param value value of the parameter to set * @return the builder instance */ public AuthorizeUrl withParameter(String name, String value) { if ("state".equals(name) || "nonce".equals(name)) { throw new IllegalArgumentException("Please, use the dedicated methods for setting the 'nonce' and 'state' parameters."); } if ("response_type".equals(name)) { throw new IllegalArgumentException("Response type cannot be changed once set."); } if ("redirect_uri".equals(name)) { throw new IllegalArgumentException("Redirect URI cannot be changed once set."); } builder.withParameter(name, value); return this; } public String build() throws IllegalStateException { if (used) { throw new IllegalStateException("The AuthorizeUrl instance must not be reused."); } if (response != null) { TransientCookieStore.SameSite sameSiteValue = containsFormPost() ? TransientCookieStore.SameSite.NONE : TransientCookieStore.SameSite.LAX; // Also store in Session just in case developer uses deprecated // AuthenticationController.handle(HttpServletRequest) API if (state != null) { TransientCookieStore.storeState(response, state, sameSiteValue, legacySameSiteCookie); RandomStorage.setSessionState(request, state); } if (nonce != null) { TransientCookieStore.storeNonce(response, nonce, sameSiteValue, legacySameSiteCookie); RandomStorage.setSessionNonce(request, nonce); } } else { if (state != null) { RandomStorage.setSessionState(request, state); } if (nonce != null) { RandomStorage.setSessionNonce(request, nonce); } } used = true; return builder.build(); } private boolean containsFormPost() { String[] splitResponseTypes = responseType.trim().split("\\s+"); List<String> responseTypes = Collections.unmodifiableList(Arrays.asList(splitResponseTypes)); return RequestProcessor.requiresFormPostResponseMode((responseTypes)); } }
package com.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import retrofit.Call; import retrofit.Response; import java.io.IOException; @org.springframework.stereotype.Controller public class Controller { private final RandomNumberService randomNumberService; @Autowired public Controller(RandomNumberService randomNumberService) { this.randomNumberService = randomNumberService; } @RequestMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity randomNumber() throws IOException { Call<RandomNumberResponse> call = randomNumberService.getRandomNumbers(5); Response<RandomNumberResponse> response = call.execute(); if (response.isSuccess()) { return ResponseEntity.ok(response.body()); } else { return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(response.raw().toString()); } } @RequestMapping(value = "/bar", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity bar() throws IOException { Call<InvalidRandomNumberResponse> call = randomNumberService.getInvalidRandomNumbers(5); Response<InvalidRandomNumberResponse> response = call.execute(); if (response.isSuccess()) { return ResponseEntity.ok(response.body()); } else { return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(response.raw().toString()); } } @RequestMapping(value = "/foo", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity foo() throws IOException { Response<RandomNumberResponse> response = randomNumberService.getFoo().execute(); if (response.isSuccess()) { return ResponseEntity.ok().build(); } else { return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(response.raw().toString()); } } }
package com.jcabi.http; import com.jcabi.aspects.Immutable; import java.io.IOException; import java.io.InputStream; import javax.validation.constraints.NotNull; @Immutable public interface Request { /** * GET method name. */ String GET = "GET"; /** * POST method name. */ String POST = "POST"; /** * PUT method name. */ String PUT = "PUT"; /** * HEAD method name. */ String HEAD = "HEAD"; /** * DELETE method name. */ String DELETE = "DELETE"; /** * OPTIONS method name. */ String OPTIONS = "OPTIONS"; /** * PATCH method name. */ String PATCH = "PATCH"; /** * Get destination URI. * @return The destination it is currently pointing to */ @NotNull(message = "URI is never NULL") RequestURI uri(); /** * Get request body. * @return New alternated request */ @NotNull(message = "request is never NULL") RequestBody body(); /** * Set request header. * @param name ImmutableHeader name * @param value Value of the header to set * @return New alternated request */ @NotNull(message = "request is never NULL") Request header( @NotNull(message = "header name can't be NULL") String name, @NotNull(message = "header value can't be NULL") Object value); /** * Remove all headers with this name. * @param name ImmutableHeader name * @return New alternated request * @since 0.10 */ @NotNull(message = "alternated request is never NULL") Request reset(@NotNull(message = "header name can't be NULL") String name); /** * Use this method. * @param method The method to use * @return New alternated request */ @NotNull(message = "request is never NULL") Request method(@NotNull(message = "method can't be NULL") String method); /** * Execute it with a specified HTTP method. * @return Response * @throws IOException If fails to fetch HTTP request */ Response fetch() throws IOException; Response fetch(InputStream stream) throws IOException; /** * Send it through a decorating {@link Wire}. * @param type Type of wire to use * @param args Optional arguments for the wire constructor * @param <T> Type to use * @return New request with a wire decorated * @since 0.10 */ <T extends Wire> Request through(Class<T> type, Object... args); }
package com.libqa.domain; import com.libqa.application.enums.SpaceLayoutType; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.*; import java.util.Date; @Data @Entity @Table(name = "space") @EqualsAndHashCode public class Space { @Id @Column(name = "spaceId", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO) private Integer spaceId; @Column(name = "description", nullable = false, columnDefinition="Text") private String description; @Column(name = "descriptionMarkup", nullable = false, columnDefinition="Text") private String descriptionMarkup; @Column(name = "title", length = 80, nullable = false) private String title; @Column(name = "titleImage", length = 40) private String titleImage; @Column(name = "titleImagePath", length = 50) private String titleImagePath; @Column(name = "isPrivate", columnDefinition="TINYINT(1) DEFAULT 0") private boolean isPrivate; @Column(name = "isDeleted", columnDefinition="TINYINT(1) DEFAULT 0") private boolean isDeleted; @Enumerated(EnumType.STRING) @Column(name = "layoutType", length = 20) private SpaceLayoutType layoutType; @Temporal(TemporalType.TIMESTAMP) private Date insertDate; @Temporal(TemporalType.TIMESTAMP) private Date updateDate; @Column(name = "insertUserId", nullable = false) private Integer insertUserId; @Column(name = "updateUserId") private Integer updateUserId; }
package com.matthewcasperson.validation.filter; import java.io.IOException; import java.util.Enumeration; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.exception.ExceptionUtils; import com.matthewcasperson.validation.exception.ValidationFailedException; import com.matthewcasperson.validation.rule.ParameterValidationRule; import com.matthewcasperson.validation.ruledefinitionimpl.ParameterValidationChain; import com.matthewcasperson.validation.ruledefinitionimpl.ParameterValidationDefinitionImpl; import com.matthewcasperson.validation.ruledefinitionimpl.ParameterValidationDefinitionsImpl; import com.matthewcasperson.validation.utils.SerialisationUtils; import com.matthewcasperson.validation.utilsimpl.JaxBSerialisationUtilsImpl; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkNotNull; /** * This filter intercepts the parameters sent by the client and cleans them up based on some * rules defined in a config file. This means any web application that sits behind this * filter can assume that the param object contains sanatised values. * @author mcasperson * */ public class ParameterValidationFilter implements Filter { private static final Logger LOGGER = Logger.getLogger(ParameterValidationFilter.class.getName()); private static final SerialisationUtils SERIALISATION_UTILS = new JaxBSerialisationUtilsImpl(); /** * This is the init-param name that we expect to hold a reference to the * config xml file. */ private static final String CONFIG_PARAMETER_NAME = "configFile"; /** * The list of validation rules that are to be applied */ private ParameterValidationDefinitionsImpl parameterValidationDefinitions; @Override public void destroy() { /* * Nothing to do here */ } /** * This filter implements multiple chains of validation rules. Each chain is executed against each parameter until * alll validation rules have been executed, or until one of the validation rules stops the execution of the chain. */ @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { //LOGGER.log(Level.INFO, "Parameter Validation Filter processing request"); ServletRequest requestWrapper = request; try { if (parameterValidationDefinitions != null && parameterValidationDefinitions.getParameterValidationDefinitions() != null) { //LOGGER.log(Level.INFO, "Parameter Validation Filter has loaded the config file"); if (requestWrapper instanceof HttpServletRequest) { //LOGGER.log(Level.INFO, "Parameter Validation Filter is filtering a HttpServletRequest"); final HttpServletRequest httpServletRequest = (HttpServletRequest)requestWrapper; /* * Loop over each param. Note that while the validation rules may well * create wrappers that return different values for the params (i.e. requestWrapper is * updated to reference a new wrapper), we use this original copy for the list of * param keys to loop over. */ final Enumeration<String> iter = httpServletRequest.getParameterNames(); while (iter.hasMoreElements()) { /* * Get the param name and move the enumerator along */ final String paramName = iter.nextElement(); //LOGGER.log(Level.INFO, "Parameter Validation Filter processing " + paramName); /* * Loop over each validation rule in the chain */ final List<ParameterValidationChain> validationChains = parameterValidationDefinitions.getParameterValidationDefinitions(); for (final ParameterValidationChain validationChain : validationChains) { checkState(validationChain != null, "A validation rule should never be null"); /* * Test this validation rule against the param name */ final boolean paramMatches = validationChain.getParamNamePattern().matcher(paramName).find(); final boolean uriMatches = validationChain.getRequestURIPattern().matcher(httpServletRequest.getRequestURI()).find(); final boolean paramMatchesAfterNegation = paramMatches ^ validationChain.isParamNamePatternNegated(); final boolean uriMatchesAfterNegation = uriMatches ^ validationChain.isRequestURIPatternNegated(); if (paramMatchesAfterNegation && uriMatchesAfterNegation) { //LOGGER.log(Level.INFO, "Parameter Validation Filter found matching chain"); /* * Loop over each rule in the chain */ for (final ParameterValidationDefinitionImpl validationRule : validationChain.getList()) { LOGGER.log(Level.INFO, "Processing " + paramName + " with " + validationRule.getValidationRuleName()); /* * Get the object that will actually do the validation */ final ParameterValidationRule rule = validationRule.getRule(); /* * It is possible that a bad configuration will result in rule being null */ checkState(rule != null, "A validation rule should never be null. Check the class name defined in the configuration xml file."); try { final ServletRequest processRequest = rule.processParameter(requestWrapper, paramName); checkState(processRequest != null, "A validation rule should never return null when processing a paramemter"); /* * The validation rule is expected to return a valid request regardless of the * processing that should or should not be done. */ requestWrapper = processRequest; } catch (final ValidationFailedException ex) { /* * Log this as a warning as we are probably interested in knowing when our apps * are getting hit with invalid data. */ LOGGER.log(Level.WARNING, ex.toString()); /* * In enforcing mode we rethrow the exception to be caught by an outer * catch block that stops processing and returns a HTTP error code. */ if (parameterValidationDefinitions.getEnforcingMode()) { throw ex; } else { LOGGER.log(Level.WARNING, "Enforcing mode is not enabled in PVF. Continuing to process the request."); } } } } else { /* * This might be intentional, so log it as an INFO */ LOGGER.log(Level.INFO, paramName + " has not been validated."); } } } } } /* * Continue to the next filter */ chain.doFilter(requestWrapper, response); } catch (final ValidationFailedException ex) { /* * Stop processing and return a HTTP error code */ respondWithBadRequest(response); } catch (final Exception ex) { /* * We probably reach this because of some invalid state due to rules returning null * or throwing unchecked exceptions during their own processing. This is logged as * severe as it is most likely a bug in the code. */ LOGGER.log(Level.SEVERE, ex.toString()); LOGGER.log(Level.SEVERE, ExceptionUtils.getFullStackTrace(ex)); /* * Don't allow apps to process raw parameters if this filter has failed */ respondWithBadRequest(response); } } /** * Return with a status code of 400 * @param response The servlet request */ private void respondWithBadRequest(final ServletResponse response) { checkNotNull(response); /* * This is thrown when one of the validation rules determined that a parameter was * sent with invalid data and could not, or should not, be sanitised. */ if (response instanceof HttpServletResponse) { try { final HttpServletResponse httpServletResponse = (HttpServletResponse)response; httpServletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid parameter data"); } catch (final IOException ex) { /* * This shouldn't happen, but log it if it does */ LOGGER.log(Level.SEVERE, ex.toString()); LOGGER.log(Level.SEVERE, ExceptionUtils.getFullStackTrace(ex)); } } } /** * Attempts to parse the XML config file. The config file is a JaxB serialisation of a * ParameterValidationDefinitionsImpl object. */ @Override public void init(final FilterConfig config) throws ServletException { try { final String configFile = config.getInitParameter(CONFIG_PARAMETER_NAME); if (configFile != null) { LOGGER.log(Level.INFO, "Attempting to unmarshall " + configFile); final String configXml = IOUtils.toString(config.getServletContext().getResourceAsStream(configFile)); LOGGER.log(Level.INFO, "configXml is \n" + configXml); parameterValidationDefinitions = SERIALISATION_UTILS.readFromXML(configXml, ParameterValidationDefinitionsImpl.class); } } catch (final Exception ex) { /* * This will happen if the supplied XML is invalid. Log the error */ LOGGER.log(Level.SEVERE, ex.toString()); LOGGER.log(Level.SEVERE, ExceptionUtils.getFullStackTrace(ex)); /* * Rethrow as we don't want to proceed with invalid configuration */ throw new ServletException(ex); } } }
package com.wizzardo.http; import com.wizzardo.http.request.ByteTree; import com.wizzardo.http.utils.StringBuilderThreadLocalHolder; import com.wizzardo.tools.misc.ExceptionDrivenStringBuilder; import com.wizzardo.tools.reflection.StringReflection; import java.util.ArrayList; import java.util.List; public class Path { protected static final StringBuilderThreadLocalHolder stringBuilder = new StringBuilderThreadLocalHolder(); private List<String> parts = new ArrayList<>(10); private String path; private boolean endsWithSlash; public String getPart(int i) { if (parts.size() <= i) return null; return parts.get(i); } public int length() { return parts.size(); } @Override public String toString() { if (path == null) path = build(); return path; } List<String> parts() { return parts; } public Path subPath(int beginIndex) { return subPath(beginIndex, length()); } public Path subPath(int beginIndex, int endIndex) { Path path = new Path(); path.parts = parts.subList(beginIndex, endIndex); if (endsWithSlash || endIndex != parts.size()) path.endsWithSlash = true; return path; } public Path add(String part) { Path path = new Path(); path.parts = new ArrayList<>(parts); if (part.isEmpty()) path.endsWithSlash = true; else { for (String s : part.split("/")) { if (s.isEmpty()) continue; if (!append(s, path)) throw new IllegalStateException("can't parse: " + part); } if (part.endsWith("/")) path.endsWithSlash = true; } return path; } private String build() { ExceptionDrivenStringBuilder sb = stringBuilder.get(); for (String part : parts) sb.append('/').append(part); if (endsWithSlash) sb.append('/'); return sb.toString(); } public boolean isEndsWithSlash() { return endsWithSlash; } public static Path parse(byte[] bytes) { return parse(bytes, 0, bytes.length); } public static Path parse(byte[] bytes, int offset, int limit) { return parse(bytes, offset, limit, null); } public static Path parse(byte[] bytes, int offset, int limit, ByteTree byteTree) { if (bytes[offset] != '/') throw new IllegalStateException("path must starts with '/'"); int length = limit - offset; int h = '/'; int k; int partStart = offset + 1; int partHash = 0; ByteTree.Node node = getByteTreeRoot(byteTree); Path path = new Path(); byte b; char[] data = new char[length]; data[0] = '/'; for (int i = 1; i < length; i++) { b = bytes[offset + i]; data[i] = (char) (k = (b & 0xff)); h = 31 * h + k; if (k == '/') { String value = null; if (node != null) value = node.getValue(); if (value == null) { char[] part = new char[i - partStart]; System.arraycopy(data, partStart, part, 0, i - partStart); value = StringReflection.createString(part, partHash); } if (!append(value, path)) throw new IllegalStateException("can't parse: " + new String(bytes, offset, length)); partStart = i + 1; partHash = 0; node = getByteTreeRoot(byteTree); } else { partHash = 31 * partHash + k; if (node != null) node = node.next(b); } } if (partStart != limit) { String value = null; if (node != null) { value = node.getValue(); } if (value == null) { char[] part = new char[limit - partStart]; System.arraycopy(data, partStart, part, 0, limit - partStart); value = StringReflection.createString(part, partHash); } if (!append(value, path)) throw new IllegalStateException("can't parse: " + new String(bytes, offset, length)); } else path.endsWithSlash = true; path.path = StringReflection.createString(data, h); return path; } private static ByteTree.Node getByteTreeRoot(ByteTree byteTree) { return byteTree != null ? byteTree.getRoot() : null; } private static boolean append(String part, Path path) { if (part.equals("..")) { if (path.parts.isEmpty()) return false; path.parts.remove(path.parts.size() - 1); } else path.parts.add(part); return true; } }
// checkstyle: Checks Java source code for adherence to a set of rules. // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.utils.CheckUtils; /** * Restricts nested if-else blocks to a specified depth (default = 1). * * @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a> */ public final class NestedIfDepthCheck extends Check { /** * A key is pointing to the warning message text in "messages.properties" * file. */ public static final String MSG_KEY = "nested.if.depth"; /** Maximum allowed nesting depth. */ private int max = 1; /** Current nesting depth. */ private int depth; /** * Setter for maximum allowed nesting depth. * @param max maximum allowed nesting depth. */ public void setMax(int max) { this.max = max; } @Override public int[] getDefaultTokens() { return getAcceptableTokens(); } @Override public int[] getAcceptableTokens() { return new int[] {TokenTypes.LITERAL_IF}; } @Override public int[] getRequiredTokens() { return getAcceptableTokens(); } @Override public void beginTree(DetailAST rootAST) { depth = 0; } @Override public void visitToken(DetailAST literalIf) { if (!CheckUtils.isElseIf(literalIf)) { if (depth > max) { log(literalIf, MSG_KEY, depth, max); } ++depth; } } @Override public void leaveToken(DetailAST literalIf) { if (!CheckUtils.isElseIf(literalIf)) { --depth; } } }
package com.thinkaurelius.faunus.mapreduce.statistics; import com.thinkaurelius.faunus.FaunusVertex; import com.thinkaurelius.faunus.Holder; import com.thinkaurelius.faunus.Tokens; import com.thinkaurelius.faunus.mapreduce.CounterMap; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.tinkerpop.blueprints.Direction.IN; import static com.tinkerpop.blueprints.Direction.OUT; public class AdjacentProperties { public static final String PROPERTY = Tokens.makeNamespace(AdjacentProperties.class) + ".property"; public static final String LABELS = Tokens.makeNamespace(AdjacentProperties.class) + ".labels"; public enum Counters { EDGES_COUNTED, VERTICES_COUNTED } public static class Map extends Mapper<NullWritable, FaunusVertex, LongWritable, Holder<FaunusVertex>> { private final LongWritable longWritable = new LongWritable(); private final Holder<FaunusVertex> vertexHolder = new Holder<FaunusVertex>(); private String[] labels; @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { this.labels = context.getConfiguration().getStrings(LABELS, new String[0]); } @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, LongWritable, Holder<FaunusVertex>>.Context context) throws IOException, InterruptedException { long counter = 0; this.longWritable.set(value.getIdAsLong()); final FaunusVertex vertex = value.cloneIdAndProperties(); context.write(this.longWritable, this.vertexHolder.set('f', vertex)); for (final Edge edge : value.getEdges(OUT, this.labels)) { final FaunusVertex vertexB = (FaunusVertex) edge.getVertex(IN); this.longWritable.set(vertexB.getIdAsLong()); context.write(this.longWritable, this.vertexHolder.set('r', vertex)); counter++; } context.getCounter(Counters.EDGES_COUNTED).increment(counter); context.getCounter(Counters.VERTICES_COUNTED).increment(1l); } } public static class Reduce extends Reducer<LongWritable, Holder<FaunusVertex>, Text, Text> { private String property; @Override public void setup(final Reducer.Context context) throws IOException, InterruptedException { this.property = context.getConfiguration().get(PROPERTY); } private final Text fText = new Text(); private final Text rText = new Text(); @Override public void reduce(final LongWritable key, final Iterable<Holder<FaunusVertex>> values, final Reducer<LongWritable, Holder<FaunusVertex>, Text, Text>.Context context) throws IOException, InterruptedException { final List<String> thusFar = new ArrayList<String>(); for (final Holder<FaunusVertex> holder : values) { if (holder.getTag() == 'f') { this.fText.set(toStringProperty(holder.get().getProperty(this.property))); break; } else { thusFar.add(toStringProperty(holder.get().getProperty(this.property))); } } for (final String text : thusFar) { this.rText.set(text); context.write(this.rText, this.fText); } for (final Holder<FaunusVertex> holder : values) { if (holder.getTag() == 'r') { this.rText.set(toStringProperty(holder.get().getProperty(this.property))); context.write(this.rText, this.fText); } } } private String toStringProperty(final Object propertyValue) { return null == propertyValue ? Tokens.NULL : propertyValue.toString(); } } public static class Map2 extends Mapper<Text, Text, Text, LongWritable> { private CounterMap<String> map; @Override public void setup(final Mapper<Text, Text, Text, LongWritable>.Context context) { this.map = new CounterMap<String>(); } @Override public void map(final Text key, final Text value, final Mapper<Text, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException { final String newKey = "(" + key.toString() + "," + value.toString() + ")"; this.map.incr(newKey, 1l); if (this.map.size() > 1000) { this.cleanup(context); this.map.clear(); } } private final LongWritable longWritable = new LongWritable(); private final Text textWritable = new Text(); @Override public void cleanup(final Mapper<Text, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException { super.cleanup(context); for (final java.util.Map.Entry<String, Long> entry : this.map.entrySet()) { this.textWritable.set(entry.getKey()); this.longWritable.set(entry.getValue()); context.write(this.textWritable, this.longWritable); } } } public static class Reduce2 extends Reducer<Text, LongWritable, Text, LongWritable> { private final LongWritable longWritable = new LongWritable(); @Override public void reduce(final Text key, final Iterable<LongWritable> values, final Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException { long counter = 0; for (final LongWritable value : values) { counter = counter + value.get(); } this.longWritable.set(counter); context.write(key, this.longWritable); } } }
package cronapi.map; import java.util.HashMap; import java.util.LinkedHashMap; import cronapi.CronapiMetaData; import cronapi.CronapiMetaData.CategoryType; import cronapi.CronapiMetaData.ObjectType; import cronapi.ParamMetaData; import cronapi.Var; @CronapiMetaData(category = CategoryType.MAP, categoryTags = { "Map", "Mapa" }) public class Operations { @CronapiMetaData(type = "function", name = "{{createObjectWithMapName}}", nameTags = { "createObjectWithMap" }, description = "{{createObjectWithMapDescription}}", wizard = "maps_create_with" , returnType = ObjectType.MAP) public static final Var createObjectMapWith( @ParamMetaData(type = ObjectType.OBJECT, description = "{{createObjectWithMapParam0}}") Var... map) throws Exception { LinkedHashMap<String, Object> mapObject = new LinkedHashMap<>(); for (int i = 0; i < map.length; i++) { mapObject.put(map[i].getId(), map[i].getObject()); } return new Var(mapObject); } @CronapiMetaData(type = "function", name = "{{createObjectMapName}}", nameTags = { "createObjectMap" }, description = "{{createObjectMapDescription}}", returnType = ObjectType.OBJECT) public static final Var createObjectMap() throws Exception { Var value = new Var(new HashMap<>()); return value; } @CronapiMetaData(type = "function", name = "{{getMapFieldName}}", nameTags = { "getMapFieldName" }, description = "{{getMapFieldDescription}}", returnType = ObjectType.OBJECT) public static final Var getJsonOrMapField( @ParamMetaData(type = ObjectType.OBJECT, description = "{{getMapFieldParam0}}") Var mapVar, @ParamMetaData(type = ObjectType.STRING, description = "{{getMapFieldParam1}}") Var keyVar) throws Exception { return cronapi.json.Operations.getJsonOrMapField(mapVar, keyVar); } @CronapiMetaData(type = "function", name = "{{setMapFieldName}}", nameTags = { "setMapField" }, description = "{{setMapFieldDescription}}", returnType = ObjectType.VOID) public static final void setMapField( @ParamMetaData(type = ObjectType.OBJECT, description = "{{setMapFieldParam0}}") Var mapVar, @ParamMetaData(type = ObjectType.STRING, description = "{{setMapFieldParam1}}") Var keyVar, @ParamMetaData(type = ObjectType.OBJECT, description = "{{setMapFieldParam2}}") Var value) throws Exception { cronapi.json.Operations.setJsonOrMapField(mapVar, keyVar, value); } @CronapiMetaData(type = "function", name = "{{toJson}}", nameTags = { "toJson" }, description = "{{functionToJson}}", returnType = ObjectType.JSON) public static final Var toJson( @ParamMetaData(type = ObjectType.OBJECT, description = "{{valueToBeRead}}") Var valueToBeRead) throws Exception { return cronapi.json.Operations.toJson(valueToBeRead); } @CronapiMetaData(type = "function", name = "{{toList}}", nameTags = { "toList", "Para Lista" }, description = "{{functionToList}}", returnType = ObjectType.LIST) public static final Var toList( @ParamMetaData(type = ObjectType.OBJECT, description = "{{valueToBeRead}}") Var valueToBeRead) throws Exception { return cronapi.json.Operations.toList(valueToBeRead); } @CronapiMetaData(type = "function", name = "{{toMap}}", nameTags = { "toMap", "Para Mapa" }, description = "{{functionToMap}}", returnType = ObjectType.MAP) public static final Var toMap( @ParamMetaData(type = ObjectType.OBJECT, description = "{{valueToBeRead}}") Var valueToBeRead) throws Exception { return cronapi.json.Operations.toMap(valueToBeRead); } }
package mitzi; import javax.swing.JFrame; import java.awt.*; import java.awt.event.*; import javax.swing.*; import com.sun.xml.internal.ws.api.model.wsdl.WSDLBoundOperation.ANONYMOUS; public class MitziGUI extends JFrame implements MouseListener, MouseMotionListener { private static final long serialVersionUID = -418000626395118246L; JLayeredPane layeredPane; JPanel chessBoard; JLabel chessPiece; int xAdjustment; int yAdjustment; int start_square; int end_square; private static GameState state = new GameState(); private static boolean mitzis_turn; private static Side mitzis_side =null; Dimension boardSize = new Dimension(800, 800); public MitziGUI() { redraw(); } private void redraw() { // Use a Layered Pane for this this application layeredPane = new JLayeredPane(); layeredPane.setPreferredSize(boardSize); layeredPane.addMouseListener(this); layeredPane.addMouseMotionListener(this); // Add a chess board to the Layered Pane chessBoard = new JPanel(); layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER); chessBoard.setLayout(new GridLayout(8, 8)); chessBoard.setPreferredSize(boardSize); chessBoard.setBounds(0, 0, boardSize.width, boardSize.height); // Color it b/w Color black = Color.getHSBColor((float) 0.10, (float) 0.40, (float) 0.80); Color white = Color.getHSBColor((float) 0.15, (float) 0.13, (float) 0.98); for (int i = 0; i < 64; i++) { JPanel square = new JPanel(new BorderLayout()); chessBoard.add(square); square.setBackground((i + i / 8) % 2 == 0 ? white : black); } getContentPane().removeAll(); getContentPane().add(layeredPane); } private int getSquare(int x, int y) { x = x / 100 + 1; y = (800 - y) / 100 + 1; return x * 10 + y; } private Component squareToComponent(int squ) { int row = 8 - squ % 10; int col = ((int) squ / 10) - 1; Component c = chessBoard.getComponent(row * 8 + col); return c; } public void setToFEN(String fen) { redraw(); JPanel panel; String[] fen_parts = fen.split(" "); // populate the squares String[] fen_rows = fen_parts[0].split("/"); char[] pieces; for (int row = 0; row < 8; row++) { int offset = 0; for (int column = 0; column + offset < 8; column++) { pieces = fen_rows[row].toCharArray(); int square = row * 8 + column + offset; JLabel piece; switch (pieces[column]) { case 'P': piece = new JLabel(""); break; case 'R': piece = new JLabel(""); break; case 'N': piece = new JLabel(""); break; case 'B': piece = new JLabel(""); break; case 'Q': piece = new JLabel(""); break; case 'K': piece = new JLabel(""); break; case 'p': piece = new JLabel(""); break; case 'r': piece = new JLabel(""); break; case 'n': piece = new JLabel(""); break; case 'b': piece = new JLabel(""); break; case 'q': piece = new JLabel(""); break; case 'k': piece = new JLabel(""); break; default: piece = new JLabel(""); offset += Character.getNumericValue(pieces[column]) - 1; break; } panel = (JPanel) chessBoard.getComponent(square); piece.setFont(new Font("Serif", Font.PLAIN, 100)); panel.add(piece); } } chessBoard.updateUI(); } public void mousePressed(MouseEvent e) { chessPiece = null; Component c = chessBoard.findComponentAt(e.getX(), e.getY()); if (c instanceof JPanel) return; Point parentLocation = c.getParent().getLocation(); xAdjustment = parentLocation.x - e.getX(); yAdjustment = parentLocation.y - e.getY(); start_square = getSquare(e.getX(), e.getY()); chessPiece = (JLabel) c; chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment); chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight()); layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER); } // Move the chess piece around public void mouseDragged(MouseEvent me) { if (chessPiece == null) return; chessPiece .setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment); } // Drop the chess piece back onto the chess board public void mouseReleased(MouseEvent e) { if (chessPiece == null) return; chessPiece.setVisible(false); Component c = chessBoard.findComponentAt(e.getX(), e.getY()); end_square = getSquare(e.getX(), e.getY()); // check for promotion IMove move; if (state.getPosition().getPieceFromBoard(start_square) == Piece.PAWN && (SquareHelper.getRow(end_square) == 8 || SquareHelper .getRow(end_square) == 1)) { move = new Move(start_square, end_square, askPromotion()); } else { move = new Move(start_square, end_square); } //if its not your turn, you are not allowed to do anything. if(mitzis_side == state.getPosition().getActiveColor()) { Container parent = (Container) squareToComponent(start_square); parent.add(chessPiece); chessPiece.setVisible(true); return; } //try to do move try { state.doMove(move); } catch (IllegalArgumentException ex) { Container parent = (Container) squareToComponent(start_square); parent.add(chessPiece); chessPiece.setVisible(true); return; } //nobody has moved, set the side for mitzi. if(mitzis_side==null) mitzis_side = state.getPosition().getActiveColor(); Object[] options = { "ok" }; IPosition position = state.getPosition(); setToFEN(position.toFEN()); if (state.getPosition().isMatePosition()) { JOptionPane.showOptionDialog(this, "You Won!","Information", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); return; } if (state.getPosition().isStaleMatePosition()) { JOptionPane.showOptionDialog(this, "Draw","Information", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); return; } mitzis_turn = true; } public void mouseClicked(MouseEvent e) { } public void mouseMoved(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } private Piece askPromotion() { Object[] options = { "Queen", "Rook", "Bishop", "Knight" }; int n = JOptionPane.showOptionDialog(this, "Which piece do you want to promote to?", "Pawn Promotion", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == 0) { return Piece.QUEEN; } else if (n == 1) { return Piece.ROOK; } else if (n == 2) { return Piece.BISHOP; } else { return Piece.KNIGHT; } } public static void main(String[] args) { JFrame frame = new MitziGUI(); frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.setTitle("Mitzi GUI"); MitziGUI gui = (MitziGUI) frame; String initialFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; gui.setToFEN(initialFEN); IBrain mitzi = new MitziBrain(); IMove move; mitzis_turn = false; while (true) { System.out.print(""); if(mitzis_turn) { // Mitzis turn mitzi.set(state); move = mitzi.search(5000, 5000, 6, true, null); state.doMove(move); gui.setToFEN(state.getPosition().toFEN()); Object[] options = { "ok" }; if (state.getPosition().isMatePosition()) { JOptionPane.showOptionDialog(frame, "Mitzi Won!","Information", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); return; } if (state.getPosition().isStaleMatePosition()) { JOptionPane.showOptionDialog(frame, "Draw!","Information", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); return; } mitzis_turn=false; } } } }
package de.germanspacebuild.plugins.fasttravel.Listener; import de.germanspacebuild.plugins.fasttravel.FastTravel; import de.germanspacebuild.plugins.fasttravel.data.FastTravelDB; import de.germanspacebuild.plugins.fasttravel.data.FastTravelSign; import de.germanspacebuild.plugins.fasttravel.events.FastTravelFoundEvent; import de.germanspacebuild.plugins.fasttravel.util.BlockUtil; import de.germanspacebuild.plugins.fasttravel.util.FastTravelUtil; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Sign; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import java.util.Arrays; public class FTPlayerListener implements Listener { private FastTravel plugin; public FTPlayerListener(FastTravel plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerInteractEvent(PlayerInteractEvent event) { if (!Arrays.asList(BlockUtil.signBlocks).contains(event.getClickedBlock().getType())) { return; } else if (!event.getPlayer().hasPermission(FastTravel.PERMS_BASE + "use")) { plugin.getIOManger().sendTranslation(event.getPlayer(), "Perms.Not"); return; } else if (event.getAction() != Action.RIGHT_CLICK_AIR || event.getAction() != Action.RIGHT_CLICK_BLOCK) { return; } else if (!FastTravelUtil.isFTSign(event.getClickedBlock())) { return; } Sign sign = (Sign) event.getClickedBlock().getState(); if (FastTravelDB.getSignsFor(event.getPlayer().getUniqueId()).contains(FastTravelDB.getSign(sign.getLine(1)))) { plugin.getIOManger().sendTranslation(event.getPlayer(), "Sign.Found.Already".replaceAll("%sign", sign.getLine(1))); } else { plugin.getServer().getPluginManager().callEvent(new FastTravelFoundEvent(event.getPlayer(), FastTravelDB.getSign(sign.getLine(1)))); } } @EventHandler(ignoreCancelled = true) public void onPlayerInteractWand(PlayerInteractEvent event) { if (!Arrays.asList(BlockUtil.signBlocks).contains(event.getClickedBlock().getType())) { } else if (event.getItem() == null) { } else if (event.getItem().getType() != Material.BONE) { } else if (!FastTravelUtil.isMoveWand(event.getItem())) { } else { if (!(event.getClickedBlock().getState() instanceof Sign)) { return; } Sign signBlock = ((Sign) event.getClickedBlock().getState()); for (String line : signBlock.getLines()) { if (!line.isEmpty()) { plugin.getIOManger().sendTranslation(event.getPlayer(), "Command.Move.SignNotEmpty"); return; } } String signName = event.getItem().getItemMeta().getLore().get(0).replace("Sign: " + ChatColor.GOLD, ""); FastTravelSign sign = FastTravelDB.getSign(signName); if (sign == null) { plugin.getIOManger().send(event.getPlayer(), plugin.getIOManger().translate("Sign.Exists.Not"). replaceAll("%sign", signName)); return; } FastTravelUtil.formatSign(signBlock, sign.getName()); Location loc = sign.getSignLocation(); loc.getBlock().setType(Material.AIR); if (sign.getSignLocation() == sign.getTPLocation()) { sign.setTPLocation(signBlock.getLocation()); } sign.setSignLocation(signBlock.getLocation()); event.getPlayer().getInventory().remove(event.getItem()); plugin.getIOManger().send(event.getPlayer(), plugin.getIOManger().translate("Command.Move.Success") .replace("%sign", sign.getName())); } } @EventHandler(priority = EventPriority.NORMAL) public void onPlayerJoinEvent(PlayerJoinEvent event) { if (event.getPlayer().hasPermission(FastTravel.PERMS_BASE + "update") && FastTravel.getInstance().needUpdate) { plugin.getIOManger().send(event.getPlayer(), plugin.getIOManger().translate( "Plugin.Update.Player").replace("%old", plugin.getDescription().getVersion()) .replaceAll("%new", plugin.getUpdateChecker().getVersion()).replaceAll("%link", plugin.getUpdateChecker().getLink())); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerItemDropEvent(PlayerDropItemEvent event) { if (event.getItemDrop().getItemStack().getType() != Material.BONE) { return; } if (FastTravelUtil.isMoveWand(event.getItemDrop().getItemStack())) { event.setCancelled(true); } } }
package edu.umkc.sce.rdf; import java.io.IOException; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.TableNotFoundException; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.util.Bytes; import com.hp.hpl.jena.graph.BulkUpdateHandler; import com.hp.hpl.jena.graph.Capabilities; import com.hp.hpl.jena.graph.GraphEventManager; import com.hp.hpl.jena.graph.GraphStatisticsHandler; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.TransactionHandler; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.graph.TripleMatch; import com.hp.hpl.jena.shared.AddDeniedException; import com.hp.hpl.jena.shared.DeleteDeniedException; import com.hp.hpl.jena.shared.PrefixMapping; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.util.iterator.NullIterator; public class Graph implements com.hp.hpl.jena.graph.Graph { private String name; private HBaseAdmin admin; private Store store; private PrefixMapping prefixMapping; private TransactionHandler transactionHandler; private GraphEventManager graphEventManager; public Graph(Store store, HBaseAdmin admin) { this.store = store; this.prefixMapping = new edu.umkc.sce.rdf.PrefixMapping(null, null); this.transactionHandler = new TxHandler(this); this.graphEventManager = new GraphEventMgr(); this.admin = admin; System.out.println("CTOR"); } public boolean dependsOn(com.hp.hpl.jena.graph.Graph other) { System.out.println("dependsOn"); return false; } public TransactionHandler getTransactionHandler() { System.out.println("txHandler"); return transactionHandler; } public BulkUpdateHandler getBulkUpdateHandler() { System.out.println("bulk upd handler"); return null; } public Capabilities getCapabilities() { System.out.println("capabilities"); return null; } public GraphEventManager getEventManager() { System.out.println("evtMgr"); return graphEventManager; } public GraphStatisticsHandler getStatisticsHandler() { System.out.println("staticsHandler"); return null; } public PrefixMapping getPrefixMapping() { System.out.println("prefixMapping"); return this.prefixMapping; } public static String getNameOfNode(Node node) { String pred = null; if (node.isURI()) pred = node.getLocalName(); else if (node.isBlank()) pred = node.getBlankNodeLabel(); else if (node.isLiteral()) pred = node.getLiteralValue().toString(); else pred = node.toString(); return pred; } private HashMap<TableName, HTable> tables = new HashMap<TableName, HTable>(); private static final TableAxis[] coreAxis = new TableAxis[] { TableAxis.Subject, TableAxis.Object }; public void add(Triple t) throws AddDeniedException { Node s = t.getSubject(), p = t.getPredicate(), o = t.getObject(); for (TableAxis axis : coreAxis) { TableName tableName = getTableName(axis, p); HTable ht; try { ht = getTable(tableName); } catch (IOException e) { throw new AddDeniedException("IOException while adding triple", t); } byte[] rowKey = null; if (axis == TableAxis.Subject) rowKey = Bytes.toBytes(s.toString()); else rowKey = Bytes.toBytes(o.toString()); Put update = new Put(rowKey); byte[] colFamilyBytes = "nodes".getBytes(), colQualBytes = null; if (axis == TableAxis.Subject) colQualBytes = Bytes.toBytes(o.toString()); else colQualBytes = Bytes.toBytes(s.toString()); update.add(colFamilyBytes, colQualBytes, Bytes.toBytes("")); put(ht, update, rowKey, colFamilyBytes, colQualBytes); update = null; rowKey = null; colFamilyBytes = null; colQualBytes = null; } } private HTable getTable(TableName tableName) throws IOException { HTable ht = null; if (tables.containsKey(tableName)) { ht = tables.get(tableName); } else { try { HTableDescriptor htd = admin.getTableDescriptor(tableName); } catch (TableNotFoundException e) { ht = createTable(tableName, admin); } ht = new HTable(tableName, admin.getConnection()); tables.put(tableName, ht); } return ht; } final ExecutorService executor = Executors.newFixedThreadPool(15); private void put(final HTable table, final Put update, final byte[] bytes, final byte[] colFamilyBytes, final byte[] colQualBytes) { executor.execute(new Runnable() { public void run() { try { table.checkAndPut(bytes, colFamilyBytes, colQualBytes, null, update); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { table.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); } private HTable createTable(TableName tableName, HBaseAdmin admin) throws IOException { HTable table = null; if (!admin.tableExists(tableName)) { System.out.printf("Creating table %s\n", tableName.getNameAsString()); HTableDescriptor desc = new HTableDescriptor(tableName); HColumnDescriptor cf = new HColumnDescriptor("nodes".getBytes()); desc.addFamily(cf); admin.createTable(desc); } table = new HTable(tableName, admin.getConnection()); table.setAutoFlush(false, true); return table; } public void delete(Triple t) throws DeleteDeniedException { System.out.println("delete(Triple)"); } public ExtendedIterator<Triple> find(TripleMatch m) { System.out.println("find(TripleMatch)"); ExtendedIterator<Triple> trIter = NullIterator.instance(); // Node s = m.getMatchSubject(); // Node p = m.getMatchPredicate(); // Node o = m.getMatchObject(); // // FIXME More robust resolution of axis // TableAxis axis = (o==null || !o.isConcrete() // ?TableAxis.Subject:TableAxis.Object); // try { // if(axis == TableAxis.Subject){ // Get res = new Get(Bytes.toBytes(s.toString())); // if (p.isConcrete()) { // TableName tableName = getTableName(axis, p); // HTable table = getTable(tableName); // Result rr = null; // if (table != null) // rr = table.get(res); // if (rr != null && !rr.isEmpty()) // // XXX // trIter = null; // // rr. new HBaseRdfSingleRowIterator(rr, sm, pm, om, // // pm.toString(), // // TableDescVPCommon.COL_FAMILY_NAME_STR); // } else { // trIter = null; // new HBaseRdfAllTablesIterator(); // // Iterate over all tables to find all triples for the // // subject // assertAllTables(); // for(TableName tableName:tables.keySet()){ // if(!isOnAxis(axis, tableName)) // continue; // HTable table = tables.get(tableName); // Result rr = null; // if (table != null) // rr = table.get(res); // if (rr != null && !rr.isEmpty()) // // XXX // trIter = null; // // ((HBaseRdfAllTablesIterator) trIter) // // .addIter(new HBaseRdfSingleRowIterator( // // getPredicateMapping(tblName), // // TableDescVPCommon.COL_FAMILY_NAME_STR)); // res = null; // } else if (axis == TableAxis.Object) { // Get res = new Get(Bytes.toBytes(o.toString())); // if (p.isConcrete()) { // TableName tableName = getTableName(axis, p); // HTable table = getTable(tableName); // Result rr = null; // if (table != null) // rr = table.get(res); // if (rr != null && !rr.isEmpty()) // // XXX // trIter = null; // // trIter = new HBaseRdfSingleRowIterator(rr, sm, pm, om, // // pm.toString(), // // TableDescVPCommon.COL_FAMILY_NAME_STR); // } else { // trIter = new HBaseRdfAllTablesIterator(); // // Iterate over all tables to find all triples for the // // subject // Iterator<String> iterTblNames = tables().keySet() // .iterator(); // while (iterTblNames.hasNext()) { // String tblName = iterTblNames.next(); // String mapPrefix = processTblName(tblName, tblPrefix, // "objects", "subjects"); // if (mapPrefix == null) // continue; // HTable table = tables().get(tblName); // Result rr = null; // if (table != null) // rr = table.get(res); // if (rr != null && !rr.isEmpty()) // ((HBaseRdfAllTablesIterator) trIter) // .addIter(new HBaseRdfSingleRowIterator( // getPredicateMapping(tblName), // TableDescVPCommon.COL_FAMILY_NAME_STR)); // tblName = null; // mapPrefix = null; // ((HBaseRdfAllTablesIterator) trIter).closeIter(); // res = null; // } else if (tblType.equalsIgnoreCase("pred")) { // // Create an iterator over all rows in the subject's HTable // Scan scanner = new Scan(); // HTable table = tables().get( // name() + "-" + tblPrefix + "-" // + HBaseUtils.getNameOfNode(pm) + "-subjects"); // if (table != null) // trIter = new HBaseRdfSingleTableIterator( // table.getScanner(scanner), sm, pm, om, // pm.toString(), // TableDescVPCommon.COL_FAMILY_NAME_STR); // } else if (tblType.equalsIgnoreCase("all")) { // trIter = new HBaseRdfAllTablesIterator(); // // Iterate over all tables to find all triples for the subject // Iterator<String> iterTblNames = tables().keySet().iterator(); // while (iterTblNames.hasNext()) { // String tblName = iterTblNames.next(); // String mapPrefix = processTblName(tblName, tblPrefix, // "subjects", "objects"); // if (mapPrefix == null) // continue; // HTable table = tables().get(tblName); // Scan scanner = new Scan(); // if (table != null) // ((HBaseRdfAllTablesIterator) trIter) // .addIter(new HBaseRdfSingleTableIterator(table // .getScanner(scanner), sm, pm, om, // getPredicateMapping(tblName), // TableDescVPCommon.COL_FAMILY_NAME_STR)); // tblName = null; // mapPrefix = null; // ((HBaseRdfAllTablesIterator) trIter).closeIter(); // sb = null; // } catch (Exception e) { // throw new HBaseRdfException("Error in querying tables", e); return trIter; } private boolean isOnAxis(TableAxis axis, TableName name) { return name.getNameAsString().endsWith(axis.toString().toLowerCase()); } private boolean allTableNamesLoaded; private synchronized void assertAllTables() throws IOException { if (!allTableNamesLoaded) { for (TableName tableName : admin.listTableNames()) { if (!tables.containsKey(tableName)) { tables.put(tableName, new HTable(tableName, admin.getConnection())); } } allTableNamesLoaded = true; } } private TableName getTableName(TableAxis axis, Node node) { StringBuilder nameBuilder = new StringBuilder(); nameBuilder.append("tbl-").append(getNameOfNode(node)).append("-") .append(axis.toString().toLowerCase()); TableName tableName = TableName.valueOf("rdf", nameBuilder.toString()); return tableName; } public ExtendedIterator<Triple> find(Node s, Node p, Node o) { System.out.println("find(Node,Node,Node)"); // TODO: implement query if (p.isConcrete()) { // perform gets TableName tableName; if (s.isConcrete()) { tableName = getTableName(TableAxis.Subject, p); Get get = new Get(s.toString().getBytes()); if (o.isConcrete()) { get.addColumn("nodes".getBytes(), o.toString().getBytes()); } else { get.addFamily("nodes".getBytes()); } HTable table; try { table = getTable(tableName); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return NullIterator.instance(); } Result getResult = null; try { getResult = table.get(get); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (getResult == null || getResult.isEmpty()) { return NullIterator.instance(); } return new ResultIterator(getResult, s, p, o, p.toString(), "nodes"); } } else { // perform scans } return null; } public boolean isIsomorphicWith(com.hp.hpl.jena.graph.Graph g) { System.out.println("isIsomorphicWith(Graph)"); return false; } public boolean contains(Node s, Node p, Node o) { System.out.println("contains(Node,Node,Node)"); return false; } public boolean contains(Triple t) { System.out.println("contains(Triple)"); return false; } public void clear() { System.out.println("clear"); } public void remove(Node s, Node p, Node o) { System.out.println("remove(Node,Node,Node)"); } public void close() { System.out.println("close"); } public boolean isEmpty() { System.out.println("isEmpty"); return false; } public int size() { System.out.println("size"); return 0; } public boolean isClosed() { System.out.println("isClosed"); try { executor.shutdown(); executor.awaitTermination(1, TimeUnit.HOURS); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } public void sync() { } }
package de.rwth.idsg.velocity.web.rest.exception; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.TypeMismatchException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.List; import java.util.Locale; @ControllerAdvice @Slf4j public class GeneralExceptionHandler { @Autowired private MessageSource messageSource; @ExceptionHandler(Exception.class) public void processException(HttpServletResponse response, Exception e) { log.error("Exception happened", e); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } @ExceptionHandler(DatabaseException.class) public ResponseEntity<ErrorMessage> processDatabaseException(DatabaseException e) { log.error("Exception happened", e); HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; ErrorMessage msg = new ErrorMessage( status.value(), status.getReasonPhrase(), e.getMessage() ); return new ResponseEntity<>(msg, status); } /* * Catches the controller path errors of the Rest API. * * Example: If a controller declares an integer in the path, but frontend sends anything but an integer. */ @ExceptionHandler(TypeMismatchException.class) public ResponseEntity<ErrorMessage> processTypeException(TypeMismatchException e) { log.error("Exception happened", e); HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY; ErrorMessage msg = new ErrorMessage( status.value(), status.getReasonPhrase(), e.getMessage() ); return new ResponseEntity<>(msg, status); } /* * Catches the Hibernate validation errors and * responds with an error message in appropriate language. */ @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ErrorMessage> processValidationException(MethodArgumentNotValidException e) { log.error("Exception happened", e); Locale currentLocale = LocaleContextHolder.getLocale(); List<FieldError> errors = e.getBindingResult().getFieldErrors(); List<String> errorMessages = new ArrayList<>(); for (FieldError fieldError : errors) { String localizedError = messageSource.getMessage(fieldError, currentLocale); errorMessages.add(localizedError); } HttpStatus status = HttpStatus.BAD_REQUEST; ErrorMessage msg = new ErrorMessage( status.value(), status.getReasonPhrase(), "Validation failed for the submitted form" ); msg.setFieldErrors(errorMessages); return new ResponseEntity<>(msg, status); } }
package de.skuzzle.enforcer.restrictimports.parser; import de.skuzzle.enforcer.restrictimports.parser.lang.LanguageSupport; import java.nio.charset.Charset; import java.nio.file.Path; /** * For parsing a source file into a {@link ParsedFile}. */ public interface ImportStatementParser { /** * Constructs a default instance of the parser which uses the provided charset. * * @param charset The charset to use. * @return The parser instance. */ static ImportStatementParser defaultInstance(Charset charset) { return new ImportStatementParserImpl(new SkipCommentsLineSupplier(charset)); } /** * Parses the given source file using the given {@link LanguageSupport} * implementation to recognize import statements. * * @param sourceFilePath The path of the file to parse. * @param languageSupport For parsing the import statements. * @return The parsed file. * @throws de.skuzzle.enforcer.restrictimports.io.RuntimeIOExceptionn In case reading the file fails. */ ParsedFile parse(Path sourceFilePath, LanguageSupport languageSupport); }
import Misc.Constants; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class getAcceptedConnections { public static void getAcceptedConnections(HttpServletRequest req, HttpServletResponse resp, Connection connection, String id) throws IOException { Long src_id; try { src_id = Long.parseLong(id); } catch (NumberFormatException e) { resp.setStatus(Constants.BAD_REQUEST); return; } try { ResultSet rs = runSelectQuery(connection, src_id); ArrayList<Long> id_arr = parseIDs(rs, src_id); if (id_arr == null) { resp.setStatus(Constants.BAD_REQUEST); return; } resp.getWriter().print(makeUserJSON(connection, id_arr)); resp.getWriter().print("3"); } catch (SQLException| JSONException e) { resp.setStatus(Constants.INTERNAL_SERVER_ERROR); resp.getWriter().print(e.getMessage()); } } public static ResultSet runSelectQuery(Connection connection, long id) throws SQLException{ String select_sql = "Select * from Connections where (requester_id = ? or target_id = ?) " + "and status = ?"; PreparedStatement stmt = connection.prepareStatement(select_sql); stmt.setLong(1, id); stmt.setLong(2, id); stmt.setString(3, Constants.ACCEPTED); return stmt.executeQuery(); } public static ArrayList<Long> parseIDs(ResultSet rs, Long src_id) throws SQLException{ ArrayList<Long> id_list = new ArrayList<Long>(); Long req_id, target_id; while (rs.next()) { req_id = rs.getLong(Constants.REQ_ID); target_id = rs.getLong(Constants.TARGET_ID); if (src_id.equals(req_id)) id_list.add(rs.getLong(Constants.TARGET_ID)); else if (src_id.equals(target_id)) id_list.add(rs.getLong(Constants.REQ_ID)); else return null; } return id_list; } public static String makeUserJSON(Connection connection, ArrayList<Long> id_list) throws SQLException, JSONException{ String select_sql = "Select user_id, name from Profile where user_id = ANY (?)"; PreparedStatement stmt = connection.prepareStatement(select_sql); stmt.setArray(1, connection.createArrayOf("bigint", id_list.toArray())); ResultSet rs = stmt.executeQuery(); JSONArray userArr = new JSONArray(); JSONObject user; while (rs.next()) { user = new JSONObject(); user.put(Constants.USER_ID, rs.getLong(Constants.USER_ID)); user.put(Constants.STATUS, Constants.ACCEPTED); userArr.put(user); } return userArr.toString(); } }
package io.disassemble.knn; import com.google.gson.*; import io.disassemble.knn.feature.BooleanFeature; import io.disassemble.knn.feature.DoubleFeature; import io.disassemble.knn.feature.Feature; import io.disassemble.knn.feature.IntegerFeature; import io.disassemble.knn.util.SourceEditor; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; /** * @author Tyler Sedlar * @since 5/17/16 */ public class KNN { public final FeatureSet[] sets; public KNN(FeatureSet[] set) { this.sets = set; } public KNN(Collection<FeatureSet> collection) { this.sets = collection.toArray(new FeatureSet[collection.size()]); } public NeighborList compute(int k, FeatureSet likely) { List<Neighbor> results = Arrays.asList(new Neighbor[k]); for (FeatureSet set : sets) { double distance = set.distanceTo(likely); for (int i = 0; i < results.size(); i++) { Neighbor neighbor = results.get(i); boolean closer = (neighbor != null && distance < neighbor.set.distanceTo(likely)); int pos = (isFull(results) && closer ? i : findInsertPosition(results, distance)); if (pos != -1) { Collections.rotate(results.subList(pos, results.size()), 1); results.set(pos, new Neighbor(set, distance)); break; } } } return new NeighborList(results, likely); } private boolean isFull(List list) { for (Object o : list) { if (o == null) { return false; } } return true; } private int findInsertPosition(List<Neighbor> neighbors, double distance) { for (int idx = 0; idx < neighbors.size(); idx++) { Neighbor neighbor = neighbors.get(idx); if (neighbor == null || distance < neighbor.distance) { return idx; } } return -1; } public FeatureSet findSet(String category) { for (FeatureSet set : sets) { if (set.category.equals(category)) { return set; } } return null; } public List<FeatureSet> findSets(String category) { List<FeatureSet> results = new ArrayList<>(); for (FeatureSet set : sets) { if (set.category.equals(category)) { results.add(set); } } return results; } public void writeJSON(Path file) throws IOException { Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonObject root = new JsonObject(); JsonArray rootArray = new JsonArray(); for (FeatureSet set : sets) { JsonObject object = new JsonObject(); object.addProperty("category", set.category); JsonObject features = new JsonObject(); set.map(f -> true).forEach((k, v) -> { JsonObject valObj = new JsonObject(); valObj.add("value", gson.toJsonTree(v.value)); valObj.addProperty("weight", v.weight); features.add(k, valObj); }); object.add("features", features); rootArray.add(object); } root.add("sets", rootArray); try (FileWriter output = new FileWriter(file.toFile())) { gson.toJson(root, output); } } public static KNN fromJSON(Path filePath, SourceEditor<JsonEntry, Feature> editor) throws IOException { JsonObject json = new JsonParser() .parse(new String(Files.readAllBytes(filePath))) .getAsJsonObject(); List<FeatureSet> sets = new ArrayList<>(); JsonArray jsonSets = json.getAsJsonArray("sets"); jsonSets.forEach(data -> { JsonObject info = data.getAsJsonObject(); String category = info.get("category").getAsString(); JsonObject features = info.getAsJsonObject("features"); Set<Map.Entry<String, JsonElement>> attrs = features.entrySet(); Feature[] featureArray = new Feature[attrs.size()]; int idx = 0; for (Map.Entry<String, JsonElement> entry : attrs) { JsonObject entryObj = entry.getValue().getAsJsonObject(); featureArray[idx++] = editor.edit(new JsonEntry(entry.getKey(), entryObj)); } sets.add(new FeatureSet(category, featureArray)); }); return new KNN(sets); } }
package edu.upc.caminstech.equipstic.client; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Optional; import java.util.TimeZone; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClients; import org.springframework.http.MediaType; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; public abstract class EquipsTicRestTemplateBuilder { private static final TimeZone EQUIPSTIC_SERVER_TIMEZONE = TimeZone.getTimeZone("Europe/Madrid"); private EquipsTicRestTemplateBuilder() { // constructor privat; classe no instanciable } public static RestTemplate createRestTemplate(URI baseUri, String username, String password, TimeZone timeZone) { HttpClient httpClient = prepareHttpClient(baseUri, username, password); return prepareRestTemplate(httpClient, timeZone); } public static RestTemplate createRestTemplate(URI baseUri, String username, String password) { return createRestTemplate(baseUri, username, password, EQUIPSTIC_SERVER_TIMEZONE); } private static HttpClient prepareHttpClient(URI baseUri, String username, String password) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(baseUri.getHost(), baseUri.getPort()); Credentials credentials = new UsernamePasswordCredentials(username, password); credsProvider.setCredentials(authScope, credentials); return HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); } private static RestTemplate prepareRestTemplate(HttpClient httpClient, TimeZone timeZone) { RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient)); fixSupportedMediaTypes(template); fixJacksonObjectMapperTimezone(template, timeZone); return template; } private static void fixJacksonObjectMapperTimezone(RestTemplate template, TimeZone timeZone) { ObjectMapper mapper = getObjectMapper(template); if (mapper != null) { mapper.setTimeZone(timeZone); } } private static ObjectMapper getObjectMapper(RestTemplate template) { MappingJackson2HttpMessageConverter converter = getJacksonMessageConverterIfPresent(template); if (converter != null) { return converter.getObjectMapper(); } return null; } private static void fixSupportedMediaTypes(RestTemplate template) { MappingJackson2HttpMessageConverter converter = getJacksonMessageConverterIfPresent(template); if (converter != null) { converter.setSupportedMediaTypes(Arrays.asList( new MediaType("application", "json", StandardCharsets.UTF_8), new MediaType("text", "plain", StandardCharsets.UTF_8))); } } private static MappingJackson2HttpMessageConverter getJacksonMessageConverterIfPresent(RestTemplate template) { Optional<HttpMessageConverter<?>> converter = template.getMessageConverters().stream() .filter(MappingJackson2HttpMessageConverter.class::isInstance).findFirst(); if (converter.isPresent()) { return (MappingJackson2HttpMessageConverter) converter.get(); } return null; } }
package io.biblia.workflows.definition.parser.v1; import com.google.common.base.CharMatcher; import io.biblia.workflows.definition.Action; import io.biblia.workflows.ConfigurationKeys; import io.biblia.workflows.Configuration; import io.biblia.workflows.definition.ActionAttributesConstants; import io.biblia.workflows.definition.ActionType; import io.biblia.workflows.definition.CommandLineAction; import io.biblia.workflows.hdfs.HdfsUtil; import io.biblia.workflows.definition.parser.WorkflowParseException; import org.bson.Document; import java.net.MalformedURLException; import java.util.*; public class CommandLineActionParser extends io.biblia.workflows.definition.parser.ActionParser implements ActionAttributesConstants, ConfigurationKeys { private static CommandLineActionParser instance; private CommandLineActionParser() { } public static CommandLineActionParser getInstance() { if (null == instance) { instance = new CommandLineActionParser(); } return instance; } /** * 2. ACTIONS 2.1 Components of the action: 2.1.1 Name and type 2.1.2 Parent * actions. 2.1.3 Input parameters 2.1.4 Output parameters 2.1.5 * Configuration parameters: The value of configuration parameters cannot * have spaces. 2.1.6 Name of the class of the action. * * Example provided below: * * { * type: "command-line", * actionId: 1, * name: "testing3", * mainClassName: "testing.java", * jobTracker: "urlTOJobTracker", * nameNode: "urlToNameNode", * forceComputation: true, * actionFolder: "/path/to/folder", * parentActions: [ 2 ], { name: "testing2" } ], * additionalInput: [ { value: * "path/to/file" } ], * outputParameters: [ { value: "path/to/file" }], * configurationParameters: [ { value: "anything" } ] } * * @throws WorkflowParseException */ @Override public Action parseAction(Document actionObject) throws WorkflowParseException { String type = (String) actionObject.get("type"); if (null == type) throw new WorkflowParseException("The action does not have a type attribute"); if (!type.equals(ActionType.COMMAND_LINE.name())) { throw new WorkflowParseException("The action type: " + type + " cannot be parsed by CommandLineActionParser"); } String name = (String) actionObject.get(ACTION_ORIGINAL_NAME); if (null == name) { name = (String) actionObject.get(ACTION_NAME); if (null == name) { throw new WorkflowParseException("The action does not have a name"); } } Integer actionId = (Integer) actionObject.getInteger(ACTION_ID); if (null == actionId) { throw new WorkflowParseException("The action does not have an id"); } String mainClassName = (String) actionObject.get(COMMANDLINE_MAIN_CLASS_NAME); if (null == mainClassName) throw new WorkflowParseException("The action does not have a mainClassName"); String nameNode = (String) actionObject.get(COMMANDLINE_NAME_NODE); if (null == nameNode) { nameNode = Configuration.getValue(NAMENODE); if (null == nameNode) throw new WorkflowParseException("The action does not have a nameNode attribute"); } String jobTracker = (String) actionObject.get(COMMANDLINE_JOB_TRACKER); if (null == jobTracker) { jobTracker = Configuration.getValue(JOBTRACKER); if (null == jobTracker) throw new WorkflowParseException("The action does not have a jobTracker attribute"); } String actionFolder = (String) actionObject.get(ACTION_FOLDER); if (null == actionFolder) throw new WorkflowParseException("The action does not have attribute <actionFolder>"); Boolean forceComputation = (Boolean) actionObject.get(ACTION_FORCE_COMPUTATION); forceComputation = (forceComputation == null || !forceComputation) ? false : true; String outputFolder = actionObject.getString(ACTION_OUTPUT_PATH); if (null != outputFolder) { try{ outputFolder = HdfsUtil.combinePath(nameNode, outputFolder); } catch(MalformedURLException e) { throw new WorkflowParseException("Malformed output Folder provided: " + outputFolder); } } List<Integer> parentActionIds = this.getParentActionIds(actionObject); LinkedHashMap<String, String> additionalInput = this.getInputParameters(actionObject); LinkedHashMap<String, String> configurationParameters = this.getConfigurationParameters(actionObject); if (null == outputFolder) { return new CommandLineAction( name, actionId, actionFolder, additionalInput, configurationParameters, parentActionIds, forceComputation, mainClassName, jobTracker, nameNode); } else { return new CommandLineAction( name, actionId, actionFolder, additionalInput, configurationParameters, parentActionIds, forceComputation, outputFolder, mainClassName, jobTracker, nameNode); } } private List<Integer> getParentActionIds(Document actionObject) { @SuppressWarnings("unchecked") List<Integer> parentActions = (List<Integer>) actionObject.get(ACTION_PARENT_ACTIONS, List.class); if (null == parentActions) { return Collections.unmodifiableList(new ArrayList<>()); } return Collections.unmodifiableList(parentActions); } private LinkedHashMap<String, String> getInputParameters(Document actionObject) { LinkedHashMap<String, String> toReturn = new LinkedHashMap<>(); @SuppressWarnings("unchecked") List<Document> inputParameters = (List<Document>) actionObject.get(ACTION_ADDITIONAL_INPUT, List.class); if (null == inputParameters) { return toReturn; } Iterator<Document> inputParametersIt = inputParameters.iterator(); int counter = 0; while (inputParametersIt.hasNext()) { counter++; Document inputParameterObject = inputParametersIt.next(); String key = (String) inputParameterObject.get("key"); String value = (String) inputParameterObject.get("value"); if (null == value) { continue; } if (null == key) { toReturn.put(Integer.toString(counter), value); } else { toReturn.put(key, value); } } return toReturn; } /** * If the configuration parameter has spaces. * * @param actionObject * @return * @throws WorkflowParseException */ private LinkedHashMap<String, String> getConfigurationParameters(Document actionObject) throws WorkflowParseException { LinkedHashMap<String, String> toReturn = new LinkedHashMap<>(); @SuppressWarnings("unchecked") List<Document> configurationParameters = (List<Document>) actionObject.get(ACTION_CONFIGURATION_PARAMETERS, List.class); if (null == configurationParameters) { return toReturn; } Iterator<Document> configurationParametersIt = configurationParameters.iterator(); int counter = 0; while (configurationParametersIt.hasNext()) { counter++; Document configurationParametersObject = configurationParametersIt.next(); String key = (String) configurationParametersObject.get("key"); String value = (String) configurationParametersObject.get("value"); if (null == value) { continue; } if (CharMatcher.WHITESPACE.matchesAnyOf(value)) { throw new WorkflowParseException("The configuration parameter: \"" + value + "\" has spaces"); } if (null == key) { toReturn.put(Integer.toString(counter), value); } else { toReturn.put(key, value); } } return toReturn; } }
package io.github.achtern.AchternEngine.core.rendering.drawing; import io.github.achtern.AchternEngine.core.rendering.Vertex; import io.github.achtern.AchternEngine.core.rendering.mesh.MeshData; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL11.glDrawElements; import static org.lwjgl.opengl.GL15.*; import static org.lwjgl.opengl.GL20.*; import static org.lwjgl.opengl.GL30.glBindVertexArray; public class SolidDraw implements DrawStrategy { @Override public void draw(MeshData data) { glBindVertexArray(data.getVao()); // Position glEnableVertexAttribArray(0); // Texture Coordinates glEnableVertexAttribArray(1); // Normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, data.getVbo()); // Position glVertexAttribPointer(0, 3, GL_FLOAT, false, Vertex.SIZE * 4, 0); // Texture Coordinates glVertexAttribPointer(1, 2, GL_FLOAT, false, Vertex.SIZE * 4, 12); // Normals glVertexAttribPointer(2, 3, GL_FLOAT, false, Vertex.SIZE * 4, 20); drawElements(data); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.getIbo()); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); } protected void drawElements(MeshData data) { glDrawElements(GL_TRIANGLES, data.getSize(), GL_UNSIGNED_INT, 0); } }
package kfk.load; import com.cyngn.kafka.produce.KafkaPublisher; import com.cyngn.kafka.produce.MessageProducer; import io.vertx.core.DeploymentOptions; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import java.io.Closeable; import java.io.IOException; public class LoadGenerator implements Closeable { private final Args args; private final MessageGenerator meessageGenerator; private final Vertx vertx; public LoadGenerator(final Args args) { vertx = Vertx.vertx(); this.args = args; this.meessageGenerator = new MessageGenerator(args.messageSize()); } public void start() { final DeploymentOptions deploymentOptions = createDeploymentOptions(); deployKafkaMessageProducers(deploymentOptions); } private void startMessagePublishers() { KafkaPublisher publisher = new KafkaPublisher(vertx.eventBus()); while (isRunning()) { publisher.send(args.topic(), meessageGenerator.nextMessage()); } } private boolean isRunning() { return true; } private DeploymentOptions createDeploymentOptions() { // sample config JsonObject producerConfig = new JsonObject(); producerConfig.put("bootstrap.servers", args.kafkaCluster().toString()); producerConfig.put("serializer.class", args.messageSerializerClass()); producerConfig.put("default_topic", args.topic()); return new DeploymentOptions() .setInstances(args.threads()) .setConfig(producerConfig); } @Override public void close() throws IOException { } void deployKafkaMessageProducers(final DeploymentOptions deploymentOptions) { // use your vertx reference to deploy the consumer verticle vertx.deployVerticle(MessageProducer.class.getName(), deploymentOptions, deploy -> { if (deploy.failed()) { System.err.println( String.format("Failed to start kafka producer verticle, ex: %s", deploy.cause())); vertx.close(); return; } System.out.println("kafka producer verticle started"); vertx.executeBlocking(f -> startMessagePublishers(), r -> { }); }); } }
package net.earthcomputer.easyeditors.gui.command.slot; import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; import net.minecraftforge.fml.client.config.HoverChecker; /** * A command slot which represents a button * * @author Earthcomputer * */ public abstract class CommandSlotButton extends GuiCommandSlotImpl { private int x; private int y; private GuiClickListenerButton wrappedButton; private String hoverText; private HoverChecker hoverChecker; public CommandSlotButton(int width, int height, String text) { this(width, height, text, null); } public CommandSlotButton(int width, int height, String text, String hoverText) { super(width, height); wrappedButton = new GuiClickListenerButton(0, 0, width, height, text); this.hoverText = hoverText; } @Override public int readFromArgs(String[] args, int index) { return 0; } @Override public void addArgs(List<String> args) { } /** * * @return The text displayed in the button */ public String getText() { return wrappedButton.displayString; } /** * * @return The text displayed when hovered */ public String getHoverText() { return hoverText; } /** * Sets the text displayed when hovered * * @param hoverText */ public void setHoverText(String hoverText) { this.hoverText = hoverText; } /** * * @return Whether the button is enabled */ public boolean isEnabled() { return wrappedButton.enabled; } /** * Sets whether the button is enabled * * @param enabled */ public void setEnabled(boolean enabled) { wrappedButton.enabled = enabled; } /** * * @return The text color in the button */ public int getTextColor() { return wrappedButton.packedFGColour; } /** * Sets the text color in the button * * @param textColor */ public void setTextColor(int textColor) { wrappedButton.packedFGColour = textColor; } @Override public void draw(int x, int y, int mouseX, int mouseY, float partialTicks) { GlStateManager.disableLighting(); GlStateManager.disableFog(); if (x != this.x || y != this.y) { this.x = x; this.y = y; GuiClickListenerButton oldButton = wrappedButton; GuiClickListenerButton newButton = wrappedButton = new GuiClickListenerButton(x, y, getWidth(), getHeight(), oldButton.displayString); newButton.enabled = oldButton.enabled; newButton.packedFGColour = oldButton.packedFGColour; } wrappedButton.drawButton(Minecraft.getMinecraft(), mouseX, mouseY); if (hoverText != null) { if (hoverChecker == null) hoverChecker = new HoverChecker(y, y + getHeight(), x, x + getWidth(), 1000); else hoverChecker.updateBounds(y, y + getHeight(), x, x + getWidth()); if (!getContext().isMouseInBounds(mouseX, mouseY)) hoverChecker.resetHoverTimer(); else if (hoverChecker.checkHover(mouseX, mouseY)) { drawTooltip(mouseX, mouseY, hoverText, 300); } } } @Override public boolean onMouseClicked(int mouseX, int mouseY, int mouseButton) { if (getContext().isMouseInBounds(mouseX, mouseY) && wrappedButton.mousePressed(Minecraft.getMinecraft(), mouseX, mouseY)) { wrappedButton.playPressSound(Minecraft.getMinecraft().getSoundHandler()); onPress(); } return false; } /** * Invoked when the button is pressed */ public abstract void onPress(); private static class GuiClickListenerButton extends GuiButton { public GuiClickListenerButton(int x, int y, int width, int height, String text) { super(0, x, y, width, height, text); } } }
package me.mneri.csv; import me.mneri.csv.exception.CsvConversionException; import me.mneri.csv.exception.CsvException; import me.mneri.csv.exception.UncheckedCsvException; import me.mneri.csv.exception.UnexpectedCharacterException; import java.io.*; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * Read csv streams and automatically transform lines into Java objects. * * @param <T> The type of the Java objects to read. * @author Massimo Neri &lt;<a href="mailto:hello@mneri.me">hello@mneri.me</a>&gt; */ public final class CsvReader<T> implements Closeable { // States private static final byte ERROR = -1; private static final byte START = 0; private static final byte QUOTE = 1; private static final byte ESCAP = 2; private static final byte STRNG = 3; private static final byte CARRG = 4; private static final byte FINSH = 5; // Actions private static final byte NO_OP = 0; private static final byte ACCUM = 1; private static final byte FIELD = 2; private static final byte NLINE = 4; //@formatter:off private static final byte[][] ACTIONS = { // * " , \r \n eof { ACCUM , NO_OP , FIELD , NO_OP , FIELD | NLINE, NO_OP }, // START { ACCUM , NO_OP , ACCUM , ACCUM , ACCUM , NO_OP }, // QUOTE { NO_OP , ACCUM , FIELD , NO_OP , FIELD | NLINE, FIELD | NLINE }, // ESCAP { ACCUM , ACCUM , FIELD , NO_OP , FIELD | NLINE, FIELD | NLINE }, // STRNG { NO_OP , NO_OP , NO_OP , NO_OP , FIELD | NLINE, NO_OP }, // CARRG { NO_OP , NO_OP , NO_OP , NO_OP , NO_OP , NO_OP }}; // FINSH //@formatter:on //@formatter:off private static final byte[][] TRANSITIONS = { // * " , \r \n eof { STRNG, QUOTE, START, CARRG, FINSH, FINSH }, // START { QUOTE, ESCAP, QUOTE, QUOTE, QUOTE, ERROR }, // QUOTE { ERROR, QUOTE, START, CARRG, FINSH, FINSH }, // ESCAP { STRNG, STRNG, START, CARRG, FINSH, FINSH }, // STRNG { ERROR, ERROR, ERROR, ERROR, FINSH, ERROR }, // CARRG { ERROR, ERROR, ERROR, ERROR, ERROR, ERROR }}; // FINSH //@formatter:on //@formatter:off private static final int ELEMENT_NOT_READ = 0; private static final int ELEMENT_READ = 1; private static final int NO_SUCH_ELEMENT = 2; private static final int CLOSED = 3; //@formatter:on private static final int DEFAULT_BUFFER_SIZE = 8192; private char[] buffer; private CsvDeserializer<T> deserializer; private T element; private RecyclableCsvLine line = new RecyclableCsvLine(); private int lines; private int next; private Reader reader; private int size; private int state = ELEMENT_NOT_READ; private CsvReader(Reader reader, CsvDeserializer<T> deserializer) { this.reader = reader; this.deserializer = deserializer; buffer = new char[DEFAULT_BUFFER_SIZE]; } private void checkClosedState() { if (state == CLOSED) { throw new IllegalStateException("The reader is closed."); } } /** * Closes the stream and releases any system resources associated with it. Once the stream has been closed, further * {@link CsvReader#hasNext()}, {@link CsvReader#next()} and {@link CsvReader#skip(int)} invocations will throw an * {@link IOException}. Closing a previously closed stream has no effect. * * @throws IOException if an I/O error occurs. */ @Override public void close() throws IOException { if (state == CLOSED) { return; } state = CLOSED; buffer = null; deserializer = null; element = null; line = null; reader.close(); reader = null; } private int columnOf(int charCode) { switch (charCode) { //@formatter:off case '"' : return 1; case ',' : return 2; case '\r': return 3; case '\n': return 4; case -1 : return 5; // EOF default : return 0; //@formatter:on } } /** * Returns {@code true} if the reader has more elements. (In other words, returns {@code true} if * {@link CsvReader#next()} would return an element rather than throwing an exception). * * @return {@code true} if the reader has more elements. * @throws CsvException if the csv is not properly formatted. * @throws IOException if an I/O error occurs. */ public boolean hasNext() throws CsvException, IOException { //@formatter:off if (state == ELEMENT_READ) { return true; } else if (state == NO_SUCH_ELEMENT) { return false; } //@formatter:on checkClosedState(); byte row = START; while (true) { int nextChar = read(); int column = columnOf(nextChar); int action = ACTIONS[row][column]; if ((action & ACCUM) != 0) { line.put((char) nextChar); } else if ((action & FIELD) != 0) { line.markField(); if ((action & NLINE) != 0) { lines++; try { T object = deserializer.deserialize(line); line.clear(); element = object; state = ELEMENT_READ; return true; } catch (Exception e) { throw new CsvConversionException(line, e); } } } row = TRANSITIONS[row][column]; if (row == FINSH) { state = NO_SUCH_ELEMENT; return false; } else if (row == ERROR) { throw new UnexpectedCharacterException(lines, nextChar); } } } private Iterator<T> iterator() { return new Iterator<T>() { @Override public boolean hasNext() { //@formatter:off try { return CsvReader.this.hasNext(); } catch (CsvException e) { throw new UncheckedCsvException(e); } catch (IOException e) { throw new UncheckedIOException(e); } //@formatter:on } @Override public T next() { //@formatter:off try { return CsvReader.this.next(); } catch (CsvException e) { throw new UncheckedCsvException(e); } catch (IOException e) { throw new UncheckedIOException(e); } //@formatter:on } }; } /** * Return the next element in the reader. * * @return The next element. * @throws CsvException if the csv is not properly formatted. * @throws IOException if an I/O error occurs. */ public T next() throws CsvException, IOException { if (!hasNext()) { throw new NoSuchElementException(); } state = ELEMENT_NOT_READ; T result = element; element = null; return result; } /** * Opens a file for reading, returning a {@code CsvReader}. Bytes from the file are decoded into characters using * the default JVM charset. Reading commences at the beginning of the file. * * @param file the file to open. * @param deserializer the deserializer used to convert csv lines into objects. * @param <T> the type of the objects to read. * @return A new {@code CsvReader} to read the specified file. * @throws IOException if an I/O error occurs. */ public static <T> CsvReader<T> open(File file, CsvDeserializer<T> deserializer) throws IOException { return open(file, Charset.defaultCharset(), deserializer); } /** * Opens a file for reading, returning a {@code CsvReader}. Bytes from the file are decoded into characters using * the specified charset. Reading commences at the beginning of the file. * * @param file the file to open. * @param charset the charset of the file. * @param deserializer the deserializer used to convert csv lines into objects. * @param <T> the type of the objects to read. * @return A new {@code CsvReader} to read the specified file. * @throws IOException if an I/O error occurs. */ public static <T> CsvReader<T> open(File file, Charset charset, CsvDeserializer<T> deserializer) throws IOException { return open(Files.newBufferedReader(file.toPath(), charset), deserializer); } /** * Return a new {@code CsvReader} using the specified {@link Reader} for reading. Bytes from the file are decoded * into characters using the reader's charset. Reading commences at the point specified by the reader. * * @param reader the {@link Reader} to read from. * @param deserializer the deserializer used to convert csv lines into objects. * @param <T> the type of the objects to read. * @return A new {@code CsvReader} to read the specified file. */ public static <T> CsvReader<T> open(Reader reader, CsvDeserializer<T> deserializer) { return new CsvReader<>(reader, deserializer); } private int read() throws IOException { if (next >= size) { size = reader.read(buffer, 0, buffer.length); next = 0; if (size < 0) { return -1; } } return buffer[next++]; } /** * Skip the next elements of the reader. * * @param n The number of elements to skip. * @throws CsvException if the csv is not properly formatted. * @throws IOException if an I/O error occurs. */ public void skip(int n) throws CsvException, IOException { checkClosedState(); if (state == NO_SUCH_ELEMENT) { return; } int toSkip = n; if (state == ELEMENT_READ) { element = null; state = ELEMENT_NOT_READ; if (--toSkip == 0) { return; } } byte row = START; while (true) { int nextChar = read(); int column = columnOf(nextChar); int action = ACTIONS[row][column]; if ((action & NLINE) != 0) { lines++; if (--toSkip == 0) { return; } row = START; } else { row = TRANSITIONS[row][column]; if (row == FINSH) { state = NO_SUCH_ELEMENT; return; } else if (row == ERROR) { throw new UnexpectedCharacterException(lines, nextChar); } } } } private Spliterator<T> spliterator() { int characteristics = Spliterator.IMMUTABLE | Spliterator.ORDERED; return Spliterators.spliteratorUnknownSize(iterator(), characteristics); } /** * Opens a file for reading, returning a {@link Stream}. Bytes from the file are decoded into characters using * the default JVM charset. Reading commences at the beginning of the file. * * @param file the file to open. * @param deserializer the deserializer used to convert csv lines into objects. * @param <T> the type of the objects to read. * @return A new {@link Stream} of objects read from the specified file. * @throws IOException if an I/O error occurs. */ public static <T> Stream<T> stream(File file, CsvDeserializer<T> deserializer) throws IOException { return stream(file, Charset.defaultCharset(), deserializer); } /** * Opens a file for reading, returning a {@link Stream}. Bytes from the file are decoded into characters using * the specified charset. Reading commences at the beginning of the file. * * @param file the file to open. * @param charset the charset of the file. * @param deserializer the deserializer used to convert csv lines into objects. * @param <T> the type of the objects to read. * @return A new {@link Stream} of objects read from the specified file. * @throws IOException if an I/O error occurs. */ public static <T> Stream<T> stream(File file, Charset charset, CsvDeserializer<T> deserializer) throws IOException { return stream(Files.newBufferedReader(file.toPath(), charset), deserializer); } /** * Return a new {@link Stream} of objects using the specified {@link Reader} for reading. Bytes from the file are * decoded into characters using the reader's charset. Reading commences at the point specified by the reader. * * @param reader the {@link Reader} to read from. * @param deserializer the deserializer used to convert csv lines into objects. * @param <T> the type of the objects to read. * @return A new {@code CsvReader} to read the specified file. */ public static <T> Stream<T> stream(Reader reader, CsvDeserializer<T> deserializer) { //@formatter:off CsvReader<T> csvReader = CsvReader.open(reader, deserializer); return StreamSupport.stream(csvReader.spliterator(), false) .onClose(() -> { try { csvReader.close(); } catch (Exception ignored) { } }); //@formatter:on } }
package net.nunnerycode.bukkit.mythicdrops.spawning; import com.google.common.base.Joiner; import net.nunnerycode.bukkit.libraries.ivory.factories.FancyMessageFactory; import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin; import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops; import net.nunnerycode.bukkit.mythicdrops.api.items.CustomItem; import net.nunnerycode.bukkit.mythicdrops.api.items.ItemGenerationReason; import net.nunnerycode.bukkit.mythicdrops.api.names.NameType; import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; import net.nunnerycode.bukkit.mythicdrops.events.EntityDyingEvent; import net.nunnerycode.bukkit.mythicdrops.items.CustomItemMap; import net.nunnerycode.bukkit.mythicdrops.items.MythicDropBuilder; import net.nunnerycode.bukkit.mythicdrops.names.NameMap; import net.nunnerycode.bukkit.mythicdrops.socketting.SocketGem; import net.nunnerycode.bukkit.mythicdrops.socketting.SocketItem; import net.nunnerycode.bukkit.mythicdrops.tiers.TierMap; import net.nunnerycode.bukkit.mythicdrops.utils.CustomItemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.EntityUtil; import net.nunnerycode.bukkit.mythicdrops.utils.ItemStackUtil; import net.nunnerycode.bukkit.mythicdrops.utils.SocketGemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.TierUtil; import org.apache.commons.lang.math.RandomUtils; import org.apache.commons.lang3.text.WordUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import mkremins.fanciful.IFancyMessage; public final class ItemSpawningListener implements Listener { private MythicDrops mythicDrops; public ItemSpawningListener(MythicDropsPlugin mythicDrops) { this.mythicDrops = mythicDrops; } public MythicDrops getMythicDrops() { return mythicDrops; } @EventHandler(priority = EventPriority.LOWEST) public void onCreatureSpawnEventLowest(CreatureSpawnEvent event) { if (!(event.getEntity() instanceof Monster) || event.isCancelled()) { return; } if (!mythicDrops.getConfigSettings().getEnabledWorlds().contains(event.getEntity().getWorld() .getName())) { return; } if (mythicDrops.getCreatureSpawningSettings().isGiveAllMobsNames()) { nameMobs(event.getEntity()); } if (mythicDrops.getCreatureSpawningSettings().isBlankMobSpawnEnabled()) { event.getEntity().getEquipment().clear(); if (event.getEntity() instanceof Skeleton && mythicDrops.getCreatureSpawningSettings() .isBlankMobSpawnSkeletonsSpawnWithBows()) { event.getEntity().getEquipment().setItemInHand(new ItemStack(Material.BOW, 1)); } } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { event.getEntity() .setCanPickupItems(mythicDrops.getCreatureSpawningSettings().isCanMobsPickUpEquipment()); return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { event.getEntity() .setCanPickupItems(mythicDrops.getCreatureSpawningSettings().isCanMobsPickUpEquipment()); return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM && mythicDrops.getCreatureSpawningSettings().isPreventCustom()) { event.getEntity() .setCanPickupItems(mythicDrops.getCreatureSpawningSettings().isCanMobsPickUpEquipment()); return; } if (event.getEntity().getLocation().getY() > mythicDrops.getCreatureSpawningSettings() .getSpawnHeightLimit(event.getEntity ().getWorld().getName())) { event.getEntity() .setCanPickupItems(mythicDrops.getCreatureSpawningSettings().isCanMobsPickUpEquipment()); return; } event.getEntity() .setCanPickupItems(mythicDrops.getCreatureSpawningSettings().isCanMobsPickUpEquipment()); } @EventHandler(priority = EventPriority.LOW) public void onCreatureSpawnEvent(CreatureSpawnEvent event) { if (!(event.getEntity() instanceof Monster) || event.isCancelled()) { return; } if (!mythicDrops.getConfigSettings().getEnabledWorlds().contains(event.getEntity().getWorld() .getName())) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { return; } if (mythicDrops.getCreatureSpawningSettings() .getSpawnHeightLimit(event.getEntity().getWorld().getName()) <= event .getEntity().getLocation().getY()) { return; } if (!mythicDrops.getCreatureSpawningSettings().isGiveMobsEquipment()) { return; } boolean giveName = false; double chance = mythicDrops.getCreatureSpawningSettings().getGlobalSpawnChance() * mythicDrops .getCreatureSpawningSettings().getEntityTypeChanceToSpawn(event.getEntityType()); if (mythicDrops.getCreatureSpawningSettings().isOnlyCustomItemsSpawn()) { if (mythicDrops.getCreatureSpawningSettings().isCustomItemsSpawn() && RandomUtils.nextDouble() < mythicDrops.getCreatureSpawningSettings(). getCustomItemSpawnChance() && !CustomItemMap.getInstance().isEmpty()) { for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { EntityUtil .equipEntity(event.getEntity(), CustomItemMap.getInstance().getRandomWithChance() .toItemStack()); chance *= 0.5; giveName = true; continue; } break; } } if (giveName) { nameMobs(event.getEntity()); } return; } double distanceFromWorldSpawn = event.getEntity().getLocation().distanceSquared(event .getEntity() .getWorld() .getSpawnLocation()); if (mythicDrops.getCreatureSpawningSettings().getEntityTypeChanceToSpawn(event.getEntityType()) <= 0 && mythicDrops.getCreatureSpawningSettings().getEntityTypeTiers(event.getEntityType()) .isEmpty()) { return; } for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { Tier tier = getTier("*", event.getEntity()); if (tier == null) { continue; } int attempts = 0; while (tier.getReplaceWith() != null && attempts < 20) { if (Math.pow(tier.getReplaceDistance(), 2) <= distanceFromWorldSpawn) { tier = tier.getReplaceWith(); attempts++; } else { break; } } try { ItemStack itemStack = new MythicDropBuilder().inWorld(event.getEntity().getWorld()) .useDurability(true).withTier(tier) .withItemGenerationReason(ItemGenerationReason.MONSTER_SPAWN) .build(); EntityUtil.equipEntity(event.getEntity(), itemStack); } catch (Exception e) { continue; } giveName = true; chance *= 0.5; continue; } break; } if (mythicDrops.getCreatureSpawningSettings().isCustomItemsSpawn() && RandomUtils.nextDouble() < mythicDrops .getCreatureSpawningSettings().getCustomItemSpawnChance() && !CustomItemMap.getInstance() .isEmpty()) { for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { EntityUtil.equipEntity(event.getEntity(), CustomItemMap.getInstance().getRandomWithChance() .toItemStack()); chance *= 0.5; giveName = true; continue; } break; } } if (giveName) { nameMobs(event.getEntity()); } } private Tier getTier(String tierName, LivingEntity livingEntity) { Tier tier; if (tierName.equals("*")) { tier = TierUtil.randomTierWithChance(mythicDrops.getCreatureSpawningSettings().getEntityTypeTiers (livingEntity.getType())); if (tier == null) { tier = TierUtil .randomTierWithChance(mythicDrops.getCreatureSpawningSettings().getEntityTypeTiers (livingEntity.getType())); } } else { tier = TierMap.getInstance().get(tierName.toLowerCase()); if (tier == null) { tier = TierMap.getInstance().get(tierName); } } return tier; } @EventHandler public void onEntityDeath(EntityDeathEvent event) { if (event.getEntity() instanceof Player || event.getEntity().getLastDamageCause() == null || event.getEntity().getLastDamageCause().isCancelled()) { return; } if (!mythicDrops.getConfigSettings().getEnabledWorlds().contains(event.getEntity().getWorld() .getName())) { return; } EntityDamageEvent.DamageCause damageCause = event.getEntity().getLastDamageCause().getCause(); switch (damageCause) { case CONTACT: case SUFFOCATION: case FALL: case FIRE_TICK: case MELTING: case LAVA: case DROWNING: case BLOCK_EXPLOSION: case VOID: case LIGHTNING: case SUICIDE: case STARVATION: case WITHER: case FALLING_BLOCK: case CUSTOM: return; } if (mythicDrops.getCreatureSpawningSettings().isGiveMobsEquipment()) { handleEntityDyingWithGive(event); } else { handleEntityDyingWithoutGive(event); } } private void handleEntityDyingWithGive(EntityDeathEvent event) { List<ItemStack> newDrops = new ArrayList<>(); ItemStack[] array = new ItemStack[5]; System.arraycopy(event.getEntity().getEquipment().getArmorContents(), 0, array, 0, 4); array[4] = event.getEntity().getEquipment().getItemInHand(); event.getEntity().getEquipment().setBootsDropChance(0.0F); event.getEntity().getEquipment().setLeggingsDropChance(0.0F); event.getEntity().getEquipment().setChestplateDropChance(0.0F); event.getEntity().getEquipment().setHelmetDropChance(0.0F); event.getEntity().getEquipment().setItemInHandDropChance(0.0F); for (ItemStack is : array) { if (is == null || is.getType() == Material.AIR) { continue; } if (!is.hasItemMeta()) { continue; } CustomItem ci; try { ci = CustomItemUtil.getCustomItemFromItemStack(is); } catch (NullPointerException e) { ci = null; } if (ci != null) { if (RandomUtils.nextDouble() < ci.getChanceToDropOnDeath()) { ItemStack cis = ci.toItemStack(); newDrops.add(cis); if (ci.isBroadcastOnFind() && event.getEntity().getKiller() != null) { String locale = mythicDrops.getConfigSettings().getFormattedLanguageString("command" + ".found-item-broadcast", new String[][]{ {"%receiver%", event .getEntity() .getKiller() .getName()}}); String[] messages = locale.split("%item%"); IFancyMessage fancyMessage = FancyMessageFactory.getInstance().getNewFancyMessage(); for (int i1 = 0; i1 < messages.length; i1++) { String key = messages[i1]; if (i1 < messages.length - 1) { fancyMessage.then(key).then(cis.getItemMeta().getDisplayName()) .itemTooltip(cis); } else { fancyMessage.then(key); } } for (Player player : event.getEntity().getWorld().getPlayers()) { fancyMessage.send(player); } } continue; } } Tier tier = TierUtil.getTierFromItemStack(is, TierMap.getInstance().values()); if (tier == null) { continue; } String displayName = WordUtils.capitalizeFully(Joiner.on(" ").join(is.getType().name().split("_"))); if (is.hasItemMeta() && is.getItemMeta().hasDisplayName()) { displayName = is.getItemMeta().getDisplayName(); } if (tier.isBroadcastOnFind() && event.getEntity().getKiller() != null) { String locale = mythicDrops.getConfigSettings().getFormattedLanguageString("command" + ".found-item-broadcast", new String[][]{ {"%receiver%", event .getEntity() .getKiller() .getName()}}); String[] messages = locale.split("%item%"); IFancyMessage fancyMessage = FancyMessageFactory.getInstance().getNewFancyMessage(); for (int i1 = 0; i1 < messages.length; i1++) { String key = messages[i1]; if (i1 < messages.length - 1) { fancyMessage.then(key).then(displayName).itemTooltip(is); } else { fancyMessage.then(key); } } for (Player player : event.getEntity().getWorld().getPlayers()) { fancyMessage.send(player); } } double dropChance = getTierDropChance(tier, event.getEntity().getWorld().getName()); mythicDrops.debug(Level.INFO, dropChance + " | " + tier.getName() + " | " + is.getType() + " | " + event.getEntity().getWorld().getName()); if (RandomUtils.nextDouble() < dropChance) { ItemStack newItemStack = is.getData().toItemStack(is.getAmount()); newItemStack.setItemMeta(is.getItemMeta().clone()); newItemStack.setDurability(ItemStackUtil.getDurabilityForMaterial(is.getType(), tier.getMinimumDurabilityPercentage(), tier.getMaximumDurabilityPercentage())); newDrops.add(newItemStack); } EntityDyingEvent ede = new EntityDyingEvent(event.getEntity(), array, newDrops); Bukkit.getPluginManager().callEvent(ede); Location location = event.getEntity().getEyeLocation(); for (ItemStack itemstack : ede.getEquipmentDrops()) { if (itemstack.getType() == Material.AIR) { continue; } location.getWorld().dropItemNaturally(location, itemstack); } } } private double getTierDropChance(Tier t, String worldName) { if (t.getWorldDropChanceMap().containsKey(worldName)) { return t.getWorldDropChanceMap().get(worldName); } if (t.getWorldDropChanceMap().containsKey("default")) { return t.getWorldDropChanceMap().get("default"); } return 1.0; } private void handleEntityDyingWithoutGive(EntityDeathEvent event) { List<ItemStack> newDrops = new ArrayList<>(); ItemStack[] array = new ItemStack[5]; System.arraycopy(event.getEntity().getEquipment().getArmorContents(), 0, array, 0, 4); array[4] = event.getEntity().getEquipment().getItemInHand(); double chance = mythicDrops.getCreatureSpawningSettings().getGlobalSpawnChance() * mythicDrops .getCreatureSpawningSettings() .getEntityTypeChanceToSpawn(event.getEntityType()); if (mythicDrops.getCreatureSpawningSettings().isOnlyCustomItemsSpawn()) { if (mythicDrops.getCreatureSpawningSettings().isCustomItemsSpawn() && RandomUtils.nextDouble() < mythicDrops .getCreatureSpawningSettings().getCustomItemSpawnChance() && !CustomItemMap.getInstance() .isEmpty()) { for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { newDrops.add(CustomItemMap.getInstance().getRandomWithChance().toItemStack()); chance *= 0.5; continue; } break; } } return; } if (mythicDrops.getCreatureSpawningSettings().getEntityTypeChanceToSpawn(event.getEntityType()) <= 0 || mythicDrops.getCreatureSpawningSettings().getEntityTypeTiers(event.getEntityType()) .isEmpty()) { return; } for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { Tier tier = getTier("*", event.getEntity()); if (tier == null) { continue; } try { ItemStack itemStack = new MythicDropBuilder().inWorld(event.getEntity().getWorld()).useDurability(true). withTier(tier).withItemGenerationReason(ItemGenerationReason.MONSTER_SPAWN) .build(); newDrops.add(itemStack); String displayName = WordUtils.capitalizeFully(Joiner.on(" ").join(itemStack.getType().name().split("_"))); if (itemStack.hasItemMeta()) { if (itemStack.getItemMeta().hasDisplayName()) { displayName = itemStack.getItemMeta().getDisplayName(); } } if (tier.isBroadcastOnFind() && event.getEntity().getKiller() != null) { String locale = mythicDrops.getConfigSettings().getFormattedLanguageString("command" + ".found-item-broadcast", new String[][]{ {"%receiver%", event .getEntity() .getKiller() .getName()}}); String[] messages = locale.split("%item%"); IFancyMessage fancyMessage = FancyMessageFactory.getInstance().getNewFancyMessage(); for (int i1 = 0; i1 < messages.length; i1++) { String key = messages[i1]; if (i1 < messages.length - 1) { fancyMessage.then(key).then(displayName) .itemTooltip(itemStack); } else { fancyMessage.then(key); } } for (Player player : event.getEntity().getWorld().getPlayers()) { fancyMessage.send(player); } } } catch (Exception e) { continue; } chance *= 0.5; continue; } break; } if (mythicDrops.getCreatureSpawningSettings().isCustomItemsSpawn() && RandomUtils.nextDouble() < mythicDrops .getCreatureSpawningSettings().getCustomItemSpawnChance() && !CustomItemMap.getInstance() .isEmpty()) { for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { newDrops.add(CustomItemMap.getInstance().getRandomWithChance().toItemStack()); chance *= 0.5; continue; } break; } } EntityDyingEvent ede = new EntityDyingEvent(event.getEntity(), array, newDrops); Bukkit.getPluginManager().callEvent(ede); Location location = event.getEntity().getLocation(); for (ItemStack itemstack : ede.getEquipmentDrops()) { if (itemstack.getType() == Material.AIR) { continue; } location.getWorld().dropItemNaturally(location, itemstack); } } @EventHandler public void onEntityDyingEvent(EntityDyingEvent event) { String replaceString = mythicDrops.getSockettingSettings().getSocketGemName().replace('&', '\u00A7') .replace("\u00A7\u00A7", "&").replaceAll("%(?s)(.*?)%", "").replaceAll("\\s+", " "); String[] splitString = ChatColor.stripColor(replaceString).split(" "); for (ItemStack is : event.getEquipment()) { if (is.getType() == Material.AIR) { continue; } if (!is.hasItemMeta()) { continue; } ItemMeta im = is.getItemMeta(); if (!im.hasDisplayName()) { continue; } String displayName = im.getDisplayName(); String colorlessName = ChatColor.stripColor(displayName); for (String s : splitString) { if (colorlessName.contains(s)) { colorlessName = colorlessName.replace(s, ""); } } colorlessName = colorlessName.replaceAll("\\s+", " ").trim(); SocketGem socketGem = SocketGemUtil.getSocketGemFromName(colorlessName); if (socketGem == null) { continue; } if (is.isSimilar(new SocketItem(is.getData(), socketGem))) { event.getEquipmentDrops().add(new SocketItem(is.getData(), socketGem)); } } } private void nameMobs(LivingEntity livingEntity) { if (mythicDrops.getCreatureSpawningSettings().isGiveMobsNames()) { String generalName = NameMap.getInstance().getRandom(NameType.MOB_NAME, ""); String specificName = NameMap.getInstance().getRandom(NameType.MOB_NAME, "." + livingEntity.getType()); if (specificName != null && !specificName.isEmpty()) { livingEntity.setCustomName(specificName); } else { livingEntity.setCustomName(generalName); } livingEntity.setCustomNameVisible(true); } } }
package me.pagar.model; import java.util.Collection; import java.util.Date; import javax.ws.rs.HttpMethod; import org.joda.time.DateTime; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import me.pagar.model.Transaction.PaymentMethod; import me.pagar.model.filter.QueriableFields; import me.pagar.util.JSONUtils; public class Payable extends PagarMeModel<Integer> { @Expose(serialize = false) private Integer amount; @Expose(serialize = false) private Integer fee; @Expose(serialize = false) private Integer installment; @Expose(serialize = false) private Integer transactionId; @Expose(serialize = false) private String splitRuleId; @Expose(serialize = false) private DateTime paymentDate; @Expose(serialize = false) private Status status; @Expose(serialize = false) private Type type; @Expose private String recipientId; @Expose private String anticipationFee; @Expose private String bulkAnticipationId; @Expose private Date originalPaymentDate; @Expose private PaymentMethod paymentMethod; public Payable() { super(); } public Payable find(Integer id) throws PagarMeException { final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", getClassName(), id)); final Payable other = JSONUtils.getAsObject((JsonObject) request.execute(), Payable.class); copy(other); flush(); return other; } public Collection<Payable> findCollection(final Integer totalPerPage, Integer page) throws PagarMeException { JsonArray response = super.paginate(totalPerPage, page); return JSONUtils.getAsList(response, new TypeToken<Collection<Payable>>() { }.getType()); } public Collection<Payable> findCollection(final Integer totalPerPage, Integer page, QueriableFields payableFilter) throws PagarMeException { JsonArray response = super.paginate(totalPerPage, page, payableFilter); return JSONUtils.getAsList(response, new TypeToken<Collection<Payable>>() { }.getType()); } private void copy(Payable other) { super.copy(other); this.amount = other.amount; this.anticipationFee = other.anticipationFee; this.bulkAnticipationId = other.bulkAnticipationId; this.fee = other.fee; this.installment = other.installment; this.originalPaymentDate = other.originalPaymentDate; this.paymentDate = other.paymentDate; this.paymentMethod = other.paymentMethod; this.recipientId = other.recipientId; this.splitRuleId = other.splitRuleId; this.status = other.status; this.transactionId = other.transactionId; this.type = other.type; } @Override public void setId(Integer id) { throw new UnsupportedOperationException("Not allowed."); } public Integer getAmount() { return amount; } public Integer getFee() { return fee; } public Integer getInstallment() { return installment; } public Integer getTransactionId() { return transactionId; } public String getSplitRuleId() { return splitRuleId; } @Deprecated public DateTime getPayment(){ return paymentDate; } public DateTime getPaymentDate() { return paymentDate; } public Status getStatus() { return status; } public Type getType() { return type; } public String getRecipientId() { return recipientId; } public String getAnticipationFee() { return anticipationFee; } public String getBulkAnticipationId() { return bulkAnticipationId; } public Date getOriginalPaymentDate() { return originalPaymentDate; } public PaymentMethod getPaymentMethod() { return paymentMethod; } public void setAmount(Integer amount) { this.amount = amount; } public void setFee(Integer fee) { this.fee = fee; } public void setInstallment(Integer installment) { this.installment = installment; } public void setTransactionId(Integer transactionId) { this.transactionId = transactionId; } public void setSplitRuleId(String splitRuleId) { this.splitRuleId = splitRuleId; } public void setPaymentDate(DateTime paymentDate) { this.paymentDate = paymentDate; } public void setStatus(Status status) { this.status = status; } public void setType(Type type) { this.type = type; } public void setRecipientId(String recipientId) { this.recipientId = recipientId; } public void setAnticipationFee(String anticipationFee) { this.anticipationFee = anticipationFee; } public void setBulkAnticipationId(String bulkAnticipationId) { this.bulkAnticipationId = bulkAnticipationId; } public void setOriginalPaymentDate(Date originalPaymentDate) { this.originalPaymentDate = originalPaymentDate; } public void setPaymentMethod(PaymentMethod paymentMethod) { this.paymentMethod = paymentMethod; } @Override public void setClassName(String className) { throw new UnsupportedOperationException("Not allowed."); } public enum Status { @SerializedName("paid") PAID, @SerializedName("waiting_funds") WAITING_FUNDS, @SerializedName("suspended") SUSPENDED } public enum Type { @SerializedName("chargeback_refund") CHARGEBACK_REFUND, @SerializedName("chargeback") CHARGEBACK, @SerializedName("credit") CREDIT, @SerializedName("refund") REFUND } }
package mmsort; import java.util.Comparator; public class MatSort implements ISortAlgorithm { /** * * * @param key * @param array * @param from * @param to + 1 * @param comparator * @return key */ public static final <T> int searchFowardingBinSearch(final T key, final T[] array, int from, int to, Comparator<? super T> comparator) { int skipSize = 1; int idx = from; while (idx < to) { if (comparator.compare(array[idx], key) < 0) { from = idx + 1; idx += skipSize; skipSize *= 2; } else { to = idx; break; } } int fromIdx = from; int toIdx = to; int curIdx = fromIdx + (toIdx - fromIdx) / 2; while (fromIdx < toIdx) { if (comparator.compare(key, array[curIdx]) <= 0) { // virtual code : (array[curIdx] < key) == false toIdx = curIdx; curIdx = fromIdx + (toIdx - fromIdx) / 2; continue; } else { fromIdx = curIdx + 1; curIdx = fromIdx + (toIdx - fromIdx) / 2; continue; } } return curIdx; } /** * MatSort * * @param array sort target / * @param from index of first element / * @param to index of last element (exclusive) / + 1 * @param comparator comparator of array element / * @param workArray work area / * @param workSize work area size / */ public static <T> void matSort(final T[] array, final int from, final int to, final Comparator<? super T> comparator, final T[] workArray, final int workSize) { // Sort the final block // Sort !! // array v // | Block | Block | Block | ... | Block | Block | Block | // from fromIdx to int fromIdx = to - workSize; // MasSort or No6Sort // many cases dpsSort faster, but fewer number of comparisons of MasSort. // dpsSortMasSort System.arraycopy(array, fromIdx, workArray, 0, workSize); MasSort.masSort(workArray, array, 0, workSize, fromIdx, comparator); //int depthRemain = (int)(Math.log(workSize) / Math.log(2.0)); //Dps6Sort.dpsSort(array, fromIdx, to, workArray, depthRemain, comparator); // It is repeated until the merge all the blocks merge ... by sorting the immediately preceding block of the last block. while (fromIdx > from) { // Sort the previous block (fromIdx midIdx), to temporary area // (fromIdx midIdx) // array // | Block | Block | Block | ... | Block | Block | sorted | // from fromIdx | midIdx to // temp v // | sorted | final int midIdx = fromIdx; fromIdx = fromIdx - workSize; if (fromIdx < from) fromIdx = from; // MasSort or dpsSort // many cases No6Sort faster, but fewer number of comparisons of MasSort. // dpsSortMasSort System.arraycopy(array, fromIdx, workArray, 0, midIdx - fromIdx); MasSort.masSort(array, workArray, fromIdx, midIdx, 0, comparator); //DpsSort.dpsSort(array, fromIdx, midIdx, workArray, depthRemain, comparator); //System.arraycopy(array, fromIdx, workArray, 0, midIdx - fromIdx); int idx1 = fromIdx; int idx2 = midIdx; if (comparator.compare(workArray[midIdx - fromIdx - 1], array[midIdx]) < 0) { System.arraycopy(workArray, 0, array, fromIdx, midIdx - fromIdx); continue; } // Merging the last block and that front of the block to create a new big block. This repeated until the block is one. // temp // | sorted | // array v // | Block | Block | Block | ... | Block | merging <- sorted | int idx = idx1; // Position currently being processed / while (idx1 < midIdx && idx2 < to) { final T value1 = workArray[idx1 - fromIdx]; final int toIdx = searchFowardingBinSearch(value1, array, idx2, to, comparator); if (toIdx != idx2) { // getting multi values from back block, stored to sorted area (Because back block is large) System.arraycopy(array, idx2, array, idx, toIdx - idx2); idx += (toIdx - idx2); idx2 = toIdx; } if (toIdx < to) { // getting single value from forward block, stored to sorted area array[idx] = value1; idx1++; idx++; } } // remaining temporary data to array while (idx1 < midIdx) { array[idx++] = workArray[idx1++ - fromIdx]; } } } /** * MatSort * * Saving memory version merge sort (saving memory version MasSort) * WorkSize can specify the less value the number of elements to be sorted as the maximum value. * Performance If the workSize to the same value as the number of elements to be sorted is maximized, it is substantially MasSort. * When workSize a small value the performance becomes lower, if a 1, it is substantially insert sort. * Since workSize If too small obviously affect the performance, rather than a fixed value, is better to specify the ratio of the number of elements, such as 1 / N it seems to be good. * The logical workSize ought larger it is to improve performance, but was also seen 1/2 to fast become the case than normal MasSort be about 1/10. * * * ( MasSort) * workSize * workSize MasSort * workSize1 * workSize1/N * workSize1/21/10 MasSort * * @param array sort target / * @param from index of first element / * @param to index of last element (exclusive) / + 1 * @param comparator comparator of array element / * @param workSize work area size / */ public static <T> void matSort(final T[] array, final int from, final int to, final Comparator<? super T> comparator, int workSize) { int range = (to - from); if (range <= 1) return ; if (workSize == 0) workSize = (range + 9) / 10; // round up / if (workSize > range) workSize = range; else if (workSize == range) ; // masSort else if (workSize > (range + 1) / 2) workSize = (range + 1) / 2; else if (workSize < 1) workSize = 1; @SuppressWarnings("unchecked") final T[] workArray = (T[])new Object[workSize]; matSort(array, from, to, comparator, workArray, workSize); } @Override public <T> void sort(final T[] array, final int from, final int to, final Comparator<? super T> comparator) { matSort(array, from, to, comparator, 0); } @Override public boolean isStable() { return true; } @Override public String getName() { return "MatSort"; } }
package net.sourceforge.pebble.event.blogentry; import net.sourceforge.pebble.api.decorator.ContentDecoratorContext; import net.sourceforge.pebble.api.event.blogentry.BlogEntryEvent; import net.sourceforge.pebble.domain.Blog; import net.sourceforge.pebble.domain.BlogEntry; import net.sourceforge.pebble.util.MailUtils; import javax.mail.Session; import java.text.SimpleDateFormat; import java.util.List; /** * Sends an e-mail notification to e-mail subscribers when new blog entries * are added. * * @author Simon Brown */ public class EmailSubscriptionListener extends BlogEntryListenerSupport { /** a token to be replaced when sending e-mails */ private static final String EMAIL_ADDRESS_TOKEN = "EMAIL_ADDRESS"; /** * Called when a blog entry has been published. * * @param event a BlogEntryEvent instance */ public void blogEntryPublished(BlogEntryEvent event) { BlogEntry blogEntry = event.getBlogEntry(); sendNotification((BlogEntry)blogEntry.clone()); } private void sendNotification(BlogEntry blogEntry) { Blog blog = blogEntry.getBlog(); // first of all decorate the blog entry, as if it was being rendered // via a HTML page or XML feed ContentDecoratorContext context = new ContentDecoratorContext(); context.setView(ContentDecoratorContext.DETAIL_VIEW); context.setMedia(ContentDecoratorContext.EMAIL); blog.getContentDecoratorChain().decorate(context, blogEntry); SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z"); sdf.setTimeZone(blog.getTimeZone()); String subject = MailUtils.getBlogEntryPrefix(blog) + " " + blogEntry.getTitle(); String message = "<a href=\"" + blogEntry.getLocalPermalink() + "\">Blog entry</a> posted by " + (blogEntry.getUser() != null ? blogEntry.getUser().getName() : blogEntry.getAuthor()) + " on " + sdf.format(blogEntry.getDate()); message += "\n<br>"; if (blogEntry.getExcerpt() != null && blogEntry.getExcerpt().trim().length() > 0) { message += blogEntry.getExcerpt(); } else { message += blogEntry.getBody(); } message += "\n<br>"; message += "<a href=\"" + blogEntry.getLocalPermalink() + "\">Permalink</a>"; message += " | "; message += "<a href=\"" + blog.getUrl() + "unsubscribe.action?email=" + EMAIL_ADDRESS_TOKEN + "\">Opt-out</a>"; List<String> to = blog.getEmailSubscriptionList().getEmailAddresses(); // now send personalized e-mails to the blog owner and everybody // that left a comment specifying their e-mail address try { Session session = MailUtils.createSession(); for (String emailAddress : to) { // customize the opt-out link and send the message MailUtils.sendMail(session, blog, emailAddress, subject, message.replaceAll(EMAIL_ADDRESS_TOKEN, emailAddress)); } } catch (Exception e) { e.printStackTrace(); } catch (NoClassDefFoundError e) { // most likely: JavaMail is not in classpath e.printStackTrace(); } } }
package net.runelite.deob; import net.runelite.deob.deobfuscators.FieldInliner; import net.runelite.deob.deobfuscators.FieldMover; import net.runelite.deob.deobfuscators.MethodMover; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import net.runelite.deob.deobfuscators.ConstantParameter; import net.runelite.deob.deobfuscators.IllegalStateExceptions; import net.runelite.deob.deobfuscators.MethodInliner; import net.runelite.deob.deobfuscators.RenameUnique; import net.runelite.deob.deobfuscators.RuntimeExceptions; import net.runelite.deob.deobfuscators.UnreachedCode; import net.runelite.deob.deobfuscators.UnusedClass; import net.runelite.deob.deobfuscators.UnusedFields; import net.runelite.deob.deobfuscators.UnusedMethods; import net.runelite.deob.deobfuscators.UnusedParameters; import net.runelite.deob.deobfuscators.arithmetic.ModArith; import net.runelite.deob.execution.Execution; //move static methods //move static fields //math deob //remove dead classes //inline constant fields //compare old and new public class Deob { public static void main(String[] args) throws IOException { long start = System.currentTimeMillis(); ClassGroup group = loadJar(args[0]); // run(group, new RenameUnique()); // // remove except RuntimeException // run(group, new RuntimeExceptions()); // // remove unused methods // run(group, new UnusedMethods()); // run(group, new UnreachedCode()); // // remove constant logically dead parameters // run(group, new ConstantParameter()); // // remove unhit blocks // run(group, new UnreachedCode()); // // remove unused parameters // run(group, new UnusedParameters()); // // remove jump obfuscation // //new Jumps().run(group); // // remove unused fields // run(group, new UnusedFields()); // // remove unused methods, again? // run(group, new UnusedMethods()); // run(group, new MethodInliner()); // run(group, new MethodMover()); // run(group, new FieldInliner()); // // XXX this is broken because when moving clinit around, some fields can depend on other fields // // (like multianewarray) // //new FieldMover().run(group); // run(group, new UnusedClass()); new ModArith().run(group); saveJar(group, args[1]); long end = System.currentTimeMillis(); System.out.println("Done in " + ((end - start) / 1000L) + "s"); } public static boolean isObfuscated(String name) { return name.length() <= 2 || name.startsWith("method") || name.startsWith("vmethod") || name.startsWith("field") || name.startsWith("class"); } private static ClassGroup loadJar(String jarfile) throws IOException { ClassGroup group = new ClassGroup(); JarFile jar = new JarFile(jarfile); for (Enumeration<JarEntry> it = jar.entries(); it.hasMoreElements();) { JarEntry entry = it.nextElement(); if (!entry.getName().endsWith(".class")) continue; InputStream is = jar.getInputStream(entry); group.addClass(entry.getName(), new DataInputStream(is)); } jar.close(); return group; } private static void saveJar(ClassGroup group, String jarfile) throws IOException { JarOutputStream jout = new JarOutputStream(new FileOutputStream(jarfile), new Manifest()); for (ClassFile cf : group.getClasses()) { JarEntry entry = new JarEntry(cf.getName() + ".class"); jout.putNextEntry(entry); ByteArrayOutputStream bout = new ByteArrayOutputStream(); cf.write(new DataOutputStream(bout)); jout.write(bout.toByteArray()); jout.closeEntry(); } jout.close(); } private static void run(ClassGroup group, Deobfuscator deob) { long bstart, bdur; bstart = System.currentTimeMillis(); deob.run(group); bdur = System.currentTimeMillis() - bstart; System.out.println(deob.getClass().getName() + " took " + (bdur / 1000L) + " seconds"); // check code is still correct Execution execution = new Execution(group); execution.populateInitialMethods(); execution.run(); } }
package no.uio.ifi.trackfind.backend.data.providers; import alexh.weak.Dynamic; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.gson.Gson; import com.vaadin.data.provider.AbstractBackEndHierarchicalDataProvider; import com.vaadin.data.provider.HierarchicalQuery; import com.vaadin.server.SerializablePredicate; import lombok.extern.slf4j.Slf4j; import no.uio.ifi.trackfind.backend.configuration.TrackFindProperties; import no.uio.ifi.trackfind.backend.dao.*; import no.uio.ifi.trackfind.backend.data.TreeNode; import no.uio.ifi.trackfind.backend.events.DataReloadEvent; import no.uio.ifi.trackfind.backend.operations.Operation; import no.uio.ifi.trackfind.backend.repositories.DatasetRepository; import no.uio.ifi.trackfind.backend.repositories.MappingRepository; import no.uio.ifi.trackfind.backend.repositories.SourceRepository; import no.uio.ifi.trackfind.backend.repositories.StandardRepository; import no.uio.ifi.trackfind.backend.scripting.ScriptingEngine; import no.uio.ifi.trackfind.backend.services.CacheService; import no.uio.ifi.trackfind.backend.services.MetamodelService; import no.uio.ifi.trackfind.frontend.filters.TreeFilter; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.CacheEvict; import org.springframework.context.ApplicationEventPublisher; import org.springframework.jdbc.core.JdbcTemplate; import javax.annotation.PostConstruct; import javax.transaction.Transactional; import java.sql.*; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Abstract class for all data providers. * Implements some common logic like getting metamodel, searching, etc. * * @author Dmytro Titov */ @Slf4j public abstract class AbstractDataProvider extends AbstractBackEndHierarchicalDataProvider<TreeNode, SerializablePredicate<TreeNode>> implements DataProvider, Comparable<DataProvider> { protected String jdbcUrl; protected TrackFindProperties properties; protected ApplicationEventPublisher applicationEventPublisher; protected CacheService cacheService; protected JdbcTemplate jdbcTemplate; protected SourceRepository sourceRepository; protected StandardRepository standardRepository; protected DatasetRepository datasetRepository; protected MappingRepository mappingRepository; protected ExecutorService executorService; protected MetamodelService metamodelService; protected Gson gson; protected Collection<ScriptingEngine> scriptingEngines; protected Connection connection; private LoadingCache<Boolean, Collection<String>> arrayOfObjectsAttributesCache = Caffeine.newBuilder() .build(key -> jdbcTemplate.queryForList( "SELECT DISTINCT attribute FROM " + (key ? "source" : "standard") + "_array_of_objects WHERE repository = ?", String.class, getName())); private LoadingCache<Boolean, Multimap<String, String>> flatMetamodelCache = Caffeine.newBuilder() .build(key -> { Multimap<String, String> metamodel = HashMultimap.create(); List<Map<String, Object>> attributeValuePairs = jdbcTemplate.queryForList( "SELECT attribute, value FROM " + (key ? "source" : "standard") + "_metamodel WHERE repository = ?", getName()); for (Map attributeValuePair : attributeValuePairs) { String attribute = String.valueOf(attributeValuePair.get("attribute")); String value = String.valueOf(attributeValuePair.get("value")); metamodel.put(attribute, value); } return metamodel; }); private LoadingCache<Boolean, Map<String, Object>> treeMetamodelCache = Caffeine.newBuilder() .build(key -> { Map<String, Object> result = new HashMap<>(); Multimap<String, String> metamodelFlat = getMetamodelFlat(key); for (Map.Entry<String, Collection<String>> entry : metamodelFlat.asMap().entrySet()) { String attribute = entry.getKey(); Map<String, Object> metamodel = result; String[] path = attribute.split(properties.getLevelsSeparator()); for (int i = 0; i < path.length - 1; i++) { String part = path[i]; metamodel = (Map<String, Object>) metamodel.computeIfAbsent(part, k -> new HashMap<String, Object>()); } String valuesKey = path[path.length - 1]; metamodel.put(valuesKey, entry.getValue()); } return result; }); @PostConstruct protected void init() throws SQLException { try { if (datasetRepository.countByRepository(getName()) == 0) { crawlRemoteRepository(); } jdbcTemplate.execute(String.format(Queries.METAMODEL_VIEW, "source", "curated", properties.getLevelsSeparator(), properties.getLevelsSeparator())); jdbcTemplate.execute(String.format(Queries.ARRAY_OF_OBJECTS_VIEW, "source", "curated", properties.getLevelsSeparator(), properties.getLevelsSeparator())); jdbcTemplate.execute(String.format(Queries.METAMODEL_VIEW, "standard", "standard", properties.getLevelsSeparator(), properties.getLevelsSeparator())); jdbcTemplate.execute(String.format(Queries.ARRAY_OF_OBJECTS_VIEW, "standard", "standard", properties.getLevelsSeparator(), properties.getLevelsSeparator())); Integer count = jdbcTemplate.queryForObject(Queries.CHECK_SEARCH_USER_EXISTS, Integer.TYPE); if (count == 0) { jdbcTemplate.execute(Queries.CREATE_SEARCH_USER); } connection = DriverManager.getConnection(jdbcUrl, "search", "search"); } catch (Exception e) { log.error(e.getMessage(), e); throw e; } } /** * {@inheritDoc} */ @Override public String getName() { return getClass().getSimpleName().replace("DataProvider", ""); } /** * Fetches data from the repository. * * @throws Exception in case of some problems. */ protected abstract void fetchData() throws Exception; /** * {@inheritDoc} */ @CacheEvict(cacheNames = { "metamodel-attributes", "metamodel-subattributes", "metamodel-values" }, allEntries = true) @Transactional @Override public synchronized void crawlRemoteRepository() { log.info("Fetching data using " + getName()); try { fetchData(); applicationEventPublisher.publishEvent(new DataReloadEvent(getName(), Operation.CRAWLING)); } catch (Exception e) { log.error(e.getMessage(), e); return; } log.info("Success!"); } /** * Saves datasets to the database. * * @param datasets Datasets to save. */ protected void save(Collection<Map> datasets) { sourceRepository.saveAll(datasets.parallelStream().map(map -> { Source source = new Source(); source.setRepository(getName()); source.setContent(gson.toJson(map)); source.setRawVersion(0L); // TODO: set proper version source.setCuratedVersion(0L); // TODO: set proper version return source; }).collect(Collectors.toList())); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @CacheEvict(cacheNames = { "metamodel-attributes", "metamodel-subattributes", "metamodel-values" }, allEntries = true) @Transactional @Override public synchronized void applyMappings() { log.info("Applying mappings for " + getName()); Collection<Mapping> mappings = mappingRepository.findByRepository(getName()); Collection<Mapping> staticMappings = mappings.stream().filter(Mapping::isStaticMapping).collect(Collectors.toSet()); Optional<Mapping> dynamicMappingOptional = mappings.stream().filter(m -> !m.isStaticMapping()).findAny(); Collection<Source> sources = sourceRepository.findByRepositoryLatest(getName()); Collection<Standard> standards = new HashSet<>(); ScriptingEngine scriptingEngine = scriptingEngines.stream().filter(se -> properties.getScriptingLanguage().equals(se.getLanguage())).findAny().orElseThrow(RuntimeException::new); try { for (Source source : sources) { Map<String, Object> rawMap = gson.fromJson(source.getContent(), Map.class); Map<String, Object> standardMap = new HashMap<>(); if (dynamicMappingOptional.isPresent()) { Mapping mapping = dynamicMappingOptional.get(); standardMap = gson.fromJson(scriptingEngine.execute(mapping.getFrom(), source.getContent()), Map.class); } for (Mapping mapping : staticMappings) { Collection<String> values; Dynamic dynamicValues = Dynamic.from(rawMap).get(mapping.getFrom(), properties.getLevelsSeparator()); if (dynamicValues.isPresent()) { if (dynamicValues.isList()) { values = dynamicValues.asList(); } else { values = Collections.singletonList(dynamicValues.asString()); } } else { values = Collections.emptyList(); } String[] path = mapping.getTo().split(properties.getLevelsSeparator()); Map<String, Object> nestedMap = standardMap; for (int i = 0; i < path.length - 1; i++) { nestedMap = (Map<String, Object>) nestedMap.computeIfAbsent(path[i], k -> new HashMap<String, Object>()); } if (CollectionUtils.size(values) == 1) { nestedMap.put(path[path.length - 1], values.iterator().next()); } else { nestedMap.put(path[path.length - 1], values); } } Standard standard = new Standard(); standard.setId(source.getId()); standard.setContent(gson.toJson(standardMap)); standard.setRawVersion(source.getRawVersion()); standard.setCuratedVersion(source.getCuratedVersion()); standard.setStandardVersion(0L); standardRepository.findByIdLatest(standard.getId()).ifPresent(s -> standard.setStandardVersion(s.getStandardVersion() + 1)); standards.add(standard); } standardRepository.saveAll(standards); applicationEventPublisher.publishEvent(new DataReloadEvent(getName(), Operation.MAPPING)); } catch (Exception e) { log.error(e.getMessage(), e); return; } log.info("Success!"); } /** * {@inheritDoc} */ @Override public synchronized void resetCaches() { arrayOfObjectsAttributesCache.invalidateAll(); treeMetamodelCache.invalidateAll(); flatMetamodelCache.invalidateAll(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public Map<String, Object> getMetamodelTree(boolean raw) { return treeMetamodelCache.get(raw); } /** * {@inheritDoc} */ @Override public Multimap<String, String> getMetamodelFlat(boolean raw) { return flatMetamodelCache.get(raw); } /** * {@inheritDoc} */ @Override public Collection<Dataset> search(String query, int limit) { try { limit = limit == 0 ? Integer.MAX_VALUE : limit; Map<String, String> joinTerms = new HashMap<>(); int size = joinTerms.size(); while (true) { query = processQuery(query, joinTerms); if (size == joinTerms.size()) { break; } size = joinTerms.size(); } String joinTermsConcatenated = joinTerms .entrySet() .stream() .map(e -> String.format("jsonb_array_elements(%s) %s", e.getKey().substring(0, e.getKey().length() - properties.getLevelsSeparator().length() - 1), e.getValue() )) .collect(Collectors.joining(", ")); if (StringUtils.isNotEmpty(joinTermsConcatenated)) { joinTermsConcatenated = ", " + joinTermsConcatenated; } String rawQuery = String.format("SELECT *\n" + "FROM latest_datasets%s\n" + "WHERE repository = '%s'\n" + " AND (%s)\n" + "ORDER BY id ASC\n" + "LIMIT %s", joinTermsConcatenated, getName(), query, limit); rawQuery = rawQuery.replaceAll("\\?", "\\?\\?"); PreparedStatement preparedStatement = connection.prepareStatement(rawQuery); ResultSet resultSet = preparedStatement.executeQuery(); Collection<Dataset> result = new ArrayList<>(); while (resultSet.next()) { Dataset dataset = new Dataset(); dataset.setId(resultSet.getLong("id")); dataset.setRepository(resultSet.getString("repository")); dataset.setCuratedContent(resultSet.getString("curated_content")); dataset.setStandardContent(resultSet.getString("standard_content")); dataset.setFairContent(resultSet.getString("fair_content")); dataset.setVersion(resultSet.getString("version")); result.add(dataset); } return result; } catch (Exception e) { log.error(e.getMessage(), e); return Collections.emptySet(); } } protected String processQuery(String query, Map<String, String> allJoinTerms) { Map<String, String> joinTerms = getJoinTerms(query, allJoinTerms); for (Map.Entry<String, String> joinTerm : joinTerms.entrySet()) { query = query.replaceAll(Pattern.quote(joinTerm.getKey()), joinTerm.getValue() + ".value"); } return query; } protected Map<String, String> getJoinTerms(String query, Map<String, String> allJoinTerms) { Collection<String> joinTerms = new HashSet<>(); String separator = properties.getLevelsSeparator(); String end = separator + "*"; for (String start : Arrays.asList( "curated_content" + separator, "standard_content" + separator, "joinTerm\\d+.value" + separator )) { String regexString = start + "(.*?)" + Pattern.quote(end); Pattern pattern = Pattern.compile(regexString, Pattern.DOTALL); Matcher matcher = pattern.matcher(query); while (matcher.find()) { joinTerms.add(matcher.group()); } } Map<String, String> substitution = new HashMap<>(); int i = allJoinTerms.size(); for (String joinTerm : joinTerms) { substitution.put(joinTerm, "joinTerm" + i++); } allJoinTerms.putAll(substitution); return substitution; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public Dataset fetch(Long datasetId, String version) { return version == null ? datasetRepository.findByIdLatest(datasetId) : datasetRepository.findByIdAndVersion(datasetId, version); } @Override protected Stream<TreeNode> fetchChildrenFromBackEnd(HierarchicalQuery<TreeNode, SerializablePredicate<TreeNode>> query) { Optional<SerializablePredicate<TreeNode>> filter = query.getFilter(); boolean raw = false; if (filter.isPresent()) { TreeFilter treeFilter = (TreeFilter) filter.get(); raw = treeFilter.isRaw(); } Map<String, Object> metamodelTree = getMetamodelTree(raw); Optional<TreeNode> parentOptional = query.getParentOptional(); if (!parentOptional.isPresent()) { boolean finalRaw1 = raw; Stream<TreeNode> treeNodeStream = metamodelTree.keySet().parallelStream().map(c -> { TreeNode treeNode = new TreeNode(); treeNode.setValue(c); treeNode.setParent(null); treeNode.setSeparator(properties.getLevelsSeparator()); treeNode.setLevel(0); treeNode.setHasValues(CollectionUtils.isNotEmpty(metamodelService.getValues(getName(), treeNode.getPath(), "", finalRaw1))); Collection<String> grandChildren = new ArrayList<>(); grandChildren.addAll(metamodelService.getValues(getName(), treeNode.getPath(), "", finalRaw1)); grandChildren.addAll(metamodelService.getSubAttributes(getName(), treeNode.getPath(), "", finalRaw1)); treeNode.setChildren(grandChildren); treeNode.setAttribute(true); treeNode.setArray(arrayOfObjectsAttributesCache.get(finalRaw1).contains(treeNode.getPath())); return treeNode; }).sorted(); return filter.isPresent() ? treeNodeStream.filter(filter.get()) : treeNodeStream; } else { TreeNode parent = parentOptional.get(); if (!parent.isAttribute()) { return Stream.empty(); } Collection<String> children = new ArrayList<>(); children.addAll(metamodelService.getValues(getName(), parent.getPath(), "", raw)); children.addAll(metamodelService.getSubAttributes(getName(), parent.getPath(), "", raw)); boolean finalRaw2 = raw; Stream<TreeNode> treeNodeStream = children.parallelStream().map(c -> { TreeNode treeNode = new TreeNode(); treeNode.setValue(c); treeNode.setParent(parent); treeNode.setSeparator(properties.getLevelsSeparator()); treeNode.setLevel(parent.getLevel() + 1); treeNode.setHasValues(CollectionUtils.isNotEmpty(metamodelService.getValues(getName(), treeNode.getPath(), "", finalRaw2))); Collection<String> grandChildren = new ArrayList<>(); grandChildren.addAll(metamodelService.getValues(getName(), treeNode.getPath(), "", finalRaw2)); grandChildren.addAll(metamodelService.getSubAttributes(getName(), treeNode.getPath(), "", finalRaw2)); treeNode.setChildren(grandChildren); treeNode.setAttribute(CollectionUtils.isNotEmpty(grandChildren)); treeNode.setArray(arrayOfObjectsAttributesCache.get(finalRaw2).contains(treeNode.getPath())); return treeNode; }).sorted(); return filter.isPresent() ? treeNodeStream.filter(filter.get()) : treeNodeStream; } } @Override public int getChildCount(HierarchicalQuery<TreeNode, SerializablePredicate<TreeNode>> query) { return (int) fetchChildrenFromBackEnd(query).count(); } @Override public boolean hasChildren(TreeNode item) { return item.isAttribute(); } /** * {@inheritDoc} */ @Override public int compareTo(DataProvider that) { return this.getName().compareTo(that.getName()); } @Value("${spring.datasource.url}") public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } @Autowired public void setProperties(TrackFindProperties properties) { this.properties = properties; } @Autowired public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } @Autowired public void setCacheService(CacheService cacheService) { this.cacheService = cacheService; } @Autowired public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Autowired public void setSourceRepository(SourceRepository sourceRepository) { this.sourceRepository = sourceRepository; } @Autowired public void setStandardRepository(StandardRepository standardRepository) { this.standardRepository = standardRepository; } @Autowired public void setDatasetRepository(DatasetRepository datasetRepository) { this.datasetRepository = datasetRepository; } @Autowired public void setMappingRepository(MappingRepository mappingRepository) { this.mappingRepository = mappingRepository; } @Autowired public void setExecutorService(ExecutorService workStealingPool) { this.executorService = workStealingPool; } @Autowired public void setMetamodelService(MetamodelService metamodelService) { this.metamodelService = metamodelService; } @Autowired public void setGson(Gson gson) { this.gson = gson; } @Autowired public void setScriptingEngines(Collection<ScriptingEngine> scriptingEngines) { this.scriptingEngines = scriptingEngines; } }
package org.javacs; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskListener; import com.sun.tools.javac.api.JavacTrees; import com.sun.tools.javac.api.MultiTaskListener; import com.sun.tools.javac.comp.*; import com.sun.tools.javac.file.JavacFileManager; import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.parser.FuzzyParserFactory; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.TreeScanner; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Name; import com.sun.tools.javac.util.Options; import javax.tools.*; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.time.Instant; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.logging.Level; import java.util.logging.Logger; /** * Maintains a reference to a Java compiler, * and several of its internal data structures, * which we need to fiddle with to get incremental compilation * and extract the diagnostic information we want. */ public class JavacHolder { private static final Logger LOG = Logger.getLogger("main"); private final Set<Path> classPath; private final Set<Path> sourcePath; private final Path outputDirectory; // javac places all of its internal state into this Context object, // which is basically a Map<String, Object> public final Context context = new Context(); // Error reporting initially goes nowhere // When we want to report errors back to VS Code, we'll replace this with something else private DiagnosticListener<JavaFileObject> errorsDelegate = diagnostic -> {}; // javac isn't friendly to swapping out the error-reporting DiagnosticListener, // so we install this intermediate DiagnosticListener, which forwards to errorsDelegate private final DiagnosticListener<JavaFileObject> errors = diagnostic -> { errorsDelegate.report(diagnostic); }; { context.put(DiagnosticListener.class, errors); } // Sets command-line options private final Options options = Options.instance(context); { // You would think we could do -Xlint:all, // but some lints trigger fatal errors in the presence of parse errors options.put("-Xlint:cast", ""); options.put("-Xlint:deprecation", ""); options.put("-Xlint:empty", ""); options.put("-Xlint:fallthrough", ""); options.put("-Xlint:finally", ""); options.put("-Xlint:path", ""); options.put("-Xlint:unchecked", ""); options.put("-Xlint:varargs", ""); options.put("-Xlint:static", ""); } // IncrementalLog registers itself in context and pre-empts the normal Log from being created private final IncrementalLog log = new IncrementalLog(context); public final JavacFileManager fileManager = new JavacFileManager(context, true, null); private final ForgivingAttr attr = ForgivingAttr.instance(context); private final Check check = Check.instance(context); // FuzzyParserFactory registers itself in context and pre-empts the normal ParserFactory from being created private final FuzzyParserFactory parserFactory = FuzzyParserFactory.instance(context); public final JavaCompiler compiler = JavaCompiler.instance(context); { // We're going to use the javadoc comments compiler.keepComments = true; } private final Todo todo = Todo.instance(context); private final JavacTrees trees = JavacTrees.instance(context); // TreeScanner tasks we want to perform before or after compilation stages // We'll use these scanners to implement features like go-to-definition private final Map<TaskEvent.Kind, List<TreeScanner>> beforeTask = new HashMap<>(), afterTask = new HashMap<>(); public final ClassIndex index = new ClassIndex(context); public JavacHolder(Set<Path> classPath, Set<Path> sourcePath, Path outputDirectory) { this.classPath = classPath; this.sourcePath = sourcePath; this.outputDirectory = outputDirectory; options.put("-classpath", Joiner.on(":").join(classPath)); options.put("-sourcepath", Joiner.on(":").join(sourcePath)); options.put("-d", outputDirectory.toString()); MultiTaskListener.instance(context).add(new TaskListener() { @Override public void started(TaskEvent e) { LOG.fine("started " + e); JCTree.JCCompilationUnit unit = (JCTree.JCCompilationUnit) e.getCompilationUnit(); List<TreeScanner> todo = beforeTask.getOrDefault(e.getKind(), Collections.emptyList()); for (TreeScanner visitor : todo) { unit.accept(visitor); } } @Override public void finished(TaskEvent e) { LOG.fine("finished " + e); JCTree.JCCompilationUnit unit = (JCTree.JCCompilationUnit) e.getCompilationUnit(); if (e.getKind() == TaskEvent.Kind.ANALYZE) unit.accept(index); List<TreeScanner> todo = afterTask.getOrDefault(e.getKind(), Collections.emptyList()); for (TreeScanner visitor : todo) { unit.accept(visitor); } } }); ensureOutputDirectory(outputDirectory); clearOutputDirectory(outputDirectory); } private void ensureOutputDirectory(Path dir) { if (!Files.exists(dir)) { try { Files.createDirectories(dir); } catch (IOException e) { throw ShowMessageException.error("Error created output directory " + dir, null); } } else if (!Files.isDirectory(dir)) throw ShowMessageException.error("Output directory " + dir + " is not a directory", null); } private static void clearOutputDirectory(Path file) { try { if (file.getFileName().toString().endsWith(".class")) { LOG.info("Invalidate " + file); Files.setLastModifiedTime(file, FileTime.from(Instant.EPOCH)); } else if (Files.isDirectory(file)) Files.list(file).forEach(JavacHolder::clearOutputDirectory); } catch (IOException e) { LOG.log(Level.SEVERE, e.getMessage(), e); } } /** * After the parse phase of compilation, * scan the source trees with these scanners. * Replaces any existing after-parse scanners. */ public void afterParse(TreeScanner... scan) { afterTask.put(TaskEvent.Kind.PARSE, ImmutableList.copyOf(scan)); } /** * After the analysis phase of compilation, * scan the source trees with these scanners. * Replaces any existing after-analyze scanners. */ public void afterAnalyze(TreeScanner... scan) { afterTask.put(TaskEvent.Kind.ANALYZE, ImmutableList.copyOf(scan)); } /** * Send all errors to callback, replacing any existing callback */ public void onError(DiagnosticListener<JavaFileObject> callback) { errorsDelegate = callback; } /** * Compile the indicated source file, and its dependencies if they have been modified. */ public JCTree.JCCompilationUnit parse(JavaFileObject source) { clear(source); JCTree.JCCompilationUnit result = compiler.parse(source); return result; } public void compile(Collection<JCTree.JCCompilationUnit> parsed) { compiler.processAnnotations(compiler.enterTrees(com.sun.tools.javac.util.List.from(parsed))); while (!todo.isEmpty()) { // We don't do the desugar or generate phases, because they remove method bodies and methods Env<AttrContext> next = todo.remove(); Env<AttrContext> attributedTree = compiler.attribute(next); Queue<Env<AttrContext>> analyzedTree = compiler.flow(attributedTree); } } /** * Compile a source tree produced by this.parse */ // TODO inline public void compile(JCTree.JCCompilationUnit source) { compile(Collections.singleton(source)); } /** * Remove source file from caches in the parse stage */ private void clear(JavaFileObject source) { // Forget about this file log.clear(source); // javac's flow stage will stop early if there are errors log.nerrors = 0; log.nwarnings = 0; // Remove all cached classes that came from this files List<Name> remove = new ArrayList<>(); check.compiled.forEach((name, symbol) -> { if (symbol.sourcefile.getName().equals(source.getName())) remove.add(name); }); remove.forEach(check.compiled::remove); } }
package org.jpmml.sklearn; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import org.dmg.pmml.Extension; import org.dmg.pmml.MiningBuildTask; import org.dmg.pmml.PMML; import org.jpmml.model.MetroJAXBUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sklearn.Estimator; import sklearn.EstimatorUtil; import sklearn_pandas.DataFrameMapper; public class Main { @Parameter ( names = {"--pkl-input", "--pkl-estimator-input"}, description = "Estimator pickle input file", required = true ) private File estimatorInput = null; @Parameter ( names = "--repr-estimator", description = "Estimator string representation", hidden = true ) private String estimatorRepr = null; @Parameter ( names = "--help", description = "Show the list of configuration options and exit", help = true ) private boolean help = false; @Parameter ( names = "--pkl-mapper-input", description = "DataFrameMapper pickle input file", required = false ) private File mapperInput = null; @Parameter ( names = "--repr-mapper", description = "DataFrameMapper string representation", hidden = true ) private String mapperRepr = null; @Parameter ( names = "--pmml-output", description = "PMML output file", required = true ) private File output = null; static public void main(String... args) throws Exception { Main main = new Main(); JCommander commander = new JCommander(main); commander.setProgramName(Main.class.getName()); try { commander.parse(args); } catch(ParameterException pe){ StringBuilder sb = new StringBuilder(); sb.append(pe.toString()); sb.append("\n"); commander.usage(sb); System.err.println(sb.toString()); System.exit(-1); } if(main.help){ StringBuilder sb = new StringBuilder(); commander.usage(sb); System.out.println(sb.toString()); System.exit(0); } main.run(); } public void run() throws Exception { PMML pmml; FeatureMapper featureMapper = new FeatureMapper(); Map<String, String> reprs = new LinkedHashMap<>(); if(this.mapperInput != null){ try(Storage storage = PickleUtil.createStorage(this.mapperInput)){ Object object; try { logger.info("Parsing DataFrameMapper PKL.."); long start = System.currentTimeMillis(); object = PickleUtil.unpickle(storage); long end = System.currentTimeMillis(); logger.info("Parsed DataFrameMapper PKL in {} ms.", (end - start)); } catch(Exception e){ logger.error("Failed to parse DataFrameMapper PKL", e); throw e; } if(!(object instanceof DataFrameMapper)){ throw new IllegalArgumentException("The mapper object (" + ClassDictUtil.formatClass(object) + ") is not a DataFrameMapper"); } DataFrameMapper mapper = (DataFrameMapper)object; try { logger.info("Converting DataFrameMapper.."); long start = System.currentTimeMillis(); mapper.encodeFeatures(featureMapper); long end = System.currentTimeMillis(); logger.info("Converted DataFrameMapper in {} ms.", (end - start)); } catch(Exception e){ logger.error("Failed to convert DataFrameMapper", e); throw e; } } if(this.mapperRepr != null){ reprs.put("mapper", this.mapperRepr); } } try(Storage storage = PickleUtil.createStorage(this.estimatorInput)){ Object object; try { logger.info("Parsing Estimator PKL.."); long start = System.currentTimeMillis(); object = PickleUtil.unpickle(storage); long end = System.currentTimeMillis(); logger.info("Parsed Estimator PKL in {} ms.", (end - start)); } catch(Exception e){ logger.error("Failed to parse Estimator PKL", e); throw e; } if(!(object instanceof Estimator)){ throw new IllegalArgumentException("The estimator object (" + ClassDictUtil.formatClass(object) + ") is not an Estimator or is not a supported Estimator subclass"); } Estimator estimator = (Estimator)object; try { logger.info("Converting Estimator.."); long start = System.currentTimeMillis(); pmml = EstimatorUtil.encodePMML(estimator, featureMapper); long end = System.currentTimeMillis(); logger.info("Converted Estimator in {} ms.", (end - start)); } catch(Exception e){ logger.error("Failed to convert Estimator", e); throw e; } } if(this.estimatorRepr != null){ reprs.put("estimator", this.estimatorRepr); } Collection<Map.Entry<String, String>> entries = reprs.entrySet(); for(Map.Entry<String, String> entry : entries){ addObjectRepr(pmml, entry.getKey(), entry.getValue()); } try(OutputStream os = new FileOutputStream(this.output)){ logger.info("Marshalling PMML.."); long start = System.currentTimeMillis(); MetroJAXBUtil.marshalPMML(pmml, os); long end = System.currentTimeMillis(); logger.info("Marshalled PMML in {} ms.", (end - start)); } catch(Exception e){ logger.error("Failed to marshal PMML", e); throw e; } } public File getEstimatorInput(){ return this.estimatorInput; } public void setEstimatorInput(File estimatorInput){ this.estimatorInput = estimatorInput; } public String getEstimatorRepr(){ return this.estimatorRepr; } public void setEstimatorRepr(String estimatorRepr){ this.estimatorRepr = estimatorRepr; } public File getMapperInput(){ return this.mapperInput; } public void setMapperInput(File mapperInput){ this.mapperInput = mapperInput; } public String getMapperRepr(){ return this.mapperRepr; } public void setMapperRepr(String mapperRepr){ this.mapperRepr = mapperRepr; } public File getOutput(){ return this.output; } public void setOutput(File output){ this.output = output; } static private void addObjectRepr(PMML pmml, String name, String content){ MiningBuildTask miningBuildTask = pmml.getMiningBuildTask(); if(miningBuildTask == null){ miningBuildTask = new MiningBuildTask(); pmml.setMiningBuildTask(miningBuildTask); } Extension extension = new Extension() .setName(name) .setValue("repr(" + name + ")") .addContent(content); miningBuildTask.addExtensions(extension); } private static final Logger logger = LoggerFactory.getLogger(Main.class); }
package org.csanchez.jenkins.plugins.kubernetes; import java.io.IOException; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.HashSet; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import hudson.model.PeriodicWork; import org.jenkinsci.plugins.kubernetes.auth.KubernetesAuthException; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import com.google.common.base.Objects; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import hudson.Extension; import hudson.XmlFile; import hudson.model.AsyncPeriodicWork; import hudson.model.Saveable; import hudson.model.TaskListener; import hudson.model.listeners.SaveableListener; import io.fabric8.kubernetes.client.HttpClientAware; import io.fabric8.kubernetes.client.KubernetesClient; import jenkins.model.Jenkins; import okhttp3.Dispatcher; import okhttp3.OkHttpClient; /** * Manages the Kubernetes client creation per cloud */ public class KubernetesClientProvider { private static final Logger LOGGER = Logger.getLogger(KubernetesClientProvider.class.getName()); /** * How many clouds can we connect to, default to 10 */ private static final Integer CACHE_SIZE = Integer .getInteger(KubernetesClientProvider.class.getPackage().getName() + ".clients.cacheSize", 10); /** * Time in seconds after which we will close the unused clients. * * Defaults to 5 minutes. */ private static final Long EXPIRED_CLIENTS_PURGE_TIME = Long.getLong( KubernetesClientProvider.class.getPackage().getName() + ".clients.expiredClientsPurgeTime", TimeUnit.MINUTES.toSeconds(5)); /** * How often to check if we need to close clients, default to {@link #EXPIRED_CLIENTS_PURGE_TIME}/2 */ private static final Long EXPIRED_CLIENTS_PURGE_PERIOD = Long.getLong( KubernetesClientProvider.class.getPackage().getName() + ".clients.expiredClientsPurgePeriod", EXPIRED_CLIENTS_PURGE_TIME / 2); /** * Client expiration in seconds. * * Some providers such as Amazon EKS use a token with 15 minutes expiration, so expire clients after 10 minutes. */ private static final long CACHE_EXPIRATION = Long.getLong( KubernetesClientProvider.class.getPackage().getName() + ".clients.cacheExpiration", TimeUnit.MINUTES.toSeconds(10)); private static final Queue<Client> expiredClients = new ConcurrentLinkedQueue<>(); private static final Cache<String, Client> clients = CacheBuilder.newBuilder() .maximumSize(CACHE_SIZE) .expireAfterWrite(CACHE_EXPIRATION, TimeUnit.SECONDS) .removalListener(rl -> { LOGGER.log(Level.FINE, "{0} cache : Removing entry for {1}", new Object[] { KubernetesClient.class.getSimpleName(), rl.getKey() }); Client client = (Client) rl.getValue(); if (client != null) { client.expired = Instant.now(); expiredClients.add(client); } }) .build(); private KubernetesClientProvider() { } static KubernetesClient createClient(KubernetesCloud cloud) throws KubernetesAuthException, IOException { String displayName = cloud.getDisplayName(); final Client c = clients.getIfPresent(displayName); if (c == null) { KubernetesClient client = new KubernetesFactoryAdapter(cloud.getServerUrl(), cloud.getNamespace(), cloud.getServerCertificate(), cloud.getCredentialsId(), cloud.isSkipTlsVerify(), cloud.getConnectTimeout(), cloud.getReadTimeout(), cloud.getMaxRequestsPerHost()).createClient(); clients.put(displayName, new Client(getValidity(cloud), client)); LOGGER.log(Level.INFO, "Created new Kubernetes client: {0} {1}", new Object[] { displayName, client }); return client; } return c.getClient(); } private static int getValidity(KubernetesCloud cloud) { return Objects.hashCode(cloud.getServerUrl(), cloud.getNamespace(), cloud.getServerCertificate(), cloud.getCredentialsId(), cloud.isSkipTlsVerify(), cloud.getConnectTimeout(), cloud.getReadTimeout(), cloud.getMaxRequestsPerHostStr()); } private static class Client { private final KubernetesClient client; private final int validity; private Instant expired; public Client(int validity, KubernetesClient client) { this.client = client; this.validity = validity; } public KubernetesClient getClient() { return client; } public int getValidity() { return validity; } public Instant getExpired() { return expired; } } @Extension public static class PurgeExpiredKubernetesClients extends AsyncPeriodicWork { public PurgeExpiredKubernetesClients() { super("Purge expired KubernetesClients"); } @Override public long getRecurrencePeriod() { return TimeUnit.SECONDS.toMillis(EXPIRED_CLIENTS_PURGE_PERIOD); } @Override protected Level getNormalLoggingLevel() { return Level.FINEST; } @Override protected void execute(TaskListener listener) { closeExpiredClients(); } } /** * Gracefully close expired clients * * @return whether some clients have been closed or not */ @Restricted(NoExternalUse.class) // testing only public static boolean closeExpiredClients() { boolean b = false; if (expiredClients.isEmpty()) { return b; } LOGGER.log(Level.FINE, "Closing expired clients: ({0}) {1}", new Object[] { expiredClients.size(), expiredClients }); if (expiredClients.size() > 10) { LOGGER.log(Level.WARNING, "High number of expired clients, may cause memory leaks: ({0}) {1}", new Object[] { expiredClients.size(), expiredClients }); } for (Iterator<Client> it = expiredClients.iterator(); it.hasNext();) { Client expiredClient = it.next(); // only purge it if the EXPIRED_CLIENTS_PURGE time has elapsed if (Instant.now().minus(EXPIRED_CLIENTS_PURGE_TIME, ChronoUnit.SECONDS) .isBefore(expiredClient.getExpired())) { break; } KubernetesClient client = expiredClient.client; if (client instanceof HttpClientAware) { if (gracefulClose(client, ((HttpClientAware) client).getHttpClient())) { it.remove(); b = true; } } else { LOGGER.log(Level.WARNING, "{0} is not {1}, forcing close", new Object[] { client.toString(), HttpClientAware.class.getSimpleName() }); client.close(); it.remove(); b = true; } } return b; } @Restricted(NoExternalUse.class) // testing only public static boolean gracefulClose(KubernetesClient client, OkHttpClient httpClient) { Dispatcher dispatcher = httpClient.dispatcher(); // Remove the client if there are no more users int runningCallsCount = dispatcher.runningCallsCount(); int queuedCallsCount = dispatcher.queuedCallsCount(); if (runningCallsCount == 0 && queuedCallsCount == 0) { LOGGER.log(Level.INFO, "Closing {0}", client.toString()); client.close(); return true; } else { LOGGER.log(Level.INFO, "Not closing {0}: there are still running ({1}) or queued ({2}) calls", new Object[] { client.toString(), runningCallsCount, queuedCallsCount }); return false; } } private static volatile int runningCallsCount; private static volatile int queuedCallsCount; public static int getRunningCallsCount() { return runningCallsCount; } public static int getQueuedCallsCount() { return queuedCallsCount; } @Restricted(NoExternalUse.class) // testing only public static void invalidate(String displayName) { clients.invalidate(displayName); } @Extension public static class SaveableListenerImpl extends SaveableListener { @Override public void onChange(Saveable o, XmlFile file) { if (o instanceof Jenkins) { Jenkins jenkins = (Jenkins) o; Set<String> cloudDisplayNames = new HashSet<>(clients.asMap().keySet()); for (KubernetesCloud cloud : jenkins.clouds.getAll(KubernetesCloud.class)) { String displayName = cloud.getDisplayName(); Client client = clients.getIfPresent(displayName); if (client != null && client.getValidity() == getValidity(cloud)) { cloudDisplayNames.remove(displayName); } else { LOGGER.log(Level.INFO, "Invalidating Kubernetes client: {0} {1}", new Object[] { displayName, client }); } } // Remove missing / invalid clients for (String displayName : cloudDisplayNames) { LOGGER.log(Level.INFO, "Invalidating Kubernetes client: {0}", displayName); invalidate(displayName); } } super.onChange(o, file); } } @Extension public static class UpdateConnectionCount extends PeriodicWork { @Override public long getRecurrencePeriod() { return TimeUnit.SECONDS.toMillis(5); } @Override protected void doRun() { int runningCallsCount = 0; int queuedCallsCount = 0; for (Client client : KubernetesClientProvider.clients.asMap().values()) { KubernetesClient kClient = client.getClient(); if (kClient instanceof HttpClientAware) { OkHttpClient httpClient = ((HttpClientAware) kClient).getHttpClient(); Dispatcher dispatcher = httpClient.dispatcher(); runningCallsCount += dispatcher.runningCallsCount(); queuedCallsCount += dispatcher.queuedCallsCount(); } } KubernetesClientProvider.runningCallsCount = runningCallsCount; KubernetesClientProvider.queuedCallsCount = queuedCallsCount; } } }
package org.jpmml.xgboost; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteOrder; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import org.dmg.pmml.FieldName; import org.dmg.pmml.PMML; import org.jpmml.model.metro.MetroJAXBUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Main { @Parameter ( names = {"--fmap-input"}, description = "XGBoost feature map input file", required = true ) private File fmapInput = null; @Parameter ( names = {"--help"}, description = "Show the list of configuration options and exit", help = true ) private boolean help = false; @Parameter ( names = {"--model-input"}, description = "XGBoost model input file", required = true ) private File modelInput = null; @Parameter ( names = {"--" + HasXGBoostOptions.OPTION_BYTE_ORDER}, description = "Endianness of XGBoost model input file. Possible values \"BIG_ENDIAN\" (\"BE\") or \"LITTLE_ENDIAN\" (\"LE\")" ) private String byteOrder = (ByteOrder.nativeOrder()).toString(); @Parameter ( names = {"--" + HasXGBoostOptions.OPTION_CHARSET}, description = "Charset of XGBoost model input file" ) private String charset = null; @Parameter ( names = {"--json-path"}, description = "JSONPath expression of the JSON model element" ) private String jsonPath = "$"; @Parameter ( names = {"--missing-value"}, description = "String representation of feature value(s) that should be regarded as missing" ) private String missingValue = null; @Parameter ( names = {"--pmml-output"}, description = "PMML output file", required = true ) private File pmmlOutput = null; @Parameter ( names = {"--target-name"}, description = "Target name. Defaults to \"_target\"" ) private String targetName = null; @Parameter ( names = {"--target-categories"}, description = "Target categories. Defaults to 0-based index [0, 1, .., num_class - 1]" ) private List<String> targetCategories = null; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_COMPACT}, description = "Transform XGBoost-style trees to PMML-style trees", arity = 1 ) private boolean compact = true; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_NUMERIC}, arity = 1, hidden = true ) private boolean numeric = true; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_PRUNE}, arity = 1, hidden = true ) private boolean prune = true; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_NAN_AS_MISSING}, description = "Treat Not-a-Number (NaN) values as missing values", arity = 1 ) private boolean nanAsMissing = true; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_NTREE_LIMIT}, description = "Limit the number of trees. Defaults to all trees" ) private Integer ntreeLimit = null; static public void main(String... args) throws Exception { Main main = new Main(); JCommander commander = new JCommander(main); commander.setProgramName(Main.class.getName()); try { commander.parse(args); } catch(ParameterException pe){ StringBuilder sb = new StringBuilder(); sb.append(pe.toString()); sb.append("\n"); commander.usage(sb); System.err.println(sb.toString()); System.exit(-1); } if(main.help){ StringBuilder sb = new StringBuilder(); commander.usage(sb); System.out.println(sb.toString()); System.exit(0); } main.run(); } private void run() throws Exception { Learner learner; ByteOrder byteOrder = ByteOrderUtil.forValue(this.byteOrder); try(InputStream is = new FileInputStream(this.modelInput)){ logger.info("Parsing learner.."); long begin = System.currentTimeMillis(); learner = XGBoostUtil.loadLearner(is, byteOrder, this.charset, this.jsonPath); long end = System.currentTimeMillis(); logger.info("Parsed learner in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to parse learner", e); throw e; } FeatureMap featureMap; try(InputStream is = new FileInputStream(this.fmapInput)){ logger.info("Parsing feature map.."); long begin = System.currentTimeMillis(); featureMap = XGBoostUtil.loadFeatureMap(is); long end = System.currentTimeMillis(); logger.info("Parsed feature map in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to parse feature map", e); throw e; } if(this.missingValue != null){ featureMap.addMissingValue(this.missingValue); } Map<String, Object> options = new LinkedHashMap<>(); options.put(HasXGBoostOptions.OPTION_COMPACT, this.compact); options.put(HasXGBoostOptions.OPTION_NUMERIC, this.numeric); options.put(HasXGBoostOptions.OPTION_PRUNE, this.prune); options.put(HasXGBoostOptions.OPTION_NAN_AS_MISSING, this.nanAsMissing); options.put(HasXGBoostOptions.OPTION_NTREE_LIMIT, this.ntreeLimit); PMML pmml; try { logger.info("Converting learner to PMML.."); long begin = System.currentTimeMillis(); pmml = learner.encodePMML(options, this.targetName != null ? FieldName.create(this.targetName) : null, this.targetCategories, featureMap); long end = System.currentTimeMillis(); logger.info("Converted learner to PMML in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to convert learner to PMML", e); throw e; } try(OutputStream os = new FileOutputStream(this.pmmlOutput)){ logger.info("Marshalling PMML.."); long begin = System.currentTimeMillis(); MetroJAXBUtil.marshalPMML(pmml, os); long end = System.currentTimeMillis(); logger.info("Marshalled PMML in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to marshal PMML", e); throw e; } } private static final Logger logger = LoggerFactory.getLogger(Main.class); }
package ibis.io; import java.io.ObjectInput; import java.io.ObjectStreamClass; import java.io.IOException; import java.io.NotActiveException; import java.io.Serializable; import java.io.Externalizable; import ibis.ipl.IbisIOException; public final class IbisSerializationInputStream extends SerializationInputStream implements IbisStreamFlags { class TypeInfo { Class clazz; boolean isArray; boolean isString; // for ibis.io.Serializable Generator gen; // for java.io.Serializable AlternativeTypeInfo altInfo; TypeInfo(Class clzz, boolean isArray, boolean isString, Generator gen){ this.clazz = clzz; this.isArray = isArray; this.isString = isString; this.gen = gen; if (gen == null) { altInfo = new AlternativeTypeInfo(clzz); } } } IbisVector objects = new IbisVector(); int next_object; public ArrayInputStream in; /* Type id management */ private int next_type = 1; private IbisVector types; private static Class stringClass; static { try { stringClass = Class.forName("java.lang.String"); } catch (Exception e) { System.err.println("Failed to find java.lang.String " + e); System.exit(1); } } /* Notion of a current object, needed for defaultWriteObject. */ private Object current_object; private int current_level; private ImplGetField current_getfield; private Object[] object_stack; private int[] level_stack; private ImplGetField[] getfield_stack; private int max_stack_size = 0; private int stack_size = 0; public IbisSerializationInputStream(ArrayInputStream in) throws IOException { super(); init(in); } public void init(ArrayInputStream in) throws IOException { types = new IbisVector(); types.add(0, null); // Vector requires this types.add(TYPE_BOOLEAN, new TypeInfo(classBooleanArray, true, false, null)); types.add(TYPE_BYTE, new TypeInfo(classByteArray, true, false, null)); types.add(TYPE_CHAR, new TypeInfo(classCharArray, true, false, null)); types.add(TYPE_SHORT, new TypeInfo(classShortArray, true, false, null)); types.add(TYPE_INT, new TypeInfo(classIntArray, true, false, null)); types.add(TYPE_LONG, new TypeInfo(classLongArray, true, false, null)); types.add(TYPE_FLOAT, new TypeInfo(classFloatArray, true, false, null)); types.add(TYPE_DOUBLE, new TypeInfo(classDoubleArray, true, false, null)); next_type = PRIMITIVE_TYPES; this.in = in; objects.clear(); next_object = CONTROL_HANDLES; } public String serializationImplName() { return "ibis"; } public void reset() { if(DEBUG) { System.err.println("IN(" + this + ") reset: next handle = " + next_object + "."); } objects.clear(); next_object = CONTROL_HANDLES; } public void statistics() { System.err.println("IbisSerializationInputStream: statistics() not yet implemented"); } private void receive() throws IOException { int leftover = in.max_handle_index - in.handle_index; if (leftover == 1 && in.handle_buffer[in.handle_index] == RESET_HANDLE) { reset(); in.handle_index++; } in.receive(); } /* This is the data output / object output part */ public int read() throws IOException { while (in.byte_index == in.max_byte_index) { receive(); } return in.byte_buffer[in.byte_index++]; } public int read(byte[] b) throws IOException { return read(b, 0, b.length); } public int read(byte[] b, int off, int len) throws IOException { readArray(b, off, len); return len; } public long skip(long n) throws IOException { throw new IOException("skip not meaningful in a typed input stream"); } public int skipBytes(int n) throws IOException { throw new IOException("skipBytes not meaningful in a typed input stream"); } public int available() throws IOException { /* @@@ NOTE: this is not right. There are also some buffered arrays..*/ return in.available(); } public void readFully(byte[] b) throws IOException { readFully(b, 0, b.length); } public void readFully(byte[] b, int off, int len) throws IOException { read(b, off, len); } public boolean readBoolean() throws IOException { while (in.byte_index == in.max_byte_index) { receive(); } return (in.byte_buffer[in.byte_index++] == 1); } public byte readByte() throws IOException { while (in.byte_index == in.max_byte_index) { receive(); } return in.byte_buffer[in.byte_index++]; } public int readUnsignedByte() throws IOException { while (in.byte_index == in.max_byte_index) { receive(); } int i = in.byte_buffer[in.byte_index++]; if (i < 0) { i += 256; } return i; } public short readShort() throws IOException { while (in.short_index == in.max_short_index) { receive(); } return in.short_buffer[in.short_index++]; } public int readUnsignedShort() throws IOException { while (in.short_index == in.max_short_index) { receive(); } int i = in.short_buffer[in.short_index++]; if (i < 0) { i += 65536; } return i; } public char readChar() throws IOException { while (in.char_index == in.max_char_index) { receive(); } return in.char_buffer[in.char_index++]; } public int readInt() throws IOException { while (in.int_index == in.max_int_index) { receive(); } return in.int_buffer[in.int_index++]; } public int readHandle() throws IOException { while (in.handle_index == in.max_handle_index) { receive(); } if(DEBUG) { System.err.println("read handle [" + in.handle_index + "] = " + Integer.toHexString(in.handle_buffer[in.handle_index])); } return in.handle_buffer[in.handle_index++]; } public long readLong() throws IOException { while (in.long_index == in.max_long_index) { receive(); } return in.long_buffer[in.long_index++]; } public float readFloat() throws IOException { while (in.float_index == in.max_float_index) { receive(); } return in.float_buffer[in.float_index++]; } public double readDouble() throws IOException { while (in.double_index == in.max_double_index) { receive(); } return in.double_buffer[in.double_index++]; } public String readUTF() throws IOException { int bn = readInt(); if(DEBUG) { System.err.println("readUTF: len = " + bn); } if(bn == -1) { return null; } /* char[] data=new char[bn]; readArray(data, 0, bn); String s = new String(data); if(DEBUG) { System.err.println("returning string " + s); } return s; */ byte[] b = new byte[bn]; readArray(b, 0, bn); int len = 0; char[] c = new char[bn]; for (int i = 0; i < bn; i++) { if ((b[i] & ~0x7f) == 0) { c[len++] = (char)(b[i] & 0x7f); } else if ((b[i] & ~0x1f) == 0xc0) { if (i + 1 >= bn || (b[i + 1] & ~0x3f) != 0x80) { throw new IOException("UTF Data Format Exception"); } c[len++] = (char)(((b[i] & 0x1f) << 6) | (b[i] & 0x3f)); i++; } else if ((b[i] & ~0x0f) == 0xe0) { if (i + 2 >= bn || (b[i + 1] & ~0x3f) != 0x80 || (b[i + 2] & ~0x3f) != 0x80) { throw new IOException("UTF Data Format Exception"); } c[len++] = (char)(((b[i] & 0x0f) << 12) | ((b[i+1] & 0x3f) << 6) | b[i+2] & 0x3f); } else { throw new IOException("UTF Data Format Exception"); } } String s = new String(c, 0, len); // System.out.println("readUTF: " + s); if(DEBUG) { System.err.println("read string " + s); } return s; } private void readArrayHeader(Class clazz, int len) throws IOException { if(DEBUG) { System.err.println("readArrayHeader: class = " + clazz + " len = " + len); } int type; while (true) { type = readHandle(); if (type != RESET_HANDLE) { break; } reset(); } if (ASSERTS && ((type & TYPE_BIT) == 0)) { throw new IOException("Array slice header but I receive a HANDLE!"); } Class in_clazz = readType(type & TYPE_MASK).clazz; int in_len = readInt(); if (ASSERTS && !clazz.isAssignableFrom(in_clazz)) { throw new ClassCastException("Cannot assign class " + clazz + " from read class " + in_clazz); } if (ASSERTS && in_len != len) { throw new ArrayIndexOutOfBoundsException("Cannot read " + in_len + " into " + len + " elements"); } } public String readBytes() throws IOException { int len = readInt(); byte[] bytes = new byte[len]; for (int i = 0; i < len; i++) { bytes[i] = readByte(); } return new String(bytes); } public String readChars() throws IOException { int len = readInt(); char[] chars = new char[len]; for (int i = 0; i < len; i++) { chars[i] = readChar(); } return new String(chars); } public void readArray(boolean[] ref, int off, int len) throws IOException { readArrayHeader(classBooleanArray, len); in.readArray(ref, off, len); } public void readArray(byte[] ref, int off, int len) throws IOException { readArrayHeader(classByteArray, len); in.readArray(ref, off, len); } public void readArray(char[] ref, int off, int len) throws IOException { readArrayHeader(classCharArray, len); in.readArray(ref, off, len); } public void readArray(short[] ref, int off, int len) throws IOException { readArrayHeader(classShortArray, len); in.readArray(ref, off, len); } public void readArray(int[] ref, int off, int len) throws IOException { readArrayHeader(classIntArray, len); in.readArray(ref, off, len); } public void readArray(long[] ref, int off, int len) throws IOException { readArrayHeader(classLongArray, len); in.readArray(ref, off, len); } public void readArray(float[] ref, int off, int len) throws IOException { readArrayHeader(classFloatArray, len); in.readArray(ref, off, len); } public void readArray(double[] ref, int off, int len) throws IOException { readArrayHeader(classDoubleArray, len); in.readArray(ref, off, len); } public void readArray(Object[] ref, int off, int len) throws IOException, ClassNotFoundException { readArrayHeader(ref.getClass(), len); for (int i = off; i < off + len; i++) { ref[i] = readObject(); } } public void addObjectToCycleCheck(Object o) { objects.add(next_object, o); next_object++; } public Object getObjectFromCycleCheck(int handle) { Object o = objects.get(handle); // - CONTROL_HANDLES); if(DEBUG) { System.err.println("getfromcycle: handle = " + (handle - CONTROL_HANDLES) + " obj = " + o); } return o; } public int readKnownTypeHeader() throws IOException { int handle_or_type = readHandle(); if (handle_or_type == NUL_HANDLE) { if(DEBUG) { System.err.println("readKnownTypeHeader -> read NUL_HANDLE"); } return 0; } if ((handle_or_type & TYPE_BIT) == 0) { if(DEBUG) { System.err.println("readKnownTypeHeader -> read OLD HANDLE " + (handle_or_type - CONTROL_HANDLES)); } return handle_or_type; } if(DEBUG) { System.err.println("readKnownTypeHeader -> read NEW HANDLE " + ((handle_or_type & TYPE_MASK) - CONTROL_HANDLES)); } return -1; } Object readArray(Class arrayClass, int type) throws IOException, ClassNotFoundException { int len = readInt(); if(DEBUG) { System.err.println("Read array " + arrayClass + " length " + len); } // if(len < 0) len = -len; switch (type) { case TYPE_BOOLEAN: boolean [] temp1 = new boolean[len]; in.readArray(temp1, 0, len); objects.add(next_object++, temp1); return temp1; case TYPE_BYTE: byte [] temp2 = new byte[len]; in.readArray(temp2, 0, len); objects.add(next_object++, temp2); return temp2; case TYPE_SHORT: short [] temp3 = new short[len]; in.readArray(temp3, 0, len); objects.add(next_object++, temp3); return temp3; case TYPE_CHAR: char [] temp4 = new char[len]; in.readArray(temp4, 0, len); objects.add(next_object++, temp4); return temp4; case TYPE_INT: int [] temp5 = new int[len]; in.readArray(temp5, 0, len); objects.add(next_object++, temp5); return temp5; case TYPE_LONG: long [] temp6 = new long[len]; in.readArray(temp6, 0, len); objects.add(next_object++, temp6); return temp6; case TYPE_FLOAT: float [] temp7 = new float[len]; in.readArray(temp7, 0, len); objects.add(next_object++, temp7); return temp7; case TYPE_DOUBLE: double [] temp8 = new double[len]; in.readArray(temp8, 0, len); objects.add(next_object++, temp8); return temp8; default: if(DEBUG) { System.err.println("Read an array " + arrayClass + " of len " + len); } Object ref = java.lang.reflect.Array.newInstance(arrayClass.getComponentType(), len); objects.add(next_object++, ref); for (int i = 0; i < len; i++) { ((Object[])ref)[i] = readObject(); if(DEBUG) { System.err.println("Read array[" + i + "] = " + ((Object[])ref)[i].getClass().getName()); } } return ref; } } public TypeInfo readType(int type) throws IOException { if(DEBUG) { System.err.println("Read type_number " + Integer.toHexString(type) + ", next = " + Integer.toHexString(next_type)); } if (type < next_type) { return (TypeInfo) types.get(type); } else { if (next_type != type) { System.err.println("EEK: readType: next_type != type"); System.exit(1); } if(DEBUG) { System.err.println("NEW TYPE: reading utf"); } String typeName = readUTF(); if(DEBUG) { System.err.println("New type " + typeName); } Class clazz = null; try { clazz = Class.forName(typeName); } catch (ClassNotFoundException e) { throw new IOException("class " + typeName + " not found"); } Generator g = null; TypeInfo t = null; if (clazz.isArray()) { t = new TypeInfo(clazz, true, false, g); } else if (clazz == stringClass) { t = new TypeInfo(clazz, false, true, g); } else { try { Class gen_class = Class.forName(typeName + "_ibis_io_Generator"); g = (Generator) gen_class.newInstance(); } catch (Exception e) { System.err.println("WARNING: Failed to find generator for " + clazz.getName()); // + " error: " + e); // failed to get generator class -> use null } t = new TypeInfo(clazz, false, false, g); } types.add(next_type, t); next_type++; return t; } } private native void setFieldDouble(Object ref, String fieldname, double d); private native void setFieldLong(Object ref, String fieldname, long l); private native void setFieldFloat(Object ref, String fieldname, float f); private native void setFieldInt(Object ref, String fieldname, int i); private native void setFieldShort(Object ref, String fieldname, short s); private native void setFieldChar(Object ref, String fieldname, char c); private native void setFieldByte(Object ref, String fieldname, byte b); private native void setFieldBoolean(Object ref, String fieldname, boolean b); private native void setFieldObject(Object ref, String fieldname, String osig, Object o); private void alternativeDefaultReadObject(AlternativeTypeInfo t, Object ref) throws IOException { int temp = 0; try { for (int i=0;i<t.double_count;i++) { if (t.fields_final[temp]) { setFieldDouble(ref, t.serializable_fields[temp].getName(), readDouble()); } else { t.serializable_fields[temp].setDouble(ref, readDouble()); } temp++; } for (int i=0;i<t.long_count;i++) { if (t.fields_final[temp]) { setFieldLong(ref, t.serializable_fields[temp].getName(), readLong()); } else { t.serializable_fields[temp].setLong(ref, readLong()); } temp++; } for (int i=0;i<t.float_count;i++) { if (t.fields_final[temp]) { setFieldFloat(ref, t.serializable_fields[temp].getName(), readFloat()); } else { t.serializable_fields[temp].setFloat(ref, readFloat()); } temp++; } for (int i=0;i<t.int_count;i++) { if (t.fields_final[temp]) { setFieldInt(ref, t.serializable_fields[temp].getName(), readInt()); } else { t.serializable_fields[temp].setInt(ref, readInt()); } temp++; } for (int i=0;i<t.short_count;i++) { if (t.fields_final[temp]) { setFieldShort(ref, t.serializable_fields[temp].getName(), readShort()); } else { t.serializable_fields[temp].setShort(ref, readShort()); } temp++; } for (int i=0;i<t.char_count;i++) { if (t.fields_final[temp]) { setFieldChar(ref, t.serializable_fields[temp].getName(), readChar()); } else { t.serializable_fields[temp].setChar(ref, readChar()); } temp++; } for (int i=0;i<t.char_count;i++) { if (t.fields_final[temp]) { setFieldChar(ref, t.serializable_fields[temp].getName(), readChar()); } else { t.serializable_fields[temp].setChar(ref, readChar()); } temp++; } for (int i=0;i<t.byte_count;i++) { if (t.fields_final[temp]) { setFieldByte(ref, t.serializable_fields[temp].getName(), readByte()); } else { t.serializable_fields[temp].setByte(ref, readByte()); } temp++; } for (int i=0;i<t.boolean_count;i++) { if (t.fields_final[temp]) { setFieldBoolean(ref, t.serializable_fields[temp].getName(), readBoolean()); } else { t.serializable_fields[temp].setBoolean(ref, readBoolean()); } temp++; } for (int i=0;i<t.reference_count;i++) { if (t.fields_final[temp]) { String fieldname = t.serializable_fields[temp].getName(); String fieldtype = t.serializable_fields[temp].getType().getName(); if (fieldtype.startsWith("[")) { } else { fieldtype = "L" + fieldtype.replace('/', '.') + ";"; } // System.out.println("fieldname = " + fieldname); // System.out.println("signature = " + fieldtype); setFieldObject(ref, fieldname, fieldtype, readObject()); } else { t.serializable_fields[temp].set(ref, readObject()); } temp++; } } catch(ClassNotFoundException e) { throw new IbisIOException("class not found exception", e); } catch(IllegalAccessException e2) { throw new IbisIOException("illegal access exception", e2); } } private void alternativeReadObject(AlternativeTypeInfo t, Object ref) throws IOException { if (t.superSerializable) { alternativeReadObject(t.alternativeSuperInfo, ref); } if (t.hasReadObject) { current_level = t.level; t.invokeReadObject(ref, this); return; } if (DEBUG) { System.err.println("Using alternative readObject for " + ref.getClass().getName()); } alternativeDefaultReadObject(t, ref); } public void readSerializableObject(Object ref, String classname) throws IOException { AlternativeTypeInfo t = AlternativeTypeInfo.getAlternativeTypeInfo(classname); push_current_object(ref, 0); alternativeReadObject(t, ref); pop_current_object(); } public void defaultReadSerializableObject(Object ref, int depth) throws IOException { Class type = ref.getClass(); AlternativeTypeInfo t = AlternativeTypeInfo.getAlternativeTypeInfo(type); /* Find the type info corresponding to the current invocation. See the invokeReadObject invocation in alternativeReadObject. */ while (t.level > depth) { t = t.alternativeSuperInfo; } alternativeDefaultReadObject(t, ref); } private native Object createUninitializedObject(Class type, Class non_serializable_super); public void push_current_object(Object ref, int level) { if (stack_size >= max_stack_size) { max_stack_size = 2 * max_stack_size + 10; Object[] new_o_stack = new Object[max_stack_size]; int[] new_l_stack = new int[max_stack_size]; ImplGetField[] new_g_stack = new ImplGetField[max_stack_size]; for (int i = 0; i < stack_size; i++) { new_o_stack[i] = object_stack[i]; new_l_stack[i] = level_stack[i]; new_g_stack[i] = getfield_stack[i]; } object_stack = new_o_stack; level_stack = new_l_stack; getfield_stack = new_g_stack; } object_stack[stack_size] = current_object; level_stack[stack_size] = current_level; getfield_stack[stack_size] = current_getfield; stack_size++; current_object = ref; current_level = level; } public void pop_current_object() { stack_size current_object = object_stack[stack_size]; current_level = level_stack[stack_size]; current_getfield = getfield_stack[stack_size]; } public Object doReadObject() throws IOException, ClassNotFoundException { /* * ref < 0: type * ref = 0: null ptr * ref > 0: handle */ int handle_or_type = readHandle(); while (handle_or_type == RESET_HANDLE) { reset(); handle_or_type = readHandle(); } if (handle_or_type == NUL_HANDLE) { return null; } if ((handle_or_type & TYPE_BIT) == 0) { /* Ah, it's a handle. Look it up, return the stored ptr */ Object o = objects.get(handle_or_type); if(DEBUG) { System.err.println("readobj: handle = " + (handle_or_type - CONTROL_HANDLES) + " obj = " + o); } return o; } int type = handle_or_type & TYPE_MASK; TypeInfo t = readType(type); if(DEBUG) { System.err.println("read type " + t.clazz + " isarray " + t.isArray); } Object obj; if(DEBUG) { System.err.println("t = " + t); } if (t.isArray) { obj = readArray(t.clazz, type); } else if (t.isString) { obj = readUTF(); addObjectToCycleCheck(obj); } else if (t.gen != null) { obj = t.gen.generated_newInstance(this); } else if (Externalizable.class.isAssignableFrom(t.clazz)) { try { // TODO: is this correct? I guess it is, when accessibility // is fixed. obj = t.clazz.newInstance(); } catch(Exception e) { throw new RuntimeException("Could not instantiate" + e); } push_current_object(obj, 0); ((java.io.Externalizable) obj).readExternal(this); pop_current_object(); } else { // this is for java.io.Serializable try { // obj = t.clazz.newInstance(); Not correct: calls wrong constructor. Class t2 = t.clazz; while (Serializable.class.isAssignableFrom(t2)) { /* Find first non-serializable super-class. */ t2 = t2.getSuperclass(); } // Calls constructor for non-serializable superclass. obj = createUninitializedObject(t.clazz, t2); addObjectToCycleCheck(obj); push_current_object(obj, 0); alternativeReadObject(t.altInfo, obj); pop_current_object(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Couldn't deserialize or create object " + e); } } return obj; } public void close() throws IOException { } protected void readStreamHeader() { /* ignored */ } public GetField readFields() throws IOException, ClassNotFoundException { if (current_object == null) { throw new NotActiveException("not in readObject"); } Class type = current_object.getClass(); AlternativeTypeInfo t = AlternativeTypeInfo.getAlternativeTypeInfo(type); current_getfield = new ImplGetField(t); current_getfield.readFields(); return current_getfield; } private class ImplGetField extends GetField { double[] doubles; long[] longs; int[] ints; float[] floats; short[] shorts; char[] chars; byte[] bytes; boolean[] booleans; Object[] references; AlternativeTypeInfo t; ImplGetField(AlternativeTypeInfo t) { doubles = new double[t.double_count]; longs = new long[t.long_count]; ints = new int[t.int_count]; shorts = new short[t.short_count]; floats = new float[t.float_count]; chars = new char[t.char_count]; bytes = new byte[t.byte_count]; booleans = new boolean[t.boolean_count]; references = new Object[t.reference_count]; this.t = t; } public ObjectStreamClass getObjectStreamClass() { /* I don't know how it could be used here, but ... */ return ObjectStreamClass.lookup(t.clazz); } public boolean defaulted(String name) { return false; } public boolean get(String name, boolean dflt) { return booleans[t.getOffset(name, Boolean.TYPE)]; } public char get(String name, char dflt) { return chars[t.getOffset(name, Character.TYPE)]; } public byte get(String name, byte dflt) { return bytes[t.getOffset(name, Byte.TYPE)]; } public short get(String name, short dflt) { return shorts[t.getOffset(name, Short.TYPE)]; } public int get(String name, int dflt) { return ints[t.getOffset(name, Integer.TYPE)]; } public long get(String name, long dflt) { return longs[t.getOffset(name, Long.TYPE)]; } public float get(String name, float dflt) { return floats[t.getOffset(name, Float.TYPE)]; } public double get(String name, double dflt) { return doubles[t.getOffset(name, Double.TYPE)]; } public Object get(String name, Object dflt) { return references[t.getOffset(name, Object.class)]; } void readFields() throws IOException, ClassNotFoundException { for (int i = 0; i < t.double_count; i++) doubles[i] = readDouble(); for (int i = 0; i < t.float_count; i++) floats[i] = readFloat(); for (int i = 0; i < t.long_count; i++) longs[i] = readLong(); for (int i = 0; i < t.int_count; i++) ints[i] = readInt(); for (int i = 0; i < t.short_count; i++) shorts[i] = readShort(); for (int i = 0; i < t.char_count; i++) chars[i] = readChar(); for (int i = 0; i < t.byte_count; i++) bytes[i] = readByte(); for (int i = 0; i < t.boolean_count; i++) booleans[i] = readBoolean(); for (int i = 0; i < t.reference_count; i++) references[i] = readObject(); } } public void defaultReadObject() throws IOException, NotActiveException { if (current_object == null) { throw new NotActiveException("defaultReadObject without a current object"); } Object ref = current_object; if (ref instanceof ibis.io.Serializable) { ((ibis.io.Serializable)ref).generated_DefaultReadObject(this, current_level); } else if (ref instanceof java.io.Serializable) { Class type = ref.getClass(); AlternativeTypeInfo t = AlternativeTypeInfo.getAlternativeTypeInfo(type); /* Find the type info corresponding to the current invocation. See the invokeReadObject invocation in alternativeReadObject. */ while (t.level > current_level) { t = t.alternativeSuperInfo; } alternativeDefaultReadObject(t, ref); } else { Class type = ref.getClass(); throw new RuntimeException("Not Serializable : " + type.toString()); } } static { try { /* Need conversion for allocation of uninitialized objects. */ System.loadLibrary("conversion"); } catch(Throwable t) { System.err.println("Could not load libconversion"); } } }
package cn.com.restarter.service; import cn.com.restarter.domain.FileInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; /** * @author : lihaoquan */ @Component public class TaskHandler { private static Logger logger = LoggerFactory.getLogger(TaskHandler.class); public String execCommand(String command){ String errorMSG = ""; try { String filePath = Thread.currentThread() .getContextClassLoader().getResource("").getPath(); String g = ""; command=filePath+command; Runtime.getRuntime().exec(new String[] {command, g}); } catch (Exception e) { System.out.println("error Message:" + e.getMessage()); e.printStackTrace(); } finally{ return errorMSG; } } public void start() { logger.info("weblogic"); execCommand("startup.bat"); } public void stop() { logger.info("weblogic"); execCommand("shutdown.bat"); } public void restart() throws Exception { logger.info("weblogic"); execCommand("shutdown.bat"); Thread.sleep(20000); execCommand("startup.bat"); } }
package battle; import java.time.Duration; public class Status { /** * Name of the Status. Identifies the Status from unrelated Status objects. * This is a required field. No default value is available. */ private final String name; /** * Simple text-based explanation of the Status. This is a required field. No * default value is available. */ private final String description; /** * The time before this status expires. Zero means the Status has an instant * duration. Less then zero means duration is infinite. This is a required * field. No default value is available. */ private Duration duration; /** * The number of stacks this status is currently up to. Statuses with a * duration greater then 0 do not stack in magnitude, rather they stack * duration. The default for this is 1. */ private int stacks; /** * States whether or not this status stuns the unit. Stunned units do not * decrement their skill cooldowns and perform skills while true. The default * for this is false. */ private final boolean stuns; /** * States whether or not the Status defeats the Unit. Defeated Unit objects * allow their Team to lose a battle if all other ally Unit object's are also * defeated. */ private final boolean defeats; /** * States whether or not the status is visible to the user of the client. The * default for this is false. */ private final boolean hidden; /** * Basic constructor. * @param name name of the Status. * @param description simple text-based description of the Status. * @param duration time before this Status expires. */ public Status(String name, String description, Duration duration) { this(name, description, duration, 1, false, false, false); } /** * Basic constructor. * @param name name of the Status. * @param description simple text-based description of the Status. * @param duration time before this Status expires. * @param stacks number of stacks this Status is currently up to. */ public Status(String name, String description, Duration duration, int stacks) { this(name, description, duration, stacks, false, false, false); } /** * Basic constructor. * @param name name of the Status. * @param description simple text-based description of the Status. * @param duration time before this Status expires. * @param stuns true if the Status stuns the target. */ public Status(String name, String description, Duration duration, boolean stuns) { this(name, description, duration, 1, stuns, false, false); } /** * Basic constructor. * @param name name of the Status. * @param description simple text-based description of the Status. * @param duration time before this Status expires. * @param stacks number of stacks this Status is currently up to. * @param stuns true if the Status stuns the target. */ public Status(String name, String description, Duration duration, int stacks, boolean stuns) { this(name, description, duration, stacks, stuns, false, false); } /** * Basic constructor. * @param name name of the Status. * @param description simple text-based description of the Status. * @param duration time before this Status expires. * @param stuns true if the Status stuns the target. * @param defeats true if the Status defeats the Unit. */ public Status(String name, String description, Duration duration, boolean stuns, boolean defeats) { this(name, description, duration, 1, stuns, defeats, false); } /** * Basic constructor. * @param name name of the Status. * @param description simple text-based description of the Status. * @param duration time before this Status expires. * @param stacks number of stacks this Status is currently up to. * @param stuns true if the Status stuns the target. * @param defeats true if the Status defeats the Unit. */ public Status(String name, String description, Duration duration, int stacks, boolean stuns, boolean defeats) { this(name, description, duration, stacks, stuns, defeats, false); } /** * Basic constructor. * @param name name of the Status. * @param description simple text-based description of the Status. * @param duration time before this Status expires. * @param stuns true if the Status stuns the target. * @param defeats true if the Status defeats the Unit. * @param hidden true if the Status should be hidden from the client user. */ public Status(String name, String description, Duration duration, boolean stuns, boolean defeats, boolean hidden) { this(name, description, duration, 1, stuns, defeats, hidden); } /** * Basic constructor. * @param name name of the Status. * @param description simple text-based description of the Status. * @param duration time before this Status expires. * @param stacks number of stacks this Status is currently up to. * @param stuns true if the Status stuns the target. * @param defeats true if the Status defeats the Unit. * @param hidden true if the Status should be hidden from the client user. */ public Status(String name, String description, Duration duration, int stacks, boolean stuns, boolean defeats, boolean hidden) { this.name = name; this.description = description; this.duration = duration; if (stacks > 0) { this.stacks = stacks; } else this.stacks = 1; this.stuns = stuns; this.defeats = defeats; this.hidden = hidden; } /** * Copy constructor. * @param copyOf is the object of Status which we make our copy from. */ public Status(Status copyOf) { this.name = copyOf.getName(); this.description = copyOf.getDescription(); this.duration = copyOf.duration; this.stacks = copyOf.getStacks(); this.stuns = copyOf.isStunning(); this.defeats = copyOf.isDefeating(); this.hidden = copyOf.isHidden(); } /** * Getter for the description of the Status. * @return simple text-based description of the Status. */ public String getDescription() { return description; } /** * Getter for the duration of the Status. * @return time before this Status expires. */ public int getDuration() { return (int)duration.toMillis(); } /** * Getter for the name of the Status. * @return name of the Status. */ public String getName() { return name; } /** * Getter for the stacks of the Status. * @return number of stacks this Status has. */ public int getStacks() { return stacks; } /** * Returns true if the Status defeats the Unit. * @return true if the Status defeats the Unit. */ public boolean isDefeating() { return defeats; } /** * Returns true if the Status should be hidden from the client user. * @return true if the Status should be hidden from the client user. */ public boolean isHidden() { return hidden; } /** * Returns true if this Status can have stacks (duration is not 0). * @return true if this Status can have stacks. */ public boolean isStackable() { return (duration.isNegative() || duration.isZero()); } /** * Returns true if the Status stuns the Unit. * @return true if the Status stuns the Unit. */ public boolean isStunning() { return stuns; } /** * Event method for when this Status is applied. This method is meant to be * overidden in order to have any effect. * @param thisUnit the Unit the Status is being applied to. * @return true if the Status allows itself to be applied. */ protected boolean onApply(Unit thisUnit) { return true; } /** * Event method for when this status is removed. This method is meant to be * overridden in order to have any effect. * @param thisUnit the Unit who owns the Status. * @return true if the Status allows itself to be removed. */ protected boolean onRemove(Unit thisUnit) { return true; } /** * Setter for the duration of the status. * @param duration time before this Status expires. */ public void setDuration(int duration) { this.duration = Duration.ofMillis(duration); } /** * Setter for the stacks the unit has. * @param stacks number of stacks this Status is set to. Stack size cannot be * 0 or less. */ public void setStacks(int stacks) { if (stacks > 0) { this.stacks = stacks; } } @Override public String toString() { return name; } }
package org.openforis.ceo; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.net.URLDecoder; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Optional; import java.util.UUID; import java.util.stream.Collector; import java.util.stream.StreamSupport; import spark.Request; import spark.Response; public class AJAX { private static String expandResourcePath(String filename) { return AJAX.class.getResource(filename).getFile(); } private static JsonElement readJsonFile(String filename) { String jsonDataDir = expandResourcePath("/public/json/"); try (FileReader fileReader = new FileReader(new File(jsonDataDir, filename))) { return (new JsonParser()).parse(fileReader); } catch (Exception e) { throw new RuntimeException(e); } } private static void writeJsonFile(String filename, JsonElement data) { String jsonDataDir = expandResourcePath("/public/json/"); try (FileWriter fileWriter = new FileWriter(new File(jsonDataDir, filename))) { fileWriter.write(data.toString()); } catch (Exception e) { throw new RuntimeException(e); } } private static Collector<JsonElement, ?, JsonArray> intoJsonArray = Collector.of(JsonArray::new, JsonArray::add, (left, right) -> { left.addAll(right); return left; }); public static String getAllProjects(Request req, Response res) { return readJsonFile("project_list.json").toString(); } public static String getProjectPlots(Request req, Response res) { String projectId = req.body(); return readJsonFile("plot_data_" + projectId + ".json").toString(); } public static String dumpProjectAggregateData(Request req, Response res) { // FIXME: Write downloads/ceo_<project_name>_<yyyy-mm-dd>.csv and return its filename String projectId = req.body(); return "downloads/ceo_mekong_river_region_2017-04-29.csv"; } public static String archiveProject(Request req, Response res) { String projectId = req.body(); JsonArray projects = readJsonFile("project_list.json").getAsJsonArray(); JsonArray updatedProjects = StreamSupport.stream(projects.spliterator(), false) .map(project -> project.getAsJsonObject()) .map(project -> { if (projectId.equals(project.get("id").getAsString())) { project.remove("archived"); project.addProperty("archived", true); return project; } else { return project; } }) .collect(intoJsonArray); writeJsonFile("project_list.json", updatedProjects); return ""; } public static String addUserSamples(Request req, Response res) { // FIXME: Stub JsonObject userSample = (new JsonParser()).parse(req.body()).getAsJsonObject(); return ""; } public static String flagPlot(Request req, Response res) { // FIXME: Stub String plotId = req.body(); return ""; } public static String geodashId(Request req, Response res) { String geodashDataDir = expandResourcePath("/public/json/"); try (FileReader projectFileReader = new FileReader(new File(geodashDataDir, "proj.json"))) { JsonParser parser = new JsonParser(); JsonArray projects = parser.parse(projectFileReader).getAsJsonArray(); Optional matchingProject = StreamSupport.stream(projects.spliterator(), false) .map(project -> project.getAsJsonObject()) .filter(project -> req.params(":id").equals(project.get("projectID").getAsString())) .map(project -> { try (FileReader dashboardFileReader = new FileReader(new File(geodashDataDir, "dash-" + project.get("dashboard").getAsString() + ".json"))) { return parser.parse(dashboardFileReader).getAsJsonObject(); } catch (Exception e) { throw new RuntimeException(e); } }) .findFirst(); if (matchingProject.isPresent()) { if (req.queryParams("callback") != null) { return req.queryParams("callback") + "(" + matchingProject.get().toString() + ")"; } else { return matchingProject.get().toString(); } } else { if (true) { // FIXME: Make sure this is true if the user has role admin String newUUID = UUID.randomUUID().toString(); JsonObject newProject = new JsonObject(); newProject.addProperty("projectID", req.params(":id")); newProject.addProperty("dashboard", newUUID); projects.add(newProject); try (FileWriter projectFileWriter = new FileWriter(new File(geodashDataDir, "proj.json"))) { projectFileWriter.write(projects.toString()); } catch (Exception e) { throw new RuntimeException(e); } JsonObject newDashboard = new JsonObject(); newDashboard.addProperty("projectID", req.params(":id")); newDashboard.addProperty("projectTitle", req.queryParams("title")); newDashboard.addProperty("widgets", "[]"); newDashboard.addProperty("dashboardID", newUUID); try (FileWriter dashboardFileWriter = new FileWriter(new File(geodashDataDir, "dash-" + newUUID + ".json"))) { dashboardFileWriter.write(newDashboard.toString()); } catch (Exception e) { throw new RuntimeException(e); } if (req.queryParams("callback") != null) { return req.queryParams("callback") + "(" + newDashboard.toString() + ")"; } else { return newDashboard.toString(); } } else { return "No project exists with ID: " + req.params(":id") + "."; } } } catch (Exception e) { throw new RuntimeException(e); } } public static String updateDashBoardByID(Request req, Response res) { String returnString = ""; /* Code will go here to update dashboard*/ return returnString; } public static String createDashBoardWidgetByID(Request req, Response res) { String geodashDataDir = expandResourcePath("/public/json/"); JsonParser parser = new JsonParser(); JsonObject dashboardObj = new JsonObject(); try (FileReader dashboardFileReader = new FileReader(new File(geodashDataDir, "dash-" + req.queryParams("dashID") + ".json"))) { dashboardObj = parser.parse(dashboardFileReader).getAsJsonObject(); dashboardObj.getAsJsonArray("widgets").add(parser.parse(URLDecoder.decode(req.queryParams("widgetJSON"), "UTF-8")).getAsJsonObject()); } catch (Exception e) { throw new RuntimeException(e); } try (FileWriter dashboardFileWriter = new FileWriter(new File(geodashDataDir, "dash-" + req.queryParams("dashID") + ".json"))) { dashboardFileWriter.write(dashboardObj.toString()); } catch (Exception e) { throw new RuntimeException(e); } if (req.queryParams("callback") != null) { return req.queryParams("callback").toString() + "()"; } else { return ""; } } public static String updateDashBoardWidgetByID(Request req, Response res) { try { deleteOrUpdate(req.queryParams("dashID"), req.params(":id"), req.queryParams("widgetJSON"), false); } catch (Exception e) { throw new RuntimeException(e); } if (req.queryParams("callback") != null) { return req.queryParams("callback").toString() + "()"; } else { return ""; } } public static String deleteDashBoardWidgetByID(Request req, Response res) { deleteOrUpdate(req.queryParams("dashID"), req.params(":id"), "", true); if (req.queryParams("callback") != null) { return req.queryParams("callback").toString() + "()"; } else { return ""; } } private static void deleteOrUpdate(String dashID, String ID, String widgetJSON, boolean delete) { try { String geodashDataDir = expandResourcePath("/public/json/"); if (geodashDataDir.indexOf("/") == 0) { geodashDataDir = geodashDataDir.substring(1); } JsonParser parser = new JsonParser(); JsonObject dashboardObj = new JsonObject(); JsonArray finalArr = new JsonArray(); FileSystem fs = FileSystems.getDefault(); Path path = fs.getPath(geodashDataDir + "dash-" + dashID + ".json"); int retries = 0; while (retries < 200) { try (FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE)) { FileLock lock = fileChannel.tryLock(); ByteBuffer buffer = ByteBuffer.allocate(2000); int noOfBytesRead = fileChannel.read(buffer); String jsonString = ""; while (noOfBytesRead != -1) { buffer.flip(); while (buffer.hasRemaining()) { jsonString += (char) buffer.get(); } buffer.clear(); noOfBytesRead = fileChannel.read(buffer); } dashboardObj = parser.parse(jsonString).getAsJsonObject(); JsonArray widgets = dashboardObj.getAsJsonArray("widgets"); for (int i = 0; i < widgets.size(); i++) { // **line 2** JsonObject childJSONObject = widgets.get(i).getAsJsonObject(); String wID = childJSONObject.get("id").getAsString(); if (wID.equals(ID)) { if (!delete) { JsonParser widgetParser = new JsonParser(); childJSONObject = widgetParser.parse(URLDecoder.decode(widgetJSON, "UTF-8")).getAsJsonObject(); finalArr.add(childJSONObject); } } else { finalArr.add(childJSONObject); } } dashboardObj.remove("widgets"); dashboardObj.add("widgets", finalArr); byte[] inputBytes = dashboardObj.toString().getBytes(); ByteBuffer buffer2 = ByteBuffer.wrap(inputBytes); fileChannel.truncate(0); fileChannel.write(buffer2); fileChannel.close(); retries = 201; } catch (Exception e) { retries++; } } } catch (Exception e) { throw new RuntimeException(e); } } }
// of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // File created: 2011-06-23 13:22:53 package fi.tkk.ics.hadoop.bam.cli.plugins; import java.io.File; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ChecksumFileSystem; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocalFileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapred.FileAlreadyExistsException; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import net.sf.picard.sam.ReservedTagConstants; import net.sf.samtools.util.BlockCompressedStreamConstants; import fi.tkk.ics.hadoop.bam.custom.hadoop.InputSampler; import fi.tkk.ics.hadoop.bam.custom.hadoop.TotalOrderPartitioner; import fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser; import fi.tkk.ics.hadoop.bam.custom.samtools.BAMFileWriter; import fi.tkk.ics.hadoop.bam.custom.samtools.SamFileHeaderMerger; import fi.tkk.ics.hadoop.bam.custom.samtools.SAMFileHeader; import fi.tkk.ics.hadoop.bam.custom.samtools.SAMFileReader; import fi.tkk.ics.hadoop.bam.custom.samtools.SAMRecord; import static fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser.Option.*; import fi.tkk.ics.hadoop.bam.AnySAMInputFormat; import fi.tkk.ics.hadoop.bam.KeyIgnoringBAMOutputFormat; import fi.tkk.ics.hadoop.bam.SAMRecordWritable; import fi.tkk.ics.hadoop.bam.cli.CLIPlugin; import fi.tkk.ics.hadoop.bam.cli.Utils; import fi.tkk.ics.hadoop.bam.util.Pair; import fi.tkk.ics.hadoop.bam.util.Timer; public final class Sort extends CLIPlugin { private static final List<Pair<CmdLineParser.Option, String>> optionDescs = new ArrayList<Pair<CmdLineParser.Option, String>>(); private static final CmdLineParser.Option verboseOpt = new BooleanOption('v', "verbose"), outputFileOpt = new StringOption('o', "output-file=PATH"), noTrustExtsOpt = new BooleanOption("no-trust-exts"); public Sort() { super("sort", "BAM sorting and merging", "2.0", "WORKDIR INPATH [INPATH...]", optionDescs, "Merges together the BAM and SAM files in the INPATHs, sorting the "+ "result, in a distributed fashion using Hadoop. Output parts are "+ "placed in WORKDIR in headerless BAM format."); } static { optionDescs.add(new Pair<CmdLineParser.Option, String>( verboseOpt, "tell the Hadoop job to be more verbose")); optionDescs.add(new Pair<CmdLineParser.Option, String>( outputFileOpt, "output a complete BAM file to the file PATH, "+ "removing the parts from WORKDIR")); optionDescs.add(new Pair<CmdLineParser.Option, String>( noTrustExtsOpt, "detect SAM/BAM files only by contents, "+ "never by file extension")); } @Override protected int run(CmdLineParser parser) { final List<String> args = parser.getRemainingArgs(); if (args.isEmpty()) { System.err.println("sort :: WORKDIR not given."); return 3; } if (args.size() == 1) { System.err.println("sort :: INPATH not given."); return 3; } final String wrkDir = args.get(0), out = (String)parser.getOptionValue(outputFileOpt); final List<String> strInputs = args.subList(1, args.size()); final List<Path> inputs = new ArrayList<Path>(strInputs.size()); for (final String in : strInputs) inputs.add(new Path(in)); final boolean verbose = parser.getBoolean(verboseOpt); final String intermediateOutName = (out == null ? inputs.get(0) : new Path(out)).getName(); final Configuration conf = getConf(); conf.setBoolean(AnySAMInputFormat.TRUST_EXTS_PROPERTY, !parser.getBoolean(noTrustExtsOpt)); // Used by getHeaderMerger. SortRecordReader needs it to correct the // reference indices when the output has a different index and // SortOutputFormat needs it to have the correct header for the output // records. conf.setStrings(INPUT_PATHS_PROP, strInputs.toArray(new String[0])); // Used by SortOutputFormat to name the output files. conf.set(SortOutputFormat.OUTPUT_NAME_PROP, intermediateOutName); final Path wrkDirPath = new Path(wrkDir); final Timer t = new Timer(); try { for (final Path in : inputs) Utils.configureSampling(in, conf); // As far as I can tell there's no non-deprecated way of getting this // info. We can silence this warning but not the import. @SuppressWarnings("deprecation") final int maxReduceTasks = new JobClient(new JobConf(conf)).getClusterStatus() .getMaxReduceTasks(); conf.setInt("mapred.reduce.tasks", Math.max(1, maxReduceTasks*9/10)); final Job job = new Job(conf); job.setJarByClass (Sort.class); job.setMapperClass (Mapper.class); job.setReducerClass(SortReducer.class); job.setMapOutputKeyClass(LongWritable.class); job.setOutputKeyClass (NullWritable.class); job.setOutputValueClass (SAMRecordWritable.class); job.setInputFormatClass (SortInputFormat.class); job.setOutputFormatClass(SortOutputFormat.class); for (final Path in : inputs) FileInputFormat.addInputPath(job, in); FileOutputFormat.setOutputPath(job, wrkDirPath); job.setPartitionerClass(TotalOrderPartitioner.class); System.out.println("sort :: Sampling..."); t.start(); InputSampler.<LongWritable,SAMRecordWritable>writePartitionFile( job, new InputSampler.IntervalSampler<LongWritable,SAMRecordWritable>( 0.01, 100)); System.out.printf("sort :: Sampling complete in %d.%03d s.\n", t.stopS(), t.fms()); job.submit(); System.out.println("sort :: Waiting for job completion..."); t.start(); if (!job.waitForCompletion(verbose)) { System.err.println("sort :: Job failed."); return 4; } System.out.printf("sort :: Job complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("sort :: Hadoop error: %s\n", e); return 4; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } if (out != null) try { System.out.println("sort :: Merging output..."); t.start(); final Path outPath = new Path(out); final FileSystem srcFS = wrkDirPath.getFileSystem(conf); FileSystem dstFS = outPath.getFileSystem(conf); // The checksummed local file system doesn't support append(). if (dstFS instanceof LocalFileSystem && dstFS instanceof ChecksumFileSystem) dstFS = ((LocalFileSystem)dstFS).getRaw(); // First, place the BAM header. final BAMFileWriter w = new BAMFileWriter(dstFS.create(outPath), new File("")); w.setSortOrder(SAMFileHeader.SortOrder.coordinate, true); w.setHeader(getHeaderMerger(conf).getMergedHeader()); w.close(); // Then, the BAM contents. final OutputStream outs = dstFS.append(outPath); final FileStatus[] parts = srcFS.globStatus(new Path( wrkDir, conf.get(SortOutputFormat.OUTPUT_NAME_PROP) + "-[0-9][0-9][0-9][0-9][0-9][0-9]*")); {int i = 0; final Timer t2 = new Timer(); for (final FileStatus part : parts) { t2.start(); final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, conf, false); ins.close(); System.out.printf("sort :: Merged part %d in %d.%03d s.\n", ++i, t2.stopS(), t2.fms()); }} for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); // Finally, the BGZF terminator. outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("sort :: Merging complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("sort :: Output merging failed: %s\n", e); return 5; } return 0; } private static final String INPUT_PATHS_PROP = "hadoopbam.sort.input.paths"; private static SamFileHeaderMerger headerMerger = null; public static SamFileHeaderMerger getHeaderMerger(Configuration conf) throws IOException { // TODO: it would be preferable to cache this beforehand instead of // having every task read the header block of every input file. But that // would be trickier, given that SamFileHeaderMerger isn't trivially // serializable. // Save it in a static field, though, in case that helps anything. if (headerMerger != null) return headerMerger; final List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>(); for (final String in : conf.getStrings(INPUT_PATHS_PROP)) { final Path p = new Path(in); final SAMFileReader r = new SAMFileReader(p.getFileSystem(conf).open(p)); headers.add(r.getFileHeader()); r.close(); } return headerMerger = new SamFileHeaderMerger( SAMFileHeader.SortOrder.coordinate, headers, true); } } final class SortReducer extends Reducer<LongWritable,SAMRecordWritable, NullWritable,SAMRecordWritable> { @Override protected void reduce( LongWritable ignored, Iterable<SAMRecordWritable> records, Reducer<LongWritable,SAMRecordWritable, NullWritable,SAMRecordWritable>.Context ctx) throws IOException, InterruptedException { for (SAMRecordWritable rec : records) ctx.write(NullWritable.get(), rec); } } // Because we want a total order and we may change the key when merging // headers, we can't use a mapper here: the InputSampler reads directly from // the InputFormat. final class SortInputFormat extends FileInputFormat<LongWritable,SAMRecordWritable> { private AnySAMInputFormat baseIF; private void initBaseIF(final Configuration conf) { baseIF = new AnySAMInputFormat(conf); } @Override public RecordReader<LongWritable,SAMRecordWritable> createRecordReader(InputSplit split, TaskAttemptContext ctx) throws InterruptedException, IOException { initBaseIF(ctx.getConfiguration()); final RecordReader<LongWritable,SAMRecordWritable> rr = new SortRecordReader(baseIF.createRecordReader(split, ctx)); rr.initialize(split, ctx); return rr; } @Override protected boolean isSplitable(JobContext job, Path path) { initBaseIF(job.getConfiguration()); return baseIF.isSplitable(job, path); } @Override public List<InputSplit> getSplits(JobContext job) throws IOException { initBaseIF(job.getConfiguration()); return baseIF.getSplits(job); } } final class SortRecordReader extends RecordReader<LongWritable,SAMRecordWritable> { private final RecordReader<LongWritable,SAMRecordWritable> baseRR; private SamFileHeaderMerger headerMerger; public SortRecordReader(RecordReader<LongWritable,SAMRecordWritable> rr) { baseRR = rr; } @Override public void initialize(InputSplit spl, TaskAttemptContext ctx) throws InterruptedException, IOException { headerMerger = Sort.getHeaderMerger(ctx.getConfiguration()); } @Override public void close() throws IOException { baseRR.close(); } @Override public float getProgress() throws InterruptedException, IOException { return baseRR.getProgress(); } @Override public LongWritable getCurrentKey() throws InterruptedException, IOException { return baseRR.getCurrentKey(); } @Override public SAMRecordWritable getCurrentValue() throws InterruptedException, IOException { return baseRR.getCurrentValue(); } @Override public boolean nextKeyValue() throws InterruptedException, IOException { if (!baseRR.nextKeyValue()) return false; final SAMRecord r = getCurrentValue().get(); final SAMFileHeader h = r.getHeader(); // Correct the reference indices, and thus the key, if necessary. if (headerMerger.hasMergedSequenceDictionary()) { final int ri = headerMerger.getMergedSequenceIndex( h, r.getReferenceIndex()); r.setReferenceIndex(ri); if (r.getReadPairedFlag()) r.setMateReferenceIndex(headerMerger.getMergedSequenceIndex( h, r.getMateReferenceIndex())); getCurrentKey().set((long)ri << 32 | r.getAlignmentStart() - 1); } // Correct the program group if necessary. if (headerMerger.hasProgramGroupCollisions()) { final String pg = (String)r.getAttribute( ReservedTagConstants.PROGRAM_GROUP_ID); if (pg != null) r.setAttribute( ReservedTagConstants.PROGRAM_GROUP_ID, headerMerger.getProgramGroupId(h, pg)); } // Correct the read group if necessary. if (headerMerger.hasReadGroupCollisions()) { final String rg = (String)r.getAttribute( ReservedTagConstants.READ_GROUP_ID); if (rg != null) r.setAttribute( ReservedTagConstants.READ_GROUP_ID, headerMerger.getProgramGroupId(h, rg)); } getCurrentValue().set(r); return true; } } final class SortOutputFormat extends KeyIgnoringBAMOutputFormat<NullWritable> { public static final String OUTPUT_NAME_PROP = "hadoopbam.sort.output.name"; @Override public RecordWriter<NullWritable,SAMRecordWritable> getRecordWriter(TaskAttemptContext context) throws IOException { if (super.header == null) super.header = Sort.getHeaderMerger( context.getConfiguration()).getMergedHeader(); return super.getRecordWriter(context); } @Override public Path getDefaultWorkFile( TaskAttemptContext context, String ext) throws IOException { String filename = context.getConfiguration().get(OUTPUT_NAME_PROP); String extension = ext.isEmpty() ? ext : "." + ext; int part = context.getTaskAttemptID().getTaskID().getId(); return new Path(super.getDefaultWorkFile(context, ext).getParent(), filename + "-" + String.format("%06d", part) + extension); } // Allow the output directory to exist. @Override public void checkOutputSpecs(JobContext job) throws FileAlreadyExistsException, IOException {} }
package ibis.io; import java.io.EOFException; import java.io.IOException; import java.io.InvalidObjectException; import java.io.NotActiveException; import java.io.NotSerializableException; import java.io.ObjectStreamClass; import java.io.Serializable; import java.io.StreamCorruptedException; import java.lang.reflect.Field; import sun.misc.Unsafe; /** * This is the <code>SerializationInputStream</code> version that is used * for Ibis serialization. */ public class IbisSerializationInputStream extends DataSerializationInputStream implements IbisStreamFlags { /** If <code>false</code>, makes all timer calls disappear. */ private static final boolean TIME_IBIS_SERIALIZATION = true; /** * Record how many objects of any class are sent the expensive way: * via the uninitialized native creator. */ private static final boolean STATS_NONREWRITTEN = properties.booleanProperty(s_stats_nonrewritten); // if STATS_NONREWRITTEN static java.util.Hashtable<Class, Integer> nonRewritten = new java.util.Hashtable<Class, Integer>(); // Only works as of Java 1.4, earlier versions of Java don't have Unsafe. private static Unsafe unsafe = null; static { try { // unsafe = Unsafe.getUnsafe(); // does not work when a classloader is present, so we get it // from ObjectStreamClass. Class cl = Class.forName("java.io.ObjectStreamClass$FieldReflector"); Field uf = cl.getDeclaredField("unsafe"); uf.setAccessible(true); unsafe = (Unsafe) uf.get(null); } catch (Exception e) { System.out.println("Got exception while getting unsafe: " + e); unsafe = null; } if (STATS_NONREWRITTEN) { System.out.println("IbisSerializationInputStream.STATS_NONREWRITTEN" + " enabled"); Runtime.getRuntime().addShutdownHook( new Thread("IbisSerializationInputStream ShutdownHook") { public void run() { System.out.print("Serializable objects created " + "nonrewritten: "); System.out.println(nonRewritten); } }); } } private static ClassLoader customClassLoader; /** List of objects, for cycle checking. */ private IbisVector objects; /** First free object index. */ private int next_handle; /** Handle to invalidate. */ private int unshared_handle = 0; /** First free type index. */ private int next_type = 1; /** List of types seen sofar. */ private IbisVector types; /** * There is a notion of a "current" object. This is needed when a * user-defined <code>readObject</code> refers to * <code>defaultReadObject</code> or to * <code>getFields</code>. */ Object current_object; /** * There also is a notion of a "current" level. * The "level" of a serializable class is computed as follows:<ul> * <li> if its superclass is serializable: the level of the superclass + 1. * <li> if its superclass is not serializable: 1. * </ul> * This level implies a level at which an object can be seen. The "current" * level is the level at which <code>current_object</code> is being * processed. */ int current_level; /** * The <code>current_object</code> and <code>current_level</code> * are maintained in * stacks, so that they can be managed by IOGenerator-generated code. */ private Object[] object_stack; private int[] level_stack; private int max_stack_size = 0; private int stack_size = 0; /** <code>AlternativeTypeInfo</code> for <code>boolean</code> arrays. */ private static AlternativeTypeInfo booleanArrayInfo = AlternativeTypeInfo.getAlternativeTypeInfo(classBooleanArray); /** <code>AlternativeTypeInfo</code> for <code>byte</code> arrays. */ private static AlternativeTypeInfo byteArrayInfo = AlternativeTypeInfo.getAlternativeTypeInfo(classByteArray); /** <code>AlternativeTypeInfo</code> for <code>char</code> arrays. */ private static AlternativeTypeInfo charArrayInfo = AlternativeTypeInfo.getAlternativeTypeInfo(classCharArray); /** <code>AlternativeTypeInfo</code> for <code>short</code> arrays. */ private static AlternativeTypeInfo shortArrayInfo = AlternativeTypeInfo.getAlternativeTypeInfo(classShortArray); /** <code>AlternativeTypeInfo</code> for <code>int</code> arrays. */ private static AlternativeTypeInfo intArrayInfo = AlternativeTypeInfo.getAlternativeTypeInfo(classIntArray); /** <code>AlternativeTypeInfo</code> for <code>long</code> arrays. */ private static AlternativeTypeInfo longArrayInfo = AlternativeTypeInfo.getAlternativeTypeInfo(classLongArray); /** <code>AlternativeTypeInfo</code> for <code>float</code> arrays. */ private static AlternativeTypeInfo floatArrayInfo = AlternativeTypeInfo.getAlternativeTypeInfo(classFloatArray); /** <code>AlternativeTypeInfo</code> for <code>double</code> arrays. */ private static AlternativeTypeInfo doubleArrayInfo = AlternativeTypeInfo.getAlternativeTypeInfo(classDoubleArray); static { String clName = System.getProperty(IOProps.s_classloader); if (clName != null) { //we try to instanciate it try { Class classDefinition = Class.forName(clName); customClassLoader = (ClassLoader) classDefinition.newInstance(); } catch (Exception e) { System.err.println("Warning: could not find or load custom " + "classloader " + clName); if (DEBUG) { e.printStackTrace(); } } } } /** * Constructor with a <code>DataInputStream</code>. * @param in the underlying <code>DataInputStream</code> * @exception IOException gets thrown when an IO error occurs. */ public IbisSerializationInputStream(DataInputStream in) throws IOException { super(in); objects = new IbisVector(1024); init(true); } /** * Constructor, may be used when this class is sub-classed. */ protected IbisSerializationInputStream() throws IOException { super(); objects = new IbisVector(1024); init(true); } public boolean reInitOnNewConnection() { return true; } /* * If you at some point want to override IbisSerializationOutputStream, * you probably need to override the methods from here on up until * comment tells you otherwise. */ public String serializationImplName() { return "ibis"; } public void close() throws IOException { super.close(); types = null; objects.clear(); } /* * If you are overriding IbisSerializationInputStream, * you can stop now :-) * The rest is built on top of these. */ public void readArray(boolean[] ref, int off, int len) throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } try { readArrayHeader(classBooleanArray, len); } catch (ClassNotFoundException e) { if (DEBUG) { dbPrint("Caught exception: " + e); e.printStackTrace(); dbPrint("now rethrow as SerializationError ..."); } throw new SerializationError("require boolean[]", e); } readBooleanArray(ref, off, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } } public void readArray(byte[] ref, int off, int len) throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } try { readArrayHeader(classByteArray, len); } catch (ClassNotFoundException e) { if (DEBUG) { dbPrint("Caught exception: " + e); e.printStackTrace(); dbPrint("now rethrow as SerializationError ..."); } throw new SerializationError("require byte[]", e); } readByteArray(ref, off, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } } public void readArray(char[] ref, int off, int len) throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } try { readArrayHeader(classCharArray, len); } catch (ClassNotFoundException e) { if (DEBUG) { dbPrint("Caught exception: " + e); e.printStackTrace(); dbPrint("now rethrow as SerializationError ..."); } throw new SerializationError("require char[]", e); } readCharArray(ref, off, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } } public void readArray(short[] ref, int off, int len) throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } try { readArrayHeader(classShortArray, len); } catch (ClassNotFoundException e) { if (DEBUG) { dbPrint("Caught exception: " + e); e.printStackTrace(); dbPrint("now rethrow as SerializationError ..."); } throw new SerializationError("require short[]", e); } readShortArray(ref, off, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } } public void readArray(int[] ref, int off, int len) throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } try { readArrayHeader(classIntArray, len); } catch (ClassNotFoundException e) { if (DEBUG) { dbPrint("Caught exception: " + e); e.printStackTrace(); dbPrint("now rethrow as SerializationError ..."); } throw new SerializationError("require int[]", e); } readIntArray(ref, off, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } } public void readArray(long[] ref, int off, int len) throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } try { readArrayHeader(classLongArray, len); } catch (ClassNotFoundException e) { if (DEBUG) { dbPrint("Caught exception: " + e); e.printStackTrace(); dbPrint("now rethrow as SerializationError ..."); } throw new SerializationError("require long[]", e); } readLongArray(ref, off, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } } public void readArray(float[] ref, int off, int len) throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } try { readArrayHeader(classFloatArray, len); } catch (ClassNotFoundException e) { if (DEBUG) { dbPrint("Caught exception: " + e); e.printStackTrace(); dbPrint("now rethrow as SerializationError ..."); } throw new SerializationError("require float[]", e); } readFloatArray(ref, off, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } } public void readArray(double[] ref, int off, int len) throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } try { readArrayHeader(classDoubleArray, len); } catch (ClassNotFoundException e) { if (DEBUG) { dbPrint("Caught exception: " + e); e.printStackTrace(); dbPrint("now rethrow as SerializationError ..."); } throw new SerializationError("require double[]", e); } readDoubleArray(ref, off, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } } public void readArray(Object[] ref, int off, int len) throws IOException, ClassNotFoundException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } readArrayHeader(ref.getClass(), len); for (int i = off; i < off + len; i++) { ref[i] = doReadObject(false); } if (TIME_IBIS_SERIALIZATION) { stopTimer(); } } /** * Allocates and reads an array of bytes from the input stream. * This method is used by IOGenerator-generated code. * @return the array read. * @exception IOException in case of error. */ public byte[] readArrayByte() throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } int len = readInt(); byte[] b = new byte[len]; addObjectToCycleCheck(b); readByteArray(b, 0, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return b; } /** * See {@link #readArrayByte()}, this one is for an array of boolans. */ public boolean[] readArrayBoolean() throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } int len = readInt(); boolean[] b = new boolean[len]; addObjectToCycleCheck(b); readBooleanArray(b, 0, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return b; } /** * See {@link #readArrayByte()}, this one is for an array of chars. */ public char[] readArrayChar() throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } int len = readInt(); char[] b = new char[len]; addObjectToCycleCheck(b); readCharArray(b, 0, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return b; } /** * See {@link #readArrayByte()}, this one is for an array of shorts. */ public short[] readArrayShort() throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } int len = readInt(); short[] b = new short[len]; addObjectToCycleCheck(b); readShortArray(b, 0, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return b; } /** * See {@link #readArrayByte()}, this one is for an array of ints. */ public int[] readArrayInt() throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } int len = readInt(); int[] b = new int[len]; addObjectToCycleCheck(b); readIntArray(b, 0, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return b; } /** * See {@link #readArrayByte()}, this one is for an array of longs. */ public long[] readArrayLong() throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } int len = readInt(); long[] b = new long[len]; addObjectToCycleCheck(b); readLongArray(b, 0, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return b; } /** * See {@link #readArrayByte()}, this one is for an array of floats. */ public float[] readArrayFloat() throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } int len = readInt(); float[] b = new float[len]; addObjectToCycleCheck(b); readFloatArray(b, 0, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return b; } /** * See {@link #readArrayByte()}, this one is for an array of doubles. */ public double[] readArrayDouble() throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } int len = readInt(); double[] b = new double[len]; addObjectToCycleCheck(b); readDoubleArray(b, 0, len); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return b; } /** * Initializes the <code>objects</code> and <code>types</code> fields, * including their indices. * * @param do_types set when the type table must be initialized as well * (this is not needed after a reset). */ private void init(boolean do_types) { if (do_types) { types = new IbisVector(); types.add(0, null); // Vector requires this types.add(TYPE_BOOLEAN, booleanArrayInfo); types.add(TYPE_BYTE, byteArrayInfo); types.add(TYPE_CHAR, charArrayInfo); types.add(TYPE_SHORT, shortArrayInfo); types.add(TYPE_INT, intArrayInfo); types.add(TYPE_LONG, longArrayInfo); types.add(TYPE_FLOAT, floatArrayInfo); types.add(TYPE_DOUBLE, doubleArrayInfo); next_type = PRIMITIVE_TYPES; } objects.clear(); next_handle = CONTROL_HANDLES; } /** * resets the stream, by clearing the object and type table. */ private void do_reset(boolean cleartypes) { if (DEBUG) { dbPrint("received reset: next handle = " + next_handle + "."); } init(cleartypes); } public void clear() { if (DEBUG) { dbPrint("explicit clear: next handle = " + next_handle + "."); } init(false); } public void statistics() { System.err.println("IbisSerializationInputStream: " + "statistics() not yet implemented"); } /* This is the data output / object output part */ /** * Reads a handle, which is just an int representing an index * in the object table. * @exception IOException gets thrown when an IO error occurs. * @return the handle read. */ private final int readHandle() throws IOException { int handle = readInt(); /* this replaces the checks for the reset handle everywhere else. --N */ for (;;) { if (handle == RESET_HANDLE) { if (DEBUG) { dbPrint("received a RESET"); } do_reset(false); handle = readInt(); } else if (handle == CLEAR_HANDLE) { if (DEBUG) { dbPrint("received a CLEAR"); } do_reset(true); handle = readInt(); } else { break; } } if (DEBUG) { dbPrint("read handle " + handle); } return handle; } /** * Reads a <code>Class</code> object from the stream and tries to load it. * @exception IOException when an IO error occurs. * @exception ClassNotFoundException when the class could not be loaded. * @return the <code>Class</code> object read. */ public Class readClass() throws IOException, ClassNotFoundException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } int handle = readHandle(); if (handle == NUL_HANDLE) { if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return null; } if ((handle & TYPE_BIT) == 0) { /* Ah, it's a handle. Look it up, return the stored ptr */ Class o = (Class) objects.get(handle); if (DEBUG) { dbPrint("readobj: handle = " + (handle - CONTROL_HANDLES) + " obj = " + o); } return o; } readType(handle & TYPE_MASK); String s = readUTF(); Class c = getClassFromName(s); addObjectToCycleCheck(c); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return c; } /** * Reads the header of an array. * This header consists of a handle, a type, and an integer representing * the length. * Note that the data read is mostly redundant. * * @exception IOException when an IO error occurs. * @exception ClassNotFoundException when the array class could * not be loaded. */ void readArrayHeader(Class<?> clazz, int len) throws IOException, ClassNotFoundException { if (DEBUG) { dbPrint("readArrayHeader: class = " + clazz.getName() + " len = " + len); } int type = readHandle(); if ((type & TYPE_BIT) == 0) { throw new StreamCorruptedException( "Array slice header but I receive a HANDLE!"); } Class in_clazz = readType(type & TYPE_MASK).clazz; int in_len = readInt(); if (ASSERTS && !clazz.isAssignableFrom(in_clazz)) { throw new ClassCastException("Cannot assign class " + clazz + " from read class " + in_clazz); } if (ASSERTS && in_len != len) { throw new ArrayIndexOutOfBoundsException("Cannot read " + in_len + " into " + len + " elements"); } } /** * Adds an object <code>o</code> to the object table, for cycle checking. * This method is public because it gets called from IOGenerator-generated * code. * @param o the object to be added */ public void addObjectToCycleCheck(Object o) { if (DEBUG) { dbPrint("addObjectToCycleCheck: handle = " + next_handle); } if (unshared_handle == next_handle) { objects.add(next_handle, null); unshared_handle = 0; } else { objects.add(next_handle, o); } next_handle++; } /** * Looks up an object in the object table. * This method is public because it gets called from IOGenerator-generated * code. * @param handle the handle of the object to be looked up * @return the corresponding object. */ public Object getObjectFromCycleCheck(int handle) { Object o = objects.get(handle); // - CONTROL_HANDLES); if (DEBUG) { dbPrint("getObjectFromCycleCheck: handle = " + handle); } return o; } /** * Method used by IOGenerator-generated code to read a handle, and * determine if it has to read a new object or get one from the object * table. * * @exception IOException when an IO error occurs. * @return 0 for a null object, -1 for a new object, and the handle for an * object already in the object table. */ public final int readKnownTypeHeader() throws IOException, ClassNotFoundException { int handle_or_type = readHandle(); if ((handle_or_type & TYPE_BIT) == 0) { // Includes NUL_HANDLE. if (DEBUG) { if (handle_or_type == NUL_HANDLE) { dbPrint("readKnownTypeHeader -> read NUL_HANDLE"); } else { dbPrint("readKnownTypeHeader -> read OLD HANDLE " + handle_or_type); } } return handle_or_type; } handle_or_type &= TYPE_MASK; if (handle_or_type >= next_type) { readType(handle_or_type); } if (DEBUG) { AlternativeTypeInfo t = (AlternativeTypeInfo) types.get(handle_or_type); dbPrint("readKnownTypeHeader -> reading NEW object, class = " + t.clazz.getName()); } return -1; } /** * Reads an array from the stream. * The handle and type have already been read. * * @param clazz the type of the array to be read * @param type an index in the types table, but * also an indication of the base type of * the array * * @exception IOException when an IO error occurs. * @exception ClassNotFoundException when element type is Object and * readObject throws it. * * @return the array read. */ Object readArray(Class clazz, int type) throws IOException, ClassNotFoundException { if (DEBUG) { if (clazz != null) { dbPrint("readArray " + clazz.getName() + " type " + type); } } switch (type) { case TYPE_BOOLEAN: return readArrayBoolean(); case TYPE_BYTE: return readArrayByte(); case TYPE_SHORT: return readArrayShort(); case TYPE_CHAR: return readArrayChar(); case TYPE_INT: return readArrayInt(); case TYPE_LONG: return readArrayLong(); case TYPE_FLOAT: return readArrayFloat(); case TYPE_DOUBLE: return readArrayDouble(); default: int len = readInt(); Object ref = java.lang.reflect.Array.newInstance( clazz.getComponentType(), len); addObjectToCycleCheck(ref); for (int i = 0; i < len; i++) { Object o = doReadObject(false); ((Object[]) ref)[i] = o; } return ref; } } /** * This method tries to load a class given its name. It tries the * default classloader, and the one from the thread context. Also, * apparently some classloaders do not understand array classes, and * from the Java documentation, it is not clear that they should. * Therefore, if the typeName indicates an array type, and the * obvious attempts to load the class fail, this method also tries * to load the base type of the array. * * @param typeName the name of the type to be loaded * @exception ClassNotFoundException is thrown when the class could * not be loaded. * @return the loaded class */ Class getClassFromName(String typeName) throws ClassNotFoundException { try { return Class.forName(typeName); } catch (ClassNotFoundException e) { try { if (DEBUG) { dbPrint("Could not load class " + typeName + " using Class.forName(), trying " + "Thread.currentThread()." + "getContextClassLoader().loadClass()"); dbPrint("Default class loader is " + this.getClass().getClassLoader()); dbPrint("now trying " + Thread.currentThread().getContextClassLoader()); } return Thread.currentThread().getContextClassLoader() .loadClass(typeName); } catch (ClassNotFoundException e2) { int dim = 0; /* Some classloaders are not able to load array classes. * Therefore, if the name * describes an array, try again with the base type. */ if (typeName.length() > 0 && typeName.charAt(0) == '[') { char[] s = typeName.toCharArray(); while (dim < s.length && s[dim] == '[') { dim++; } int begin = dim; int end = s.length; if (dim < s.length && s[dim] == 'L') { begin++; } if (s[end - 1] == ';') { end } typeName = typeName.substring(begin, end); int dims[] = new int[dim]; for (int i = 0; i < dim; i++) dims[i] = 0; /* Now try to load the base class, create an array * from it and then return its class. */ return java.lang.reflect.Array.newInstance( getClassFromName(typeName), dims).getClass(); } return loadClassFromCustomCL(typeName); } } } private Class loadClassFromCustomCL(String className) throws ClassNotFoundException { if (DEBUG) { System.out.println("loadClassTest " + className); } if (customClassLoader == null) { throw new ClassNotFoundException(className); } if (DEBUG) { System.out.println("******* Calling custom classloader"); } return customClassLoader.loadClass(className); } /** * Returns the <code>AlternativeTypeInfo</code> corresponding to the type * number given as parameter. * If the parameter indicates a type not yet read, its name is read * (as an UTF), and the class is loaded. * * @param type the type number * @exception ClassNotFoundException is thrown when the class could * not be loaded. * @exception IOException is thrown when an IO error occurs * @return the <code>AlternativeTypeInfo</code> for <code>type</code>. */ private AlternativeTypeInfo readType(int type) throws IOException, ClassNotFoundException { if (type < next_type) { if (DEBUG) { dbPrint("read type number 0x" + Integer.toHexString(type)); } return (AlternativeTypeInfo) types.get(type); } if (next_type != type) { throw new SerializationError("Internal error: next_type = " + next_type + ", type = " + type); } String typeName = readUTF(); if (DEBUG) { dbPrint("read NEW type number 0x" + Integer.toHexString(type) + " type " + typeName); } Class clazz = getClassFromName(typeName); AlternativeTypeInfo t = AlternativeTypeInfo.getAlternativeTypeInfo(clazz); types.add(next_type, t); next_type++; return t; } /** * Native methods needed for assigning to final fields of objects that are * not rewritten. */ private native void setFieldDouble(Object ref, String fieldname, double d); private native void setFieldLong(Object ref, String fieldname, long l); private native void setFieldFloat(Object ref, String fieldname, float f); private native void setFieldInt(Object ref, String fieldname, int i); private native void setFieldShort(Object ref, String fieldname, short s); private native void setFieldChar(Object ref, String fieldname, char c); private native void setFieldByte(Object ref, String fieldname, byte b); private native void setFieldBoolean(Object ref, String fieldname, boolean b); private native void setFieldObject(Object ref, String fieldname, String osig, Object o); /** * This method reads a value from the stream and assigns it to a * final field. * IOGenerator uses this method when assigning final fields of an * object that is rewritten, but super is not, and super is serializable. * The problem with this situation is that IOGenerator cannot create * a proper constructor for this object, so cannot assign * to final fields without falling back to native code. * * @param ref object with a final field * @param fieldname name of the field * @exception IOException is thrown when an IO error occurs. */ public void readFieldDouble(Object ref, String fieldname) throws IOException { double d = readDouble(); if (unsafe != null) { Class cl = ref.getClass(); try { Field f = cl.getDeclaredField(fieldname); long key = unsafe.objectFieldOffset(f); unsafe.putDouble(ref, key, d); return; } catch (Exception e) { // throw new InternalError("No such field " + fieldname // + " in " cl.getName()); } } setFieldDouble(ref, fieldname, d); } /** * See {@link #readFieldDouble(Object, String)} for a description. */ public void readFieldLong(Object ref, String fieldname) throws IOException { long d = readLong(); if (unsafe != null) { Class cl = ref.getClass(); try { Field f = cl.getDeclaredField(fieldname); long key = unsafe.objectFieldOffset(f); unsafe.putLong(ref, key, d); return; } catch (Exception e) { // throw new InternalError("No such field " + fieldname // + " in " cl.getName()); } } setFieldLong(ref, fieldname, d); } /** * See {@link #readFieldDouble(Object, String)} for a description. */ public void readFieldFloat(Object ref, String fieldname) throws IOException { float d = readFloat(); if (unsafe != null) { Class cl = ref.getClass(); try { Field f = cl.getDeclaredField(fieldname); long key = unsafe.objectFieldOffset(f); unsafe.putFloat(ref, key, d); return; } catch (Exception e) { // throw new InternalError("No such field " + fieldname // + " in " cl.getName()); } } setFieldFloat(ref, fieldname, d); } /** * See {@link #readFieldDouble(Object, String)} for a description. */ public void readFieldInt(Object ref, String fieldname) throws IOException { int d = readInt(); if (unsafe != null) { Class cl = ref.getClass(); try { Field f = cl.getDeclaredField(fieldname); long key = unsafe.objectFieldOffset(f); unsafe.putInt(ref, key, d); return; } catch (Exception e) { // throw new InternalError("No such field " + fieldname // + " in " cl.getName()); } } setFieldInt(ref, fieldname, d); } /** * See {@link #readFieldDouble(Object, String)} for a description. */ public void readFieldShort(Object ref, String fieldname) throws IOException { short d = readShort(); if (unsafe != null) { Class cl = ref.getClass(); try { Field f = cl.getDeclaredField(fieldname); long key = unsafe.objectFieldOffset(f); unsafe.putShort(ref, key, d); return; } catch (Exception e) { // throw new InternalError("No such field " + fieldname // + " in " cl.getName()); } } setFieldShort(ref, fieldname, d); } /** * See {@link #readFieldDouble(Object, String)} for a description. */ public void readFieldChar(Object ref, String fieldname) throws IOException { char d = readChar(); if (unsafe != null) { Class cl = ref.getClass(); try { Field f = cl.getDeclaredField(fieldname); long key = unsafe.objectFieldOffset(f); unsafe.putChar(ref, key, d); return; } catch (Exception e) { // throw new InternalError("No such field " + fieldname // + " in " cl.getName()); } } setFieldChar(ref, fieldname, d); } /** * See {@link #readFieldDouble(Object, String)} for a description. */ public void readFieldByte(Object ref, String fieldname) throws IOException { byte d = readByte(); if (unsafe != null) { Class cl = ref.getClass(); try { Field f = cl.getDeclaredField(fieldname); long key = unsafe.objectFieldOffset(f); unsafe.putByte(ref, key, d); return; } catch (Exception e) { // throw new InternalError("No such field " + fieldname // + " in " cl.getName()); } } setFieldByte(ref, fieldname, d); } /** * See {@link #readFieldDouble(Object, String)} for a description. */ public void readFieldBoolean(Object ref, String fieldname) throws IOException { boolean d = readBoolean(); if (unsafe != null) { Class cl = ref.getClass(); try { Field f = cl.getDeclaredField(fieldname); long key = unsafe.objectFieldOffset(f); unsafe.putBoolean(ref, key, d); return; } catch (Exception e) { // throw new InternalError("No such field " + fieldname // + " in " cl.getName()); } } setFieldBoolean(ref, fieldname, d); } /** * See {@link #readFieldDouble(Object, String)} for a description. */ public void readFieldString(Object ref, String fieldname) throws IOException { String d = readString(); if (unsafe != null) { Class cl = ref.getClass(); try { Field f = cl.getDeclaredField(fieldname); long key = unsafe.objectFieldOffset(f); unsafe.putObject(ref, key, d); return; } catch (Exception e) { // throw new InternalError("No such field " + fieldname // + " in " cl.getName()); } } setFieldObject(ref, fieldname, "Ljava/lang/String;", d); } /** * See {@link #readFieldDouble(Object, String)} for a description. * @exception ClassNotFoundException when the class could not be loaded. */ public void readFieldClass(Object ref, String fieldname) throws IOException, ClassNotFoundException { Class d = readClass(); if (unsafe != null) { Class cl = ref.getClass(); try { Field f = cl.getDeclaredField(fieldname); long key = unsafe.objectFieldOffset(f); unsafe.putObject(ref, key, d); return; } catch (Exception e) { // throw new InternalError("No such field " + fieldname // + " in " cl.getName()); } } setFieldObject(ref, fieldname, "Ljava/lang/Class;", d); } /** * See {@link #readFieldDouble(Object, String)} for a description. * @param fieldsig signature of the field * @exception ClassNotFoundException when readObject throws it. */ public void readFieldObject(Object ref, String fieldname, String fieldsig) throws IOException, ClassNotFoundException { Object d = doReadObject(false); if (unsafe != null) { Class cl = ref.getClass(); try { Field f = cl.getDeclaredField(fieldname); if (d != null && !f.getType().isInstance(d)) { throw new ClassCastException("wrong field type"); } long key = unsafe.objectFieldOffset(f); unsafe.putObject(ref, key, d); return; } catch (ClassCastException e) { throw e; } catch (Exception e) { // throw new InternalError("No such field " + fieldname // + " in " cl.getName()); } } setFieldObject(ref, fieldname, fieldsig, d); } void alternativeDefaultReadObject(AlternativeTypeInfo t, Object ref) throws ClassNotFoundException, IllegalAccessException, IOException { int temp = 0; if (DEBUG) { dbPrint("alternativeDefaultReadObject, class = " + t.clazz.getName()); } for (int i = 0; i < t.double_count; i++) { if (t.fields_final[temp]) { readFieldDouble(ref, t.serializable_fields[temp].getName()); } else { t.serializable_fields[temp].setDouble(ref, readDouble()); } temp++; } for (int i = 0; i < t.long_count; i++) { if (t.fields_final[temp]) { readFieldLong(ref, t.serializable_fields[temp].getName()); } else { t.serializable_fields[temp].setLong(ref, readLong()); } temp++; } for (int i = 0; i < t.float_count; i++) { if (t.fields_final[temp]) { readFieldFloat(ref, t.serializable_fields[temp].getName()); } else { t.serializable_fields[temp].setFloat(ref, readFloat()); } temp++; } for (int i = 0; i < t.int_count; i++) { if (t.fields_final[temp]) { readFieldInt(ref, t.serializable_fields[temp].getName()); } else { t.serializable_fields[temp].setInt(ref, readInt()); } temp++; } for (int i = 0; i < t.short_count; i++) { if (t.fields_final[temp]) { readFieldShort(ref, t.serializable_fields[temp].getName()); } else { t.serializable_fields[temp].setShort(ref, readShort()); } temp++; } for (int i = 0; i < t.char_count; i++) { if (t.fields_final[temp]) { readFieldChar(ref, t.serializable_fields[temp].getName()); } else { t.serializable_fields[temp].setChar(ref, readChar()); } temp++; } for (int i = 0; i < t.byte_count; i++) { if (t.fields_final[temp]) { readFieldByte(ref, t.serializable_fields[temp].getName()); } else { t.serializable_fields[temp].setByte(ref, readByte()); } temp++; } for (int i = 0; i < t.boolean_count; i++) { if (t.fields_final[temp]) { readFieldBoolean(ref, t.serializable_fields[temp].getName()); } else { t.serializable_fields[temp].setBoolean(ref, readBoolean()); } temp++; } for (int i = 0; i < t.reference_count; i++) { if (t.fields_final[temp]) { String fieldname = t.serializable_fields[temp].getName(); String fieldtype = t.serializable_fields[temp].getType().getName(); if (fieldtype.startsWith("[")) { // do nothing } else { fieldtype = "L" + fieldtype.replace('.', '/') + ";"; } // dbPrint("fieldname = " + fieldname); // dbPrint("signature = " + fieldtype); readFieldObject(ref, fieldname, fieldtype); } else { Object o = doReadObject(false); if (DEBUG) { if (o == null) { dbPrint("Assigning null to field " + t.serializable_fields[temp].getName()); } else { dbPrint("Assigning an object of type " + o.getClass().getName() + " to field " + t.serializable_fields[temp].getName()); } } t.serializable_fields[temp].set(ref, o); } temp++; } } void alternativeReadObject(AlternativeTypeInfo t, Object ref) throws ClassNotFoundException, IllegalAccessException, IOException { if (t.superSerializable) { alternativeReadObject(t.alternativeSuperInfo, ref); } if (t.hasReadObject) { current_level = t.level; try { if (DEBUG) { dbPrint("invoking readObject() of class " + t.clazz.getName()); } t.invokeReadObject(ref, getJavaObjectInputStream()); if (DEBUG) { dbPrint("done with readObject() of class " + t.clazz.getName()); } } catch (java.lang.reflect.InvocationTargetException e) { if (DEBUG) { dbPrint("Caught exception: " + e); e.printStackTrace(); } Throwable cause = e.getTargetException(); if (cause instanceof Error) { throw (Error) cause; } if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } if (cause instanceof IOException) { throw (IOException) cause; } if (cause instanceof ClassNotFoundException) { throw (ClassNotFoundException) cause; } if (DEBUG) { dbPrint("now rethrow as IllegalAccessException ..."); } throw new IllegalAccessException("readObject method: " + e); } return; } alternativeDefaultReadObject(t, ref); } /** * This method takes care of reading the serializable fields of the * parent object, and also those of its parent objects. * Its gets called by IOGenerator-generated code when an object * has a superclass that is serializable but not Ibis serializable. * * @param ref the object with a non-Ibis-serializable parent object * @param classname the name of the superclass * @exception IOException gets thrown on IO error * @exception ClassNotFoundException when readObject throws it. */ public void readSerializableObject(Object ref, String classname) throws ClassNotFoundException, IOException { AlternativeTypeInfo t = AlternativeTypeInfo.getAlternativeTypeInfo(classname); push_current_object(ref, 0); try { alternativeReadObject(t, ref); } catch (IllegalAccessException e) { if (DEBUG) { dbPrint("Caught exception: " + e); e.printStackTrace(); dbPrint("now rethrow as NotSerializableException ..."); } throw new NotSerializableException(classname + " " + e); } pop_current_object(); } /** * This method reads the serializable fields of object <code>ref</code> * at the level indicated by <code>depth</code> (see the explanation at * the declaration of the <code>current_level</code> field. * It gets called from IOGenerator-generated code, when a parent object * is serializable but not Ibis serializable. * * @param ref the object of which serializable fields must be written * @param depth an indication of the current "view" of the object * @exception IOException gets thrown when an IO error occurs. * @exception ClassNotFoundException when readObject throws it. */ public void defaultReadSerializableObject(Object ref, int depth) throws ClassNotFoundException, IOException { Class type = ref.getClass(); AlternativeTypeInfo t = AlternativeTypeInfo.getAlternativeTypeInfo(type); /* Find the type info corresponding to the current invocation. See the invokeReadObject invocation in alternativeReadObject. */ while (t.level > depth) { t = t.alternativeSuperInfo; } try { alternativeDefaultReadObject(t, ref); } catch (IllegalAccessException e) { if (DEBUG) { dbPrint("Caught exception: " + e); e.printStackTrace(); dbPrint("now rethrow as NotSerializableException ..."); } throw new NotSerializableException(type + " " + e); } } /** * Native method for creating an uninitialized object. * We need such a method to call the right constructor for it, * which is the parameter-less constructor of the "highest" superclass * that is not serializable. * @param type the type of the object to be created * @param non_serializable_super the "highest" superclass of * <code>type</code> that is not serializable * @return the object created */ private native Object createUninitializedObject(Class type, Class non_serializable_super); /** * Creates an uninitialized object of the type indicated by * <code>classname</code>. * The corresponding constructor called is the parameter-less * constructor of the "highest" superclass that is not serializable. * * @param classname name of the class * @exception ClassNotFoundException when class <code>classname</code> * cannot be loaded. */ public Object create_uninitialized_object(String classname) throws ClassNotFoundException { Class clazz = getClassFromName(classname); return create_uninitialized_object(clazz); } Object create_uninitialized_object(Class clazz) { AlternativeTypeInfo t = AlternativeTypeInfo.getAlternativeTypeInfo(clazz); if (STATS_NONREWRITTEN) { Integer n = nonRewritten.get(clazz); if (n == null) { n = new Integer(1); } else { n = new Integer(n.intValue() + 1); } nonRewritten.put(clazz, n); } Object o = t.newInstance(); if (o != null) { addObjectToCycleCheck(o); return o; } Class t2 = clazz; while (Serializable.class.isAssignableFrom(t2)) { /* Find first non-serializable super-class. */ t2 = t2.getSuperclass(); } // Calls constructor for non-serializable superclass. try { Object obj = createUninitializedObject(clazz, t2); addObjectToCycleCheck(obj); return obj; } catch (Throwable thro) { thro.printStackTrace(); System.err.println("class: " + clazz.getName() + ",superclass: " + t2.getName()); throw new RuntimeException(); } } /** * Push the notions of <code>current_object</code> and * <code>current_level</code> on their stacks, and set new ones. * @param ref the new <code>current_object</code> notion * @param level the new <code>current_level</code> notion */ public void push_current_object(Object ref, int level) { if (stack_size >= max_stack_size) { max_stack_size = 2 * max_stack_size + 10; Object[] new_o_stack = new Object[max_stack_size]; int[] new_l_stack = new int[max_stack_size]; for (int i = 0; i < stack_size; i++) { new_o_stack[i] = object_stack[i]; new_l_stack[i] = level_stack[i]; } object_stack = new_o_stack; level_stack = new_l_stack; } object_stack[stack_size] = current_object; level_stack[stack_size] = current_level; stack_size++; current_object = ref; current_level = level; } /** * Pop the notions of <code>current_object</code> and * <code>current_level</code> from their stacks. */ public void pop_current_object() { stack_size current_object = object_stack[stack_size]; current_level = level_stack[stack_size]; // Don't keep references around ... object_stack[stack_size] = null; } /** * Reads and returns a <code>String</code> object. This is a special case, * because strings are written as an UTF. * * @exception IOException gets thrown on IO error * @return the string read. */ public String readString() throws IOException { if (TIME_IBIS_SERIALIZATION) { startTimer(); } int handle = readHandle(); if (handle == NUL_HANDLE) { if (DEBUG) { dbPrint("readString: --> null"); } if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return null; } if ((handle & TYPE_BIT) == 0) { /* Ah, it's a handle. Look it up, return the stored ptr */ String o = (String) objects.get(handle); if (DEBUG) { dbPrint("readString: duplicate handle = " + handle + " string = " + o); } if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return o; } try { readType(handle & TYPE_MASK); } catch (ClassNotFoundException e) { if (DEBUG) { dbPrint("Caught exception: " + e); e.printStackTrace(); dbPrint("now rethrow as SerializationError ..."); } throw new SerializationError("Cannot find java.lang.String?", e); } String s = readUTF(); if (DEBUG) { dbPrint("readString returns " + s); } addObjectToCycleCheck(s); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return s; } public Object readObject() throws IOException, ClassNotFoundException { return doReadObject(false); } final Object doReadObject(boolean unshared) throws IOException, ClassNotFoundException { /* * ref < 0: type * ref = 0: null ptr * ref > 0: handle */ if (TIME_IBIS_SERIALIZATION) { startTimer(); } int handle_or_type = readHandle(); if (handle_or_type == NUL_HANDLE) { if (TIME_IBIS_SERIALIZATION) { stopTimer(); } return null; } if ((handle_or_type & TYPE_BIT) == 0) { // Ah, it's a handle. Look it up, return the stored ptr, // unless it should be unshared. if (unshared) { if (TIME_IBIS_SERIALIZATION) { stopTimer(); } throw new InvalidObjectException( "readUnshared got a handle instead of an object"); } Object o = objects.get(handle_or_type); if (DEBUG) { dbPrint("readObject: duplicate handle " + handle_or_type + " class = " + o.getClass()); } if (TIME_IBIS_SERIALIZATION) { stopTimer(); } if (o == null) { throw new InvalidObjectException( "readObject got handle " + handle_or_type + " to unshared object"); } return o; } if (unshared) { unshared_handle = next_handle; } int type = handle_or_type & TYPE_MASK; AlternativeTypeInfo t = readType(type); if (DEBUG) { dbPrint("start readObject of class " + t.clazz.getName() + " handle = " + next_handle); } Object obj = t.reader.readObject(this, t, type); if (TIME_IBIS_SERIALIZATION) { stopTimer(); } if (DEBUG) { dbPrint("finished readObject of class " + t.clazz.getName()); } return obj; } private JavaObjectInputStream objectStream = null; public java.io.ObjectInputStream getJavaObjectInputStream() throws IOException { if (objectStream == null) { objectStream = new JavaObjectInputStream(this); } return objectStream; } private class JavaObjectInputStream extends java.io.ObjectInputStream { IbisSerializationInputStream ibisStream; JavaObjectInputStream(IbisSerializationInputStream s) throws IOException { super(); ibisStream = s; } public int available() throws IOException { return ibisStream.available(); } public void close() throws IOException { ibisStream.close(); } public int read() throws IOException { int b; try { b = ibisStream.readByte(); return b & 0377; } catch(EOFException e) { return -1; } } public int read(byte[] b) throws IOException { return read(b, 0, b.length); } public int read(byte[] b, int off, int len) throws IOException { ibisStream.readArray(b, off, len); return len; } public Object readObjectOverride() throws IOException, ClassNotFoundException { return ibisStream.doReadObject(false); } /** * Ignored for Ibis serialization. */ protected void readStreamHeader() { // ignored } protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { Class cl = ibisStream.readClass(); if (cl == null) { return null; } return ObjectStreamClass.lookup(cl); } public void readFully(byte[] b) throws IOException { ibisStream.readArray(b); } public void readFully(byte[] b, int off, int len) throws IOException { ibisStream.readArray(b, off, len); } public String readLine() throws IOException { // Now really deprecated :-) return null; } public Object readUnshared() throws IOException, ClassNotFoundException { return doReadObject(true); } public void registerValidation(java.io.ObjectInputValidation obj, int prio) throws NotActiveException, InvalidObjectException { if (current_object != obj) { throw new NotActiveException("not in readObject"); } throw new SerializationError("registerValidation not implemented"); } public Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { return desc.forClass(); } public int skipBytes(int len) throws IOException { throw new SerializationError("skipBytes not implemented"); } public long skip(long len) throws IOException { throw new SerializationError("skip not implemented"); } public boolean markSupported() { return false; } public void mark(int readLimit) { // nothing } public void reset() throws IOException { throw new IOException("mark/reset not supported"); } public GetField readFields() throws IOException, ClassNotFoundException { if (current_object == null) { throw new NotActiveException("not in readObject"); } Class type = current_object.getClass(); AlternativeTypeInfo t = AlternativeTypeInfo.getAlternativeTypeInfo(type); ImplGetField current_getfield = new ImplGetField(t); current_getfield.readFields(); return current_getfield; } /** * The Ibis serialization implementation of <code>GetField</code>. */ private class ImplGetField extends GetField { private double[] doubles; private long[] longs; private int[] ints; private float[] floats; private short[] shorts; private char[] chars; private byte[] bytes; private boolean[] booleans; private Object[] references; private AlternativeTypeInfo t; ImplGetField(AlternativeTypeInfo t) { doubles = new double[t.double_count]; longs = new long[t.long_count]; ints = new int[t.int_count]; shorts = new short[t.short_count]; floats = new float[t.float_count]; chars = new char[t.char_count]; bytes = new byte[t.byte_count]; booleans = new boolean[t.boolean_count]; references = new Object[t.reference_count]; this.t = t; } public ObjectStreamClass getObjectStreamClass() { /* I don't know how it could be used here, but ... */ return ObjectStreamClass.lookup(t.clazz); } public boolean defaulted(String name) { return false; } public boolean get(String name, boolean dflt) { return booleans[t.getOffset(name, Boolean.TYPE)]; } public char get(String name, char dflt) { return chars[t.getOffset(name, Character.TYPE)]; } public byte get(String name, byte dflt) { return bytes[t.getOffset(name, Byte.TYPE)]; } public short get(String name, short dflt) { return shorts[t.getOffset(name, Short.TYPE)]; } public int get(String name, int dflt) { return ints[t.getOffset(name, Integer.TYPE)]; } public long get(String name, long dflt) { return longs[t.getOffset(name, Long.TYPE)]; } public float get(String name, float dflt) { return floats[t.getOffset(name, Float.TYPE)]; } public double get(String name, double dflt) { return doubles[t.getOffset(name, Double.TYPE)]; } public Object get(String name, Object dflt) { return references[t.getOffset(name, Object.class)]; } void readFields() throws IOException, ClassNotFoundException { for (int i = 0; i < t.double_count; i++) { doubles[i] = ibisStream.readDouble(); } for (int i = 0; i < t.float_count; i++) { floats[i] = ibisStream.readFloat(); } for (int i = 0; i < t.long_count; i++) { longs[i] = ibisStream.readLong(); } for (int i = 0; i < t.int_count; i++) { ints[i] = ibisStream.readInt(); } for (int i = 0; i < t.short_count; i++) { shorts[i] = ibisStream.readShort(); } for (int i = 0; i < t.char_count; i++) { chars[i] = ibisStream.readChar(); } for (int i = 0; i < t.byte_count; i++) { bytes[i] = ibisStream.readByte(); } for (int i = 0; i < t.boolean_count; i++) { booleans[i] = ibisStream.readBoolean(); } for (int i = 0; i < t.reference_count; i++) { references[i] = ibisStream.doReadObject(false); } } } public String readUTF() throws IOException { return ibisStream.readUTF(); } public byte readByte() throws IOException { return ibisStream.readByte(); } public int readUnsignedByte() throws IOException { return ibisStream.readUnsignedByte(); } public boolean readBoolean() throws IOException { return ibisStream.readBoolean(); } public short readShort() throws IOException { return ibisStream.readShort(); } public int readUnsignedShort() throws IOException { return ibisStream.readUnsignedShort(); } public char readChar() throws IOException { return ibisStream.readChar(); } public int readInt() throws IOException { return ibisStream.readInt(); } public long readLong() throws IOException { return ibisStream.readLong(); } public float readFloat() throws IOException { return ibisStream.readFloat(); } public double readDouble() throws IOException { return ibisStream.readDouble(); } public void defaultReadObject() throws ClassNotFoundException, IOException, NotActiveException { if (current_object == null) { throw new NotActiveException( "defaultReadObject without a current object"); } Object ref = current_object; Class type = ref.getClass(); AlternativeTypeInfo t = AlternativeTypeInfo.getAlternativeTypeInfo(type); if (t.isIbisSerializable) { if (DEBUG) { dbPrint("generated_DefaultReadObject, class = " + type + ", level = " + current_level); } ((ibis.io.Serializable) ref).generated_DefaultReadObject(ibisStream, current_level); } else if (t.isSerializable) { /* Find the type info corresponding to the current invocation. * See the invokeReadObject invocation in alternativeReadObject. */ while (t.level > current_level) { t = t.alternativeSuperInfo; } try { ibisStream.alternativeDefaultReadObject(t, ref); } catch (IllegalAccessException e) { if (DEBUG) { dbPrint("Caught exception: " + e); e.printStackTrace(); dbPrint("now rethrow as NotSerializableException ..."); } throw new NotSerializableException(type + " " + e); } } else { throw new NotSerializableException("Not Serializable : " + type.toString()); } } } }
package org.wiztools.restclient; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.XMLEvent; import nu.xom.*; import org.wiztools.commons.MultiValueMap; import org.wiztools.commons.StringUtil; /** * * @author rsubramanian */ public final class XMLUtil { private XMLUtil() { } private static final Logger LOG = Logger.getLogger(XMLUtil.class.getName()); private static final String[] VERSIONS = new String[]{ "2.0", "2.1", "2.2a1", "2.2a2", "2.2", "2.3b1", "2.3", "2.3.1", "2.3.2", "2.3.3", "2.4", RCConstants.VERSION }; private static final List<String> LEGACY_BASE64_VERSIONS = Arrays.asList(new String[]{ "2.0", "2.1", "2.2a1", "2.2a2", "2.2", "2.3b1", "2.3", "2.3.1", "2.3.2", "2.3.3", "2.4" }); public static final String XML_MIME = "application/xml"; static { // Sort the version array for binary search Arrays.sort(VERSIONS); } private static void checkIfVersionValid(final String restVersion) throws XMLException { if (restVersion == null) { throw new XMLException("Attribute `version' not available for root element <rest-client>"); } int res = Arrays.binarySearch(VERSIONS, restVersion); if (res == -1) { throw new XMLException("Version not supported"); } } private static Document request2XML(final Request bean) throws XMLException { try { Element reqRootElement = new Element("rest-client"); // set version attributes to rest-client root tag Attribute versionAttributes = new Attribute("version", RCConstants.VERSION); reqRootElement.addAttribute(versionAttributes); Element reqChildElement = new Element("request"); { // HTTP Version Element e = new Element("http-version"); e.appendChild(bean.getHttpVersion().versionNumber()); reqChildElement.appendChild(e); } { // HTTP Follow Redirect Element e = new Element("http-follow-redirects"); e.appendChild(String.valueOf(bean.isFollowRedirect())); reqChildElement.appendChild(e); } { // creating the URL child element Element e = new Element("URL"); e.appendChild(bean.getUrl().toString()); reqChildElement.appendChild(e); } { // creating the method child element Element e = new Element("method"); e.appendChild(bean.getMethod().name()); reqChildElement.appendChild(e); } { // creating the auth-methods child element List<HTTPAuthMethod> authMethods = bean.getAuthMethods(); if (authMethods == null || authMethods.size() > 0) { { // auth-methods Element e = new Element("auth-methods"); String methods = ""; for (HTTPAuthMethod authMethod : authMethods) { methods = methods + authMethod + ","; } String authenticationMethod = methods.substring(0, methods.length() == 0 ? 0 : methods.length() - 1); e.appendChild(authenticationMethod); reqChildElement.appendChild(e); } { // creating the auth-preemptive child element Element e = new Element("auth-preemptive"); e.appendChild(String.valueOf(bean.isAuthPreemptive())); reqChildElement.appendChild(e); } // creating the auth-host child element String authHost = bean.getAuthHost(); if (StringUtil.isNotEmpty(authHost)) { Element e = new Element("auth-host"); e.appendChild(authHost); reqChildElement.appendChild(e); } // creating the auth-realm child element String authRealm = bean.getAuthRealm(); if (StringUtil.isNotEmpty(authRealm)) { Element e = new Element("auth-realm"); e.appendChild(authRealm); reqChildElement.appendChild(e); } // creating the auth-username child element String authUsername = bean.getAuthUsername(); if (StringUtil.isNotEmpty(authUsername)) { Element e = new Element("auth-username"); e.appendChild(authUsername); reqChildElement.appendChild(e); } // creating the auth-password child element String authPassword = null; if (bean.getAuthPassword() != null) { authPassword = new String(bean.getAuthPassword()); if (StringUtil.isNotEmpty(authPassword)) { String encPassword = Util.base64encode(authPassword); Element e = new Element("auth-password"); e.appendChild(encPassword); reqChildElement.appendChild(e); } } // creating auth-token child element String authToken = bean.getAuthToken(); if(StringUtil.isNotEmpty(authToken)) { Element e = new Element("auth-token"); e.appendChild(authToken); reqChildElement.appendChild(e); } } } // Creating SSL elements String sslTruststore = bean.getSslTrustStore(); if (StringUtil.isNotEmpty(sslTruststore)) { { // 1. Create trust-store entry Element e = new Element("ssl-truststore"); e.appendChild(sslTruststore); reqChildElement.appendChild(e); } { // 2. Create password entry String sslPassword = new String(bean.getSslTrustStorePassword()); String encPassword = Util.base64encode(sslPassword); Element e = new Element("ssl-truststore-password"); e.appendChild(encPassword); reqChildElement.appendChild(e); } } String sslKeystore = bean.getSslKeyStore(); if(StringUtil.isNotEmpty(sslKeystore)) { { // 1. Create keystore entry Element e = new Element("ssl-keystore"); e.appendChild(sslKeystore); reqChildElement.appendChild(e); } { // 2. Create password entry String sslPassword = new String(bean.getSslKeyStorePassword()); String encPassword = Util.base64encode(sslPassword); Element e = new Element("ssl-keystore-password"); e.appendChild(encPassword); reqChildElement.appendChild(e); } } { // Create Hostname Verifier entry String sslHostnameVerifier = bean.getSslHostNameVerifier().name(); Element e = new Element("ssl-hostname-verifier"); e.appendChild(sslHostnameVerifier); reqChildElement.appendChild(e); } { // Create Trust Self-signed cert entry: if(bean.isSslTrustSelfSignedCert()) { Element e = new Element("ssl-trust-self-signed-cert"); reqChildElement.appendChild(e); } } // creating the headers child element MultiValueMap<String, String> headers = bean.getHeaders(); if (!headers.isEmpty()) { Element e = new Element("headers"); for (String key : headers.keySet()) { for(String value: headers.get(key)) { Element ee = new Element("header"); ee.addAttribute(new Attribute("key", key)); ee.addAttribute(new Attribute("value", value)); e.appendChild(ee); } } reqChildElement.appendChild(e); } // creating the body child element ReqEntity rBean = bean.getBody(); if (rBean != null) { String contentType = rBean.getContentType(); String charSet = rBean.getCharSet(); String body = rBean.getBody(); Element e = new Element("body"); e.addAttribute(new Attribute("content-type", contentType)); e.addAttribute(new Attribute("charset", charSet)); e.appendChild(body); reqChildElement.appendChild(e); } // creating the test-script child element String testScript = bean.getTestScript(); if (testScript != null) { Element e = new Element("test-script"); e.appendChild(testScript); reqChildElement.appendChild(e); } reqRootElement.appendChild(reqChildElement); Document xomDocument = new Document(reqRootElement); return xomDocument; } catch (Exception ex) { throw new XMLException(ex.getMessage(), ex); } } private static Map<String, String> getHeadersFromHeaderNode(final Element node) throws XMLException { Map<String, String> m = new LinkedHashMap<String, String>(); for (int i = 0; i < node.getChildElements().size(); i++) { Element headerElement = node.getChildElements().get(i); if (!"header".equals(headerElement.getQualifiedName())) { throw new XMLException("<headers> element should contain only <header> elements"); } m.put(headerElement.getAttributeValue("key"), headerElement.getAttributeValue("value")); } return m; } private static String base64decode(String rcVersion, String base64Str) { if(LEGACY_BASE64_VERSIONS.contains(rcVersion)) { return (String) LegacyBase64.decodeToObject(base64Str); } else { return Util.base64decode(base64Str); } } private static Request xml2Request(final Document doc) throws MalformedURLException, XMLException { RequestBean requestBean = new RequestBean(); // get the rootNode Element rootNode = doc.getRootElement(); if (!"rest-client".equals(rootNode.getQualifiedName())) { throw new XMLException("Root node is not <rest-client>"); } // checking correct rest version final String rcVersion = rootNode.getAttributeValue("version"); checkIfVersionValid(rcVersion); // assign rootnode to current node and also finding 'request' node Element tNode = null; Element requestNode = null; // if more than two request element is present then throw the exception if (rootNode.getChildElements().size() != 1) { throw new XMLException("There can be only one child node for root node: <request>"); } // minimum one request element is present in xml if (rootNode.getFirstChildElement("request") == null) { throw new XMLException("The child node of <rest-client> should be <request>"); } requestNode = rootNode.getFirstChildElement("request"); for (int i = 0; i < requestNode.getChildElements().size(); i++) { tNode = requestNode.getChildElements().get(i); String nodeName = tNode.getQualifiedName(); if ("http-version".equals(nodeName)) { String t = tNode.getValue(); HTTPVersion httpVersion = "1.1".equals(t) ? HTTPVersion.HTTP_1_1 : HTTPVersion.HTTP_1_0; requestBean.setHttpVersion(httpVersion); } else if("http-follow-redirects".equals(nodeName)) { requestBean.setFollwoRedirect(Boolean.valueOf(tNode.getValue())); } else if ("URL".equals(nodeName)) { URL url = new URL(tNode.getValue()); requestBean.setUrl(url); } else if ("method".equals(nodeName)) { requestBean.setMethod(HTTPMethod.get(tNode.getValue())); } else if ("auth-methods".equals(nodeName)) { String[] authenticationMethods = tNode.getValue().split(","); for (int j = 0; j < authenticationMethods.length; j++) { requestBean.addAuthMethod(HTTPAuthMethod.get(authenticationMethods[j])); } } else if ("auth-preemptive".equals(nodeName)) { if (tNode.getValue().equals("true")) { requestBean.setAuthPreemptive(true); } else { requestBean.setAuthPreemptive(false); } } else if ("auth-host".equals(nodeName)) { requestBean.setAuthHost(tNode.getValue()); } else if ("auth-realm".equals(nodeName)) { requestBean.setAuthRealm(tNode.getValue()); } else if ("auth-username".equals(nodeName)) { requestBean.setAuthUsername(tNode.getValue()); } else if ("auth-password".equals(nodeName)) { String password = base64decode(rcVersion, tNode.getValue()); requestBean.setAuthPassword(password.toCharArray()); } else if("auth-token".equals(nodeName)) { requestBean.setAuthToken(tNode.getValue()); } else if ("ssl-truststore".equals(nodeName)) { String sslTrustStore = tNode.getValue(); requestBean.setSslTrustStore(sslTrustStore); } else if ("ssl-truststore-password".equals(nodeName)) { String sslTrustStorePassword = base64decode(rcVersion, tNode.getValue()); requestBean.setSslTrustStorePassword(sslTrustStorePassword.toCharArray()); } else if("ssl-hostname-verifier".equals(nodeName)){ String sslHostnameVerifierStr = tNode.getValue(); SSLHostnameVerifier sslHostnameVerifier = SSLHostnameVerifier.valueOf(sslHostnameVerifierStr); requestBean.setSslHostNameVerifier(sslHostnameVerifier); } else if("ssl-trust-self-signed-cert".equals(nodeName)) { requestBean.setSslTrustSelfSignedCert(true); } else if ("ssl-keystore".equals(nodeName)) { String sslKeyStore = tNode.getValue(); requestBean.setSslKeyStore(sslKeyStore); } else if ("ssl-keystore-password".equals(nodeName)) { String sslKeyStorePassword = base64decode(rcVersion, tNode.getValue()); requestBean.setSslKeyStorePassword(sslKeyStorePassword.toCharArray()); } else if ("headers".equals(nodeName)) { Map<String, String> m = getHeadersFromHeaderNode(tNode); for (String key : m.keySet()) { requestBean.addHeader(key, m.get(key)); } } else if ("body".equals(nodeName)) { requestBean.setBody(new ReqEntityBean(tNode.getValue(), tNode.getAttributeValue("content-type"), tNode.getAttributeValue("charset"))); } else if ("test-script".equals(nodeName)) { requestBean.setTestScript(tNode.getValue()); } else { throw new XMLException("Invalid element encountered: <" + nodeName + ">"); } } return requestBean; } private static Document response2XML(final Response bean) throws XMLException { try { Element respRootElement = new Element("rest-client"); Element respChildElement = new Element("response"); Element respChildSubElement = null; Element respChildSubSubElement = null; // set version attributes to rest-client root tag Attribute versionAttributes = new Attribute("version", RCConstants.VERSION); respRootElement.addAttribute(versionAttributes); // adding first sub child element - execution-time and append to response child element respChildSubElement = new Element("execution-time"); respChildSubElement.appendChild(String.valueOf(bean.getExecutionTime())); respChildElement.appendChild(respChildSubElement); // adding second sub child element - status and code attributes and append to response child element respChildSubElement = new Element("status"); Attribute codeAttributes = new Attribute("code", String.valueOf(bean.getStatusCode())); respChildSubElement.addAttribute(codeAttributes); respChildSubElement.appendChild(bean.getStatusLine()); respChildElement.appendChild(respChildSubElement); // adding third sub child element - headers MultiValueMap<String, String> headers = bean.getHeaders(); if (!headers.isEmpty()) { Attribute keyAttribute = null; Attribute valueAttribute = null; // creating sub child-child element respChildSubElement = new Element("headers"); for (String key : headers.keySet()) { for(String value: headers.get(key)) { respChildSubSubElement = new Element("header"); keyAttribute = new Attribute("key", key); valueAttribute = new Attribute("value", value); respChildSubSubElement.addAttribute(keyAttribute); respChildSubSubElement.addAttribute(valueAttribute); respChildSubElement.appendChild(respChildSubSubElement); } } // add response child element - headers respChildElement.appendChild(respChildSubElement); } String responseBody = bean.getResponseBody(); if (responseBody != null) { //creating the body child element and append to response child element respChildSubElement = new Element("body"); respChildSubElement.appendChild(responseBody); respChildElement.appendChild(respChildSubElement); } // test result TestResult testResult = bean.getTestResult(); if (testResult != null) { //creating the test-result child element respChildSubElement = new Element("test-result"); // Counts: Element e_runCount = new Element("run-coun"); e_runCount.appendChild(String.valueOf(testResult.getRunCount())); Element e_failureCount = new Element("failure-coun"); e_failureCount.appendChild(String.valueOf(testResult.getFailureCount())); Element e_errorCount = new Element("error-coun"); e_errorCount.appendChild(String.valueOf(testResult.getErrorCount())); respChildSubElement.appendChild(e_runCount); respChildSubElement.appendChild(e_failureCount); respChildSubElement.appendChild(e_errorCount); // Failures if (testResult.getFailureCount() > 0) { Element e_failures = new Element("failures"); List<TestExceptionResult> l = testResult.getFailures(); for (TestExceptionResult b : l) { Element e_message = new Element("message"); e_message.appendChild(b.getExceptionMessage()); Element e_line = new Element("line-number"); e_line.appendChild(String.valueOf(b.getLineNumber())); Element e_failure = new Element("failure"); e_failure.appendChild(e_message); e_failure.appendChild(e_line); e_failures.appendChild(e_failure); } respChildSubElement.appendChild(e_failures); } //Errors if (testResult.getErrorCount() > 0) { Element e_errors = new Element("errors"); List<TestExceptionResult> l = testResult.getErrors(); for (TestExceptionResult b : l) { Element e_message = new Element("message"); e_message.appendChild(b.getExceptionMessage()); Element e_line = new Element("line-number"); e_line.appendChild(String.valueOf(b.getLineNumber())); Element e_error = new Element("error"); e_error.appendChild(e_message); e_error.appendChild(e_line); e_errors.appendChild(e_error); } respChildSubElement.appendChild(e_errors); } // Trace Element e_trace = new Element("trace"); e_trace.appendChild(testResult.toString()); respChildSubElement.appendChild(e_trace); respChildElement.appendChild(respChildSubElement); } respRootElement.appendChild(respChildElement); Document xomDocument = new Document(respRootElement); return xomDocument; } catch (Exception ex) { throw new XMLException(ex.getMessage(), ex); } } private static Response xml2Response(final Document doc) throws XMLException { ResponseBean responseBean = new ResponseBean(); // get the rootNode Element rootNode = doc.getRootElement(); if (!"rest-client".equals(rootNode.getQualifiedName())) { throw new XMLException("Root node is not <rest-client>"); } // checking correct rest version checkIfVersionValid(rootNode.getAttributeValue("version")); // assign rootnode to current node and also finding 'response' node Element tNode = null; Element responseNode = null; // if more than two request element is present then throw the exception if (rootNode.getChildElements().size() != 1) { throw new XMLException("There can be only one child node for root node: <response>"); } // minimum one response element is present in xml if (rootNode.getFirstChildElement("response") == null) { throw new XMLException("The child node of <rest-client> should be <response>"); } responseNode = rootNode.getFirstChildElement("response"); for (int i = 0; i < responseNode.getChildElements().size(); i++) { tNode = responseNode.getChildElements().get(i); String nodeName = tNode.getQualifiedName(); if ("execution-time".equals(nodeName)) { responseBean.setExecutionTime(Long.parseLong(tNode.getValue())); } else if ("status".equals(nodeName)) { responseBean.setStatusLine(tNode.getValue()); responseBean.setStatusCode(Integer.parseInt(tNode.getAttributeValue("code"))); } else if ("headers".equals(nodeName)) { Map<String, String> m = getHeadersFromHeaderNode(tNode); for (String key : m.keySet()) { responseBean.addHeader(key, m.get(key)); } } else if ("body".equals(nodeName)) { responseBean.setResponseBody(tNode.getValue()); } else if ("test-result".equals(nodeName)) { //responseBean.setTestResult(node.getTextContent()); TODO TestResultBean testResultBean = new TestResultBean(); for (int j = 0; j < tNode.getChildCount(); j++) { String nn = tNode.getQualifiedName(); if ("run-count".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } else if ("failure-count".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } else if ("error-count".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } else if ("failures".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } else if ("errors".equals(nn)) { throw new XMLException("<headers> element should contain only <header> elements"); } } responseBean.setTestResult(testResultBean); } else { throw new XMLException("Unrecognized element found: <" + nodeName + ">"); } } return responseBean; } private static void writeXML(final Document doc, final File f) throws IOException, XMLException { try { OutputStream out = new FileOutputStream(f); out = new BufferedOutputStream(out); // getDocumentCharset(f) - to retrieve the charset encoding attribute Serializer serializer = new Serializer(out, getDocumentCharset(f)); serializer.write(doc); out.close(); } catch (IOException ex) { throw new XMLException(ex.getMessage(), ex); } } private static Document getDocumentFromFile(final File f) throws IOException, XMLException { try { Builder parser = new Builder(); Document doc = parser.build(f); return doc; } catch (ParsingException ex) { throw new XMLException(ex.getMessage(), ex); } catch (IOException ex) { throw new XMLException(ex.getMessage(), ex); } } public static String getDocumentCharset(final File f) throws IOException, XMLException { XMLEventReader reader = null; try { // using stax to get xml factory objects and read the input file XMLInputFactory inputFactory = XMLInputFactory.newInstance(); reader = inputFactory.createXMLEventReader(new FileInputStream(f)); XMLEvent event = reader.nextEvent(); // Always the first element is StartDocument // even if the XML does not have explicit declaration: StartDocument document = (StartDocument) event; return document.getCharacterEncodingScheme(); } catch (XMLStreamException ex) { throw new XMLException(ex.getMessage(), ex); } finally{ if(reader != null){ try{ reader.close(); } catch(XMLStreamException ex){ LOG.warning(ex.getMessage()); } } } } public static void writeRequestXML(final Request bean, final File f) throws IOException, XMLException { Document doc = request2XML(bean); writeXML(doc, f); } public static void writeResponseXML(final Response bean, final File f) throws IOException, XMLException { Document doc = response2XML(bean); writeXML(doc, f); } public static Request getRequestFromXMLFile(final File f) throws IOException, XMLException { Document doc = getDocumentFromFile(f); return xml2Request(doc); } public static Response getResponseFromXMLFile(final File f) throws IOException, XMLException { Document doc = getDocumentFromFile(f); return xml2Response(doc); } public static String indentXML(final String in) throws XMLException, IOException { try { Builder parser = new Builder(); Document doc = parser.build(in, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Serializer serializer = new Serializer(baos); serializer.setIndent(4); serializer.setMaxLength(69); serializer.write(doc); return new String(baos.toByteArray()); } catch (ParsingException ex) { // LOG.log(Level.SEVERE, null, ex); throw new XMLException("XML indentation failed.", ex); } } }
package fi_81.cwp_morse_mangle.morse; import java.util.ArrayList; /* * Bit format string, originally implemented with BitSet as backing buffer, but as * it appeared to be too slow (profiling results on Motorola Defy+), reverted to String. */ public class BitString implements Comparable<BitString>, CharSequence { private String bits; /* Format input to BitString */ private static String makeBits(CharSequence chars) { int i, len; /* Check if can accept input as is */ for (i = 0, len = chars.length(); i < len; i++) { char ch = chars.charAt(i); if (ch != '0' && ch != '1') break; } if (i == len) { /* Already in correct bit-format */ return chars.toString(); } StringBuffer sb = localStringBuffer.get(); sb.setLength(0); sb.append(chars, 0, i); for (; i < len; i++) { char ch = chars.charAt(i); sb.append(ch == '1' ? '1' : '0'); } return sb.toString(); } /* Internal constructor for buffer that already is in bit-format */ private BitString(String str, boolean alreadyBits) { if (alreadyBits) bits = str; else this.bits = makeBits(str); } /* Public constructor */ public BitString(CharSequence chars) { this.bits = makeBits(chars); } /* Empty constructor */ public BitString() { this.bits = ""; } /* * Helper builders */ public static BitString newFilled(char oneOrZero, int numChars) { StringBuffer sb = localStringBuffer.get(); sb.setLength(0); for (int i = 0; i < numChars; i++) sb.append(oneOrZero); return new BitString(sb.toString(), true); } public static BitString newZeros(int numZeros) { return newFilled('0', numZeros); } public static BitString newOnes(int numOnes) { return newFilled('1', numOnes); } public static BitString newBits(String onesAndZeros) { return new BitString(onesAndZeros, true); } public char charAt(int index) { return bits.charAt(index); } public int length() { return bits.length(); } public CharSequence subSequence(int start, int end) { return bits.subSequence(start, end); } public int compareTo(BitString another) { return bits.compareTo(another.bits); } @Override public String toString() { return bits; } public BitString substring(int start, int end) { return new BitString(bits.substring(start, end), true); } /* Check if object is same as this. */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof BitString)) return false; BitString obs = (BitString) o; return (bits == null ? obs.bits == null : bits.equals(obs.bits)); } /** Append another BitString at end of this and return resulting BitString */ public BitString append(BitString endBits) { StringBuffer sb = localStringBuffer.get(); sb.setLength(0); sb.append(bits); sb.append(endBits.bits); return new BitString(sb.toString(), true); } public BitString[] split(BitString splitString) { /* Emulate String.split() as closely as possible */ int stringLength = bits.length(); int splitStringLength = splitString.bits.length(); /* * Empty string gives array with one cell, and that cell is empty * string. */ if (stringLength == 0) { BitString array[] = new BitString[1]; array[0] = this; return array; } ArrayList<BitString> list = localArrayList.get(); int idx = 0, prev = 0; list.clear(); /* Iterate through all split strings and copy to array */ while ((idx = bits.indexOf(splitString.bits, idx)) >= 0) { list.add(new BitString(bits.substring(prev, idx), true)); if (splitStringLength > 0) idx += splitStringLength; else idx++; /* Avoid endless loop */ prev = idx; } /* Finally, copy the last split string */ idx = stringLength; list.add(new BitString(bits.substring(prev, idx), true)); BitString splits[] = list.toArray(emptyArray); list.clear(); return splits; } public boolean endWith(BitString suffix) { return bits.endsWith(suffix.bits); } /* Helper for handling endWith for StringBuffer */ public static boolean stringBufferEndWithBits(StringBuffer stringBuf, BitString suffix) { int suffixLen = suffix.length(); int bufferLen = stringBuf.length(); if (bufferLen < suffixLen) return false; return stringBuf.lastIndexOf(suffix.toString(), bufferLen - suffixLen) != -1; } /* Cached empty object to avoid allocation in split() */ private final static BitString[] emptyArray = new BitString[0]; /* Cached thread-local objects to reduce memory allocations by BitString */ private final static ThreadLocal<StringBuffer> localStringBuffer = new ThreadLocal<StringBuffer>() { @Override protected StringBuffer initialValue() { return new StringBuffer(); } }; private final static ThreadLocal<ArrayList<BitString>> localArrayList = new ThreadLocal<ArrayList<BitString>>() { @Override protected ArrayList<BitString> initialValue() { return new ArrayList<BitString>(); } }; }
package com.rexsl.core; import com.sun.jersey.api.core.PackagesResourceConfig; import com.sun.jersey.spi.container.servlet.ServletContainer; import com.ymock.util.Logger; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Properties; import java.util.Vector; import javax.servlet.FilterConfig; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; /** * Core servlet. * * @author Yegor Bugayenko (yegor@rexsl.com) * @version $Id$ */ public final class RestfulServlet extends HttpServlet { /** * Comma. */ private static final String COMMA = ","; /** * Jersey servlet. */ private final ServletContainer jersey = new ServletContainer(); /** * {@inheritDoc} * @checkstyle RedundantThrows (3 lines) */ @Override public void init(final ServletConfig config) throws ServletException { final List<String> packages = new ArrayList<String>(); packages.add(this.getClass().getPackage().getName()); final String param = config.getInitParameter("com.rexsl.PACKAGES"); if (param != null) { for (String pkg : StringUtils.split(param, this.COMMA)) { if (packages.contains(pkg)) { continue; } packages.add(pkg); Logger.info( this, "#init(): '%s' package added (%d total)", pkg, packages.size() ); } } final Properties props = new Properties(); props.setProperty( PackagesResourceConfig.PROPERTY_PACKAGES, StringUtils.join(packages, this.COMMA) ); this.julToSlf4j(); final FilterConfig cfg = new ServletConfigWrapper(config, props); this.jersey.init(cfg); Logger.debug(this, "#init(): servlet initialized"); } /** * {@inheritDoc} * @checkstyle ThrowsCount (6 lines) * @checkstyle RedundantThrows (5 lines) */ @Override protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { this.jersey.service(request, response); Logger.debug( this, "#service(%s): processed by Jersey", request.getRequestURI() ); } /** * Initialize JUL-to-SLF4J bridge. */ private void julToSlf4j() { final java.util.logging.Logger rootLogger = java.util.logging.LogManager.getLogManager().getLogger(""); final java.util.logging.Handler[] handlers = rootLogger.getHandlers(); for (int idx = 0; idx < handlers.length; idx += 1) { rootLogger.removeHandler(handlers[idx]); } org.slf4j.bridge.SLF4JBridgeHandler.install(); } /** * Custom filter config. */ private static final class ServletConfigWrapper implements FilterConfig { /** * Wrapped config. */ private final ServletConfig config; /** * Additional properties. */ private final Properties properties; /** * Public ctor. * @param cfg Servlet config * @param props Properties to add to existing params */ public ServletConfigWrapper(final ServletConfig cfg, final Properties props) { this.config = cfg; this.properties = props; } /** * {@inheritDoc} */ @Override public String getFilterName() { return this.config.getServletName() + "-filter"; } /** * {@inheritDoc} */ @Override public String getInitParameter(final String name) { String value = this.properties.getProperty(name); if (value == null) { value = this.config.getInitParameter(name); } return value; } /** * {@inheritDoc} */ @Override public Enumeration<String> getInitParameterNames() { final Vector<String> names = new Vector<String>(); for (Object name : this.properties.keySet()) { names.add((String) name); } final Enumeration<String> enm = this.config.getInitParameterNames(); while (enm.hasMoreElements()) { names.add(enm.nextElement()); } return names.elements(); } /** * {@inheritDoc} */ @Override public ServletContext getServletContext() { return this.config.getServletContext(); } } }
package org.obolibrary.robot; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.AddOntologyAnnotation; import org.semanticweb.owlapi.model.OWLAnnotation; import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom; import org.semanticweb.owlapi.model.OWLAnnotationProperty; import org.semanticweb.owlapi.model.OWLAnnotationSubject; import org.semanticweb.owlapi.model.OWLAnnotationValue; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLDatatype; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.model.OWLLiteral; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.model.OWLOntologyID; import org.semanticweb.owlapi.model.RemoveOntologyAnnotation; import org.semanticweb.owlapi.model.SetOntologyID; import org.semanticweb.owlapi.util.ReferencedEntitySetProvider; /** * Provides convenience methods for working with OWL ontologies. * * @author <a href="mailto:james@overton.ca">James A. Overton</a> */ public class OntologyHelper { /** * Logger. */ private static final Logger logger = LoggerFactory.getLogger(OntologyHelper.class); /** * Set the ontology IRI and version IRI using strings. * * @param ontology the ontology to change * @param ontologyIRIString the ontology IRI string, or null for no change * @param versionIRIString the version IRI string, or null for no change */ public static void setOntologyIRI(OWLOntology ontology, String ontologyIRIString, String versionIRIString) { IRI ontologyIRI = null; if (ontologyIRIString != null) { ontologyIRI = IRI.create(ontologyIRIString); } IRI versionIRI = null; if (versionIRIString != null) { versionIRI = IRI.create(versionIRIString); } setOntologyIRI(ontology, ontologyIRI, versionIRI); } /** * Set the ontology IRI and version IRI. * * @param ontology the ontology to change * @param ontologyIRI the new ontology IRI, or null for no change * @param versionIRI the new version IRI, or null for no change */ public static void setOntologyIRI(OWLOntology ontology, IRI ontologyIRI, IRI versionIRI) { OWLOntologyID currentID = ontology.getOntologyID(); if (ontologyIRI == null && versionIRI == null) { // don't change anything return; } else if (ontologyIRI == null) { ontologyIRI = currentID.getOntologyIRI(); } else if (versionIRI == null) { versionIRI = currentID.getVersionIRI(); } OWLOntologyID newID; if (versionIRI == null) { newID = new OWLOntologyID(ontologyIRI); } else { newID = new OWLOntologyID(ontologyIRI, versionIRI); } SetOntologyID setID = new SetOntologyID(ontology, newID); ontology.getOWLOntologyManager().applyChange(setID); } /** * Given an OWLAnnotationValue, return its value as a string. * * @param value the OWLAnnotationValue to get the string value of * @return the string value */ public static String getValue(OWLAnnotationValue value) { String result = null; if (value instanceof OWLLiteral) { result = ((OWLLiteral) value).getLiteral(); } return result; } /** * Given an OWLAnnotation, return its value as a string. * * @param annotation the OWLAnnotation to get the string value of * @return the string value */ public static String getValue(OWLAnnotation annotation) { return getValue(annotation.getValue()); } /** * Given a set of OWLAnnotations, return the first string value * as determined by natural string sorting. * * @param annotations a set of OWLAnnotations to get the value of * @return the first string value */ public static String getValue(Set<OWLAnnotation> annotations) { Set<String> valueSet = getValues(annotations); List<String> valueList = new ArrayList<String>(valueSet); Collections.sort(valueList); String value = null; if (valueList.size() > 0) { value = valueList.get(0); } return value; } /** * Given a set of OWLAnnotations, return a set of their value strings. * * @param annotations a set of OWLAnnotations to get the value of * @return a set of the value strings */ public static Set<String> getValues(Set<OWLAnnotation> annotations) { Set<String> results = new HashSet<String>(); for (OWLAnnotation annotation: annotations) { String value = getValue(annotation); if (value != null) { results.add(value); } } return results; } /** * Given an annotation value, return its datatype, or null. * * @param value the value to check * @return the datatype, or null if the value has none */ public static OWLDatatype getType(OWLAnnotationValue value) { if (value instanceof OWLLiteral) { return ((OWLLiteral) value).getDatatype(); } return null; } /** * Given an annotation value, return the IRI of its datatype, or null. * * @param value the value to check * @return the IRI of the datatype, or null if the value has none */ public static IRI getTypeIRI(OWLAnnotationValue value) { OWLDatatype datatype = getType(value); if (datatype == null) { return null; } else { return datatype.getIRI(); } } /** * Given an ontology, an optional set of annotation properties, * and an optional set of subject, * return a set of annotation assertion axioms for those * subjects and those properties. * * @param ontology the ontology to search (including imports closure) * @param property an annotation property * @param subject an annotation subject IRIs * @return a filtered set of annotation assertion axioms */ public static Set<OWLAnnotationAssertionAxiom> getAnnotationAxioms( OWLOntology ontology, OWLAnnotationProperty property, IRI subject) { Set<OWLAnnotationProperty> properties = new HashSet<OWLAnnotationProperty>(); properties.add(property); Set<IRI> subjects = new HashSet<IRI>(); subjects.add(subject); return getAnnotationAxioms(ontology, properties, subjects); } /** * Given an ontology, an optional set of annotation properties, * and an optional set of subject, * return a set of annotation assertion axioms for those * subjects and those properties. * * @param ontology the ontology to search (including imports closure) * @param properties a set of annotation properties, * or null if all properties should be included * @param subjects a set of annotation subject IRIs, * or null if all subjects should be included * @return a filtered set of annotation assertion axioms */ public static Set<OWLAnnotationAssertionAxiom> getAnnotationAxioms( OWLOntology ontology, Set<OWLAnnotationProperty> properties, Set<IRI> subjects) { Set<OWLAnnotationAssertionAxiom> results = new HashSet<OWLAnnotationAssertionAxiom>(); for (OWLAxiom axiom: ontology.getAxioms()) { if (!(axiom instanceof OWLAnnotationAssertionAxiom)) { continue; } OWLAnnotationAssertionAxiom aaa = (OWLAnnotationAssertionAxiom) axiom; if (properties != null && !properties.contains(aaa.getProperty())) { continue; } OWLAnnotationSubject subject = aaa.getSubject(); if (subjects == null) { results.add(aaa); } else if (subject instanceof IRI && subjects.contains((IRI) subject)) { results.add(aaa); } } return results; } /** * Given an ontology, an optional set of annotation properties, * and an optional set of subject, * return a set of annotation values for those * subjects and those properties. * * @param ontology the ontology to search (including imports closure) * @param property an annotation property * @param subject an annotation subject IRIs * @return a filtered set of annotation values */ public static Set<OWLAnnotationValue> getAnnotationValues( OWLOntology ontology, OWLAnnotationProperty property, IRI subject) { Set<OWLAnnotationProperty> properties = new HashSet<OWLAnnotationProperty>(); properties.add(property); Set<IRI> subjects = new HashSet<IRI>(); subjects.add(subject); return getAnnotationValues(ontology, properties, subjects); } /** * Given an ontology, an optional set of annotation properties, * and an optional set of subject, * return a set of annotation values for those * subjects and those properties. * * @param ontology the ontology to search (including imports closure) * @param properties a set of annotation properties, * or null if all properties should be included * @param subjects a set of annotation subject IRIs, * or null if all subjects should be included * @return a filtered set of annotation values */ public static Set<OWLAnnotationValue> getAnnotationValues( OWLOntology ontology, Set<OWLAnnotationProperty> properties, Set<IRI> subjects) { Set<OWLAnnotationValue> results = new HashSet<OWLAnnotationValue>(); Set<OWLAnnotationAssertionAxiom> axioms = getAnnotationAxioms(ontology, properties, subjects); for (OWLAnnotationAssertionAxiom axiom: axioms) { results.add(axiom.getValue()); } return results; } /** * Given an ontology, an optional set of annotation properties, * and an optional set of subject, * return a set of strings for those subjects and those properties. * * @param ontology the ontology to search (including imports closure) * @param property an annotation property * @param subject an annotation subject IRIs * @return a filtered set of annotation strings */ public static Set<String> getAnnotationStrings( OWLOntology ontology, OWLAnnotationProperty property, IRI subject) { Set<OWLAnnotationProperty> properties = new HashSet<OWLAnnotationProperty>(); properties.add(property); Set<IRI> subjects = new HashSet<IRI>(); subjects.add(subject); return getAnnotationStrings(ontology, properties, subjects); } /** * Given an ontology, an optional set of annotation properties, * and an optional set of subject, * return a set of strings for those subjects and those properties. * * @param ontology the ontology to search (including imports closure) * @param properties a set of annotation properties, * or null if all properties should be included * @param subjects a set of annotation subject IRIs, * or null if all subjects should be included * @return a filtered set of annotation strings */ public static Set<String> getAnnotationStrings( OWLOntology ontology, Set<OWLAnnotationProperty> properties, Set<IRI> subjects) { Set<String> results = new HashSet<String>(); Set<OWLAnnotationValue> values = getAnnotationValues(ontology, properties, subjects); for (OWLAnnotationValue value: values) { results.add(getValue(value)); } return results; } /** * Given an ontology, an optional set of annotation properties, * and an optional set of subject, * return the alphanumerically first annotation value string * for those subjects and those properties. * * @param ontology the ontology to search (including imports closure) * @param property an annotation property * @param subject an annotation subject IRIs * @return the first annotation string */ public static String getAnnotationString( OWLOntology ontology, OWLAnnotationProperty property, IRI subject) { Set<OWLAnnotationProperty> properties = new HashSet<OWLAnnotationProperty>(); properties.add(property); Set<IRI> subjects = new HashSet<IRI>(); subjects.add(subject); return getAnnotationString(ontology, properties, subjects); } /** * Given an ontology, an optional set of annotation properties, * and an optional set of subject, * return the alphanumerically first annotation value string * for those subjects and those properties. * * @param ontology the ontology to search (including imports closure) * @param properties a set of annotation properties, * or null if all properties should be included * @param subjects a set of annotation subject IRIs, * or null if all subjects should be included * @return the first annotation string */ public static String getAnnotationString( OWLOntology ontology, Set<OWLAnnotationProperty> properties, Set<IRI> subjects) { Set<String> valueSet = getAnnotationStrings(ontology, properties, subjects); List<String> valueList = new ArrayList<String>(valueSet); Collections.sort(valueList); String value = null; if (valueList.size() > 0) { value = valueList.get(0); } return value; } /** * Given an ontology, return a map from IRIs to rdfs:labels. * Includes labels asserted in for all imported ontologies. * If there are multiple labels, use the alphanumerically first. * * @param ontology the ontology to use * @return a map from IRIs to label strings */ public static Map<IRI, String> getLabels(OWLOntology ontology) { Map<IRI, String> results = new HashMap<IRI, String>(); OWLOntologyManager manager = ontology.getOWLOntologyManager(); OWLAnnotationProperty rdfsLabel = manager.getOWLDataFactory().getRDFSLabel(); Set<OWLOntology> ontologies = new HashSet<OWLOntology>(); ontologies.add(ontology); ReferencedEntitySetProvider resp = new ReferencedEntitySetProvider(ontologies); for (OWLEntity entity: resp.getEntities()) { String value = getAnnotationString( ontology, rdfsLabel, entity.getIRI()); if (value != null) { results.put(entity.getIRI(), value); } } return results; } /** * Given an ontology and a set of term IRIs, * return a set of entities for those IRIs. * The input ontology is not changed. * * @param ontology the ontology to search * @param iris the IRIs of the entities to find * @return a set of OWLEntities with the given IRIs */ public static Set<OWLEntity> getEntities(OWLOntology ontology, Set<IRI> iris) { Set<OWLEntity> entities = new HashSet<OWLEntity>(); if (iris == null) { return null; } for (IRI iri: iris) { entities.addAll(ontology.getEntitiesInSignature(iri, true)); } return entities; } /** * Given an ontology, return a set of all the entities in its signature. * * @param ontology the ontology to search * @return a set of all entities in the ontology */ public static Set<OWLEntity> getEntities(OWLOntology ontology) { Set<OWLOntology> ontologies = new HashSet<OWLOntology>(); ontologies.add(ontology); ReferencedEntitySetProvider resp = new ReferencedEntitySetProvider(ontologies); return resp.getEntities(); } /** * Given an ontology, return a set of IRIs for all the entities * in its signature. * * @param ontology the ontology to search * @return a set of IRIs for all entities in the ontology */ public static Set<IRI> getIRIs(OWLOntology ontology) { Set<IRI> iris = new HashSet<IRI>(); for (OWLEntity entity: getEntities(ontology)) { iris.add(entity.getIRI()); } return iris; } /** * Remove all annotations on this ontology. * Just annotations on the ontology itself, * not annotations on its classes, etc. * * @param ontology the ontology to modify */ public static void removeOntologyAnnotations(OWLOntology ontology) { OWLOntologyManager manager = ontology.getOWLOntologyManager(); for (OWLAnnotation annotation: ontology.getAnnotations()) { RemoveOntologyAnnotation remove = new RemoveOntologyAnnotation(ontology, annotation); manager.applyChange(remove); } } /** * Given an ontology, a property IRI, and a value string, * add an annotation to this ontology with that property and value. * * @param ontology the ontology to modify * @param propertyIRI the IRI of the property to add * @param value the IRI or literal value to add */ public static void addOntologyAnnotation(OWLOntology ontology, IRI propertyIRI, OWLAnnotationValue value) { OWLOntologyManager manager = ontology.getOWLOntologyManager(); OWLDataFactory df = manager.getOWLDataFactory(); OWLAnnotationProperty property = df.getOWLAnnotationProperty(propertyIRI); OWLAnnotation annotation = df.getOWLAnnotation(property, value); addOntologyAnnotation(ontology, annotation); } /** * Annotate the ontology with the annotation. * * @param ontology the ontology to modify * @param annotation the annotation to add */ public static void addOntologyAnnotation(OWLOntology ontology, OWLAnnotation annotation) { OWLOntologyManager manager = ontology.getOWLOntologyManager(); AddOntologyAnnotation addition = new AddOntologyAnnotation(ontology, annotation); manager.applyChange(addition); } }
package org.mvnsearch.ali.oss.spring.shell.commands; import com.aliyun.openservices.oss.model.*; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.filefilter.AbstractFileFilter; import org.apache.commons.lang3.StringUtils; import org.apache.http.impl.cookie.DateUtils; import org.fusesource.jansi.Ansi; import org.jetbrains.annotations.Nullable; import org.mvnsearch.ali.oss.spring.services.*; import org.mvnsearch.ali.oss.spring.shell.converters.BucketEnum; import org.mvnsearch.ali.oss.spring.shell.converters.HttpHeader; import org.mvnsearch.ali.oss.spring.shell.converters.ObjectKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.shell.core.CommandMarker; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.awt.*; import java.io.File; import java.net.URI; import java.net.URL; import java.text.MessageFormat; import java.util.*; import java.util.List; /** * Aliyun OSS operation commands * * @author linux_china */ @SuppressWarnings("StringConcatenationInsideStringBufferAppend") @Component public class OssOperationCommands implements CommandMarker { /** * log */ private Logger log = LoggerFactory.getLogger(OssOperationCommands.class); /** * The platform-specific line separator. */ public static final String LINE_SEPARATOR = System.getProperty("line.separator"); /** * current bucket */ public static OSSUri currentBucket = null; /** * local repository */ private File localRepository; /** * config service */ private ConfigService configService; /** * aliyun oss service */ private AliyunOssService aliyunOssService; /** * inject aliyun oss service * * @param aliyunOssService aliyun oss service */ @Autowired public void setAliyunOssService(AliyunOssService aliyunOssService) { this.aliyunOssService = aliyunOssService; } /** * inject config service * * @param configService config service */ @Autowired public void setConfigService(ConfigService configService) { this.configService = configService; } /** * init method: load current bucket */ @PostConstruct public void init() { currentBucket = new OSSUri(configService.getProperty("BUCKET"), null); String repository = configService.getRepository(); if (repository != null && !repository.isEmpty()) { localRepository = new File(repository); } //bucket if (configService.available()) { try { List<Bucket> buckets = aliyunOssService.getBuckets(); for (Bucket bucket : buckets) { BucketEnum.addBucketName(bucket.getName()); } } catch (Exception ignore) { } } } /** * config command to save aliyun OSS information * * @return result */ @CliCommand(value = "config", help = "Config the Aliyun OSS access settings") public String config(@CliOption(key = {"id"}, mandatory = true, help = "Aliyun Access ID") final String accessId, @CliOption(key = {"key"}, mandatory = true, help = "Aliyun Access Key") final String accessKey, @CliOption(key = {"repository"}, mandatory = true, help = "local repository directory") final File reposity) { try { configService.setAccessInfo(accessId, accessKey); aliyunOssService.refreshToken(); try { List<Bucket> buckets = aliyunOssService.getBuckets(); //local repository if (!reposity.exists()) { FileUtils.forceMkdir(reposity); //create bucket directory if (buckets != null) { for (Bucket bucket : buckets) { FileUtils.forceMkdir(new File(reposity, bucket.getName())); } } } localRepository = reposity; configService.setRepository(reposity.getAbsolutePath()); } catch (Exception e) { System.out.println(wrappedAsRed("Failed to set access info!")); return null; } } catch (Exception e) { log.error("config", e); return wrappedAsRed(e.getMessage()); } return "Access info saved!"; } /** * list all your buckets * * @return bucket list */ @CliCommand(value = "df", help = "List all your buckets") public String df() { return listBuckets(); } /** * create a bucket * * @return new bucket */ @CliCommand(value = "create", help = "Create a bucket") public String create(@CliOption(key = {"acl"}, mandatory = false, help = "Bucket's acl, such as: Private, R- or RW") String acl, @CliOption(key = {""}, mandatory = true, help = "Bucket name: pattern as [a-z][a-z0-9\\-_]{5,15}") final String bucket) { try { if (acl == null || acl.isEmpty() || acl.equalsIgnoreCase("private")) { acl = " } if (!(acl.equalsIgnoreCase("--") || acl.equals("R-") || acl.equals("RW"))) { return wrappedAsRed("ACL's value should be 'Private', 'R-' or 'RW'"); } aliyunOssService.createBucket(bucket); aliyunOssService.setBucketACL(bucket, acl); return MessageFormat.format("Bucket ''{0}'' has been created!", bucket); } catch (Exception e) { log.error("create", e); return wrappedAsRed(e.getMessage()); } } /** * drop bucket * * @param bucketEnum bucket enum * @return result */ @CliCommand(value = "drop", help = "Drop bucket") public String drop(@CliOption(key = {""}, mandatory = true, help = "Bucket name") BucketEnum bucketEnum) { try { String bucketName = bucketEnum.getName(); Bucket bucket = aliyunOssService.getBucket(bucketName); if (bucket != null) { return wrappedAsRed(MessageFormat.format("Bucket ''{0}'' not found!", bucketName)); } ObjectListing listing = aliyunOssService.list(bucketName, ""); if (!listing.getObjectSummaries().isEmpty()) { return wrappedAsRed("The bucket is not empty, and you can't delete it!"); } aliyunOssService.dropBucket(bucketName); if (bucketName.equals(currentBucket.getBucket())) { currentBucket = null; configService.setProperty("BUCKET", null); } return MessageFormat.format("Bucket ''{0}'' has been dropped!", bucketName); } catch (Exception e) { log.error("drop", e); return wrappedAsRed(e.getMessage()); } } /** * Change current bucket's Access Control Lists * * @return result */ @CliCommand(value = "chmod", help = "Change current bucket's Access Control Lists") public String chmod(@CliOption(key = {""}, mandatory = true, help = "Access Control List: Private, ReadOnly or ReadWrite") BucketAclType acl) { try { if (currentBucket == null) { return wrappedAsYellow("Please select a bucket!"); } if (acl != null && acl.getType() != null) { aliyunOssService.setBucketACL(currentBucket.getBucket(), acl.getShortCode()); } else { return wrappedAsRed("ACL value should be 'Private', 'ReadOnly' or 'ReadWrite'."); } return MessageFormat.format("{0} {1}", acl, currentBucket.toString()); } catch (Exception e) { log.error("chmod", e); return wrappedAsRed(e.getMessage()); } } /** * download oss object * * @param localFilePath dest local file path * @param objectKey object key * @return message */ @CliCommand(value = "get", help = "Retrieve OSS object and save it to local file system") public String get(@CliOption(key = {"o"}, mandatory = false, help = "Local file or directory path") File localFilePath, @CliOption(key = {""}, mandatory = true, help = "OSS object uri or key") String objectKey) { if (currentBucket == null) { return wrappedAsYellow("Please select a bucket!"); } try { OSSUri objectUri = currentBucket.getChildObjectUri(objectKey); ObjectMetadata objectMetadata = aliyunOssService.getObjectMetadata(objectUri); if (objectMetadata == null) { return wrappedAsRed("The object not found!"); } String destFilePath = aliyunOssService.get(objectUri, localFilePath.getAbsolutePath()); return MessageFormat.format("Object {0} saved to {1} ({3} bytes)", objectUri.toString(), destFilePath, objectMetadata.getContentLength()); } catch (Exception e) { log.error("get", e); return e.getMessage(); } } /** * display object content * * @return message */ @CliCommand(value = "cat", help = "concatenate and print OSS object's content") public String cat(@CliOption(key = {""}, mandatory = true, help = "OSS object uri or key") final ObjectKey objectKey) { try { OSSUri objectUri = currentBucket.getChildObjectUri(objectKey.getKey()); OSSObject ossObject = aliyunOssService.getOssObject(objectUri); if (ossObject != null) { byte[] content = IOUtils.toByteArray(ossObject.getObjectContent()); if ("gzip".equalsIgnoreCase(ossObject.getObjectMetadata().getContentEncoding())) { content = ZipUtils.uncompress(content); } System.out.println(new String(content)); } else { return wrappedAsRed("The object not found!"); } } catch (Exception e) { log.error("cat", e); return wrappedAsRed(e.getMessage()); } return null; } /** * open OSS object in browser * * @param objectKey object key or uri * @return message */ @CliCommand(value = "open", help = "Open OSS object in browser") public String open(@CliOption(key = {""}, mandatory = true, help = "OSS object uri or key") final ObjectKey objectKey) { try { OSSUri objectUri = currentBucket.getChildObjectUri(objectKey.getKey()); if (Desktop.isDesktopSupported()) { ObjectMetadata objectMetadata = aliyunOssService.getObjectMetadata(objectUri); if (objectMetadata != null) { Desktop desktop = Desktop.getDesktop(); desktop.browse(new URI(objectUri.getHttpUrl())); } else { return wrappedAsRed("The object not found!"); } } else { return wrappedAsRed("Luanch Brower not support, please copy url to browser address: " + objectUri.getBucket()); } } catch (Exception e) { log.error("open", e); return wrappedAsRed(e.getMessage()); } return null; } /** * Upload file or director to OSS * * @return message */ @CliCommand(value = "put", help = "Upload the local file or directory to OSS") public String put(@CliOption(key = {"source"}, mandatory = true, help = "Local file or directory path") File sourceFile, @CliOption(key = {"zip"}, mandatory = false, help = "Zip the file", specifiedDefaultValue = "true") Boolean zip, @CliOption(key = {""}, mandatory = false, help = "Destination OSS object uri, key or path") String objectKey) { if (!sourceFile.exists()) { return wrappedAsRed(MessageFormat.format("The file ''{0}'' not exits. ", sourceFile.getAbsolutePath())); } try { if (sourceFile.isDirectory()) { int count = uploadDirectory(currentBucket.getBucket(), StringUtils.defaultIfEmpty(objectKey, ""), sourceFile, false, zip); return count + " files uploaded"; } else { if (objectKey == null || objectKey.isEmpty()) { objectKey = sourceFile.getName(); } if (objectKey.endsWith("/")) { objectKey = objectKey + sourceFile.getName(); } OSSUri destObjectUri = currentBucket.getChildObjectUri(objectKey); ObjectMetadata metadata = aliyunOssService.put(sourceFile.getAbsolutePath(), destObjectUri, zip); return MessageFormat.format("File ''{0}'' stored as {1} ({2} bytes)", sourceFile.getAbsolutePath(), destObjectUri.toString(), metadata.getContentLength()); } } catch (Exception e) { log.error("put", e); return e.getMessage(); } } /** * upload directory * * @param bucket bucket * @param destFilePath dest file name * @param sourceDir source directory * @param synced synced mark * @throws Exception exception */ private int uploadDirectory(String bucket, String destFilePath, File sourceDir, boolean synced, Boolean zip) throws Exception { Collection<File> files = FileUtils.listFiles(sourceDir, new AbstractFileFilter() { public boolean accept(File file) { return !file.getName().startsWith("."); } }, new AbstractFileFilter() { public boolean accept(File dir, String name) { return !name.startsWith("."); } } ); int count = files.size(); for (File file : files) { String destPath = file.getAbsolutePath().replace(sourceDir.getAbsolutePath(), ""); destPath = destFilePath + destPath.replaceAll("\\\\", "/"); if (destPath.contains(" destPath = destPath.replace(" } boolean overwrite = true; OSSUri objectUri = new OSSUri(bucket, destPath); //sync validation if (synced) { ObjectMetadata objectMetadata = aliyunOssService.getObjectMetadata(objectUri); if (objectMetadata != null) { if (objectMetadata.getLastModified().getTime() >= file.lastModified() && file.length() == objectMetadata.getContentLength()) { overwrite = false; } } } if (overwrite) { aliyunOssService.put(file.getAbsolutePath(), objectUri, zip); System.out.println("Uploaded: " + objectUri); } else { System.out.println("Skipped: " + objectUri); count = count - 1; } } return count; } /** * sync directory * * @return message */ @CliCommand(value = "sync", help = "Sync bucket or directory with OSS") public String sync(@CliOption(key = {"source"}, mandatory = false, help = "local directory") @Nullable File sourceFile, @CliOption(key = {"bucket"}, mandatory = false, help = "bucket name") @Nullable BucketEnum bucketEnum, @CliOption(key = {"zip"}, mandatory = false, help = "Zip the file", specifiedDefaultValue = "true") Boolean zip, @CliOption(key = {""}, mandatory = false, help = "OSS object path") String objectPath) { if (currentBucket == null) { return wrappedAsYellow("Please select a bucket!"); } String bucketName = currentBucket.getBucket(); if (sourceFile == null && bucketEnum == null) { return wrappedAsYellow("Please use --bucket or --source for sync"); } //source filebucketobject path if (sourceFile == null) { sourceFile = new File(localRepository, bucketEnum.getName()); bucketName = bucketEnum.getName(); objectPath = ""; } if (!sourceFile.exists()) { return wrappedAsRed(MessageFormat.format("File ''{0}'' not exits: ", sourceFile.getAbsolutePath())); } try { if (sourceFile.isDirectory()) { int count = uploadDirectory(bucketName, StringUtils.defaultIfEmpty(objectPath, ""), sourceFile, true, zip); return count + " files uploaded!"; } else { OSSUri objectUri = currentBucket.getChildObjectUri(objectPath); ObjectMetadata metadata = aliyunOssService.put(sourceFile.getAbsolutePath(), objectUri); return MessageFormat.format("File '{0}' stored as {1} ({2} bytes)", sourceFile.getAbsolutePath(), objectUri.toString(), metadata.getContentLength()); } } catch (Exception e) { log.error("sync", e); return wrappedAsRed(e.getMessage()); } } /** * list files * * @return content */ @CliCommand(value = "ls", help = "List object or virtual directory in Bucket") public String ls(@CliOption(key = {""}, mandatory = false, help = "Object key or path: support suffix wild match") final String filename) { if (currentBucket == null) { return listBuckets(); } StringBuilder buf = new StringBuilder(); OSSUri dirObject = currentBucket.getChildObjectUri(filename); try { ObjectListing objectListing; if (dirObject.getFilePath().endsWith("*")) { objectListing = aliyunOssService.list(currentBucket.getBucket(), dirObject.getFilePath()); } else { objectListing = aliyunOssService.listChildren(currentBucket.getBucket(), dirObject.getFilePath()); } int dirCount = 0; int objectCount = 0; if (!objectListing.getCommonPrefixes().isEmpty()) { for (String commonPrefix : objectListing.getCommonPrefixes()) { buf.append(StringUtils.repeat("-.", 14) + "- " + commonPrefix + LINE_SEPARATOR); dirCount += 1; } } if (!objectListing.getObjectSummaries().isEmpty()) { for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) { buf.append(DateUtils.formatDate(objectSummary.getLastModified(), "yyyy-MM-dd HH:mm:ss") + StringUtils.leftPad(String.valueOf(objectSummary.getSize()), 10, ' ') + " " + objectSummary.getKey() + LINE_SEPARATOR); objectCount += 1; } } if (dirCount > 0 && objectCount > 0) { buf.append(dirCount + " virtual directories and " + objectCount + " objects found!"); } else if (dirCount > 0) { buf.append(dirCount + " virtual directories found!"); } else if (objectCount > 0) { buf.append(objectCount + " objects found!"); } else { buf.append("No object found for " + dirObject.toString()); } return buf.toString(); } catch (Exception e) { log.error("ls", e); return wrappedAsRed(e.getMessage()); } } /** * list buckets * * @return bucket list */ private String listBuckets() { StringBuilder buf = new StringBuilder(); try { buf.append("Buckets:" + LINE_SEPARATOR); List<Bucket> buckets = aliyunOssService.getBuckets(); for (Bucket bucket : buckets) { //acl buf.append(aliyunOssService.getBucketACL(bucket.getName())); //create time buf.append(" " + DateUtils.formatDate(bucket.getCreationDate(), "yyyy-MM-dd HH:mm:ss")); //pad buf.append((bucket.getName().equals(currentBucket.getBucket())) ? " => " : " "); //apend url buf.append("oss://" + bucket.getName() + LINE_SEPARATOR); } } catch (Exception e) { log.error("listbuckets", e); return wrappedAsRed(e.getMessage()); } return buf.toString().trim(); } /** * change directory * * @return content */ @CliCommand(value = "cd", help = "Change virtual directory on OSS") public String cd(@CliOption(key = {""}, mandatory = false, help = "Oss virtual directory name") String dir) { if (dir == null || dir.isEmpty() || dir.equals("/")) { currentBucket.setFilePath(""); } else { if (dir.endsWith(".")) { return currentBucket.toString(); } if (!dir.endsWith("/")) { dir = dir + "/"; } String currentDir = currentBucket.getChildObjectUri(dir).getFilePath(); currentBucket.setFilePath(currentDir); } OssCliPromptProvider.prompt = currentBucket.toString(); return currentBucket.toString(); } /** * display working virtual directory uri * * @return content */ @CliCommand(value = "pwd", help = "Return working virtual directory uri") public String pwd() { if (currentBucket == null) { return wrappedAsRed("Please select a bucket!"); } return wrappedAsRed(currentBucket.toString()); } /** * switch bucket * * @return content */ @CliCommand(value = "use", help = "Switch bucket") public String use(@CliOption(key = {""}, mandatory = true, help = "bucket name") final BucketEnum bucketEnum) { try { String bucketName = bucketEnum.getName(); Bucket bucket = aliyunOssService.getBucket(bucketName); if (bucket == null) { return wrappedAsRed("The bucket not found"); } currentBucket = new OSSUri(bucketName, null); configService.setProperty("BUCKET", bucketName); OssCliPromptProvider.prompt = currentBucket.toString(); return "Switched to " + currentBucket.toString(); } catch (Exception e) { log.error("use", e); return wrappedAsRed(e.getMessage()); } } /** * show OSS object detail information * * @return content */ @CliCommand(value = "file", help = "Get OSS object detail information") public String file(@CliOption(key = {""}, mandatory = true, help = "Oss object uri or key") final ObjectKey objectKey) { StringBuilder buf = new StringBuilder(); try { OSSUri objectUri = currentBucket.getChildObjectUri(objectKey.getKey()); ObjectMetadata objectMetadata = aliyunOssService.getObjectMetadata(objectUri); if (objectMetadata != null) { buf.append(StringUtils.rightPad("Bucket", 20, ' ') + " : " + objectUri.getBucket() + LINE_SEPARATOR); buf.append(StringUtils.rightPad("Folder", 20, ' ') + " : " + objectUri.getPath() + LINE_SEPARATOR); buf.append(StringUtils.rightPad("Name", 20, ' ') + " : " + objectUri.getFileName() + LINE_SEPARATOR); Map<String, Object> rawMetadata = objectMetadata.getRawMetadata(); //date buf.append(StringUtils.rightPad("Date", 20, ' ') + " : " + rawMetadata.get("Date") + LINE_SEPARATOR); buf.append(StringUtils.rightPad("Last-Modified", 20, ' ') + " : " + rawMetadata.get("Date") + LINE_SEPARATOR); if (rawMetadata.get("Expires") != null) { buf.append(StringUtils.rightPad("Expires", 20, ' ') + " : " + rawMetadata.get("Expires") + LINE_SEPARATOR); } //content buf.append(StringUtils.rightPad("Content-Type", 20, ' ') + " : " + rawMetadata.get("Content-Type") + LINE_SEPARATOR); buf.append(StringUtils.rightPad("Content-Length", 20, ' ') + " : " + rawMetadata.get("Content-Length") + LINE_SEPARATOR); List<String> reservedKeys = Arrays.asList("Connection", "Server", "x-oss-request-id", "Date", "Last-Modified", "Content-Type", "Content-Length"); for (Map.Entry<String, Object> entry : rawMetadata.entrySet()) { if (!reservedKeys.contains(entry.getKey())) { buf.append(StringUtils.rightPad(entry.getKey(), 20, ' ') + " : " + entry.getValue() + LINE_SEPARATOR); } } Map<String, String> userMetadata = objectMetadata.getUserMetadata(); if (userMetadata != null && !userMetadata.isEmpty()) { buf.append("================ User Metadata ========================" + LINE_SEPARATOR); for (Map.Entry<String, String> entry : userMetadata.entrySet()) { buf.append(StringUtils.rightPad(entry.getKey(), 20, ' ') + " : " + entry.getValue() + LINE_SEPARATOR); } } } else { return wrappedAsRed("The object not found!"); } } catch (Exception e) { log.error("file", e); return wrappedAsRed(e.getMessage()); } return buf.toString().trim(); } /** * share object to generate signed url, expired one hour * * @return content */ @CliCommand(value = "share", help = "Generate signed url for OSS object.") public String share(@CliOption(key = {""}, mandatory = true, help = "Object uri or key") final String filePath) { OSSUri destObject = currentBucket.getChildObjectUri(filePath); try { URL url = aliyunOssService.getOssClient().generatePresignedUrl(destObject.getBucket(), destObject.getFilePath(), new Date(System.currentTimeMillis() + 1000 * 60 * 60)); return url.toString(); } catch (Exception e) { log.error("share", e); return e.getMessage(); } } /** * delete OSS object * * @return content */ @CliCommand(value = "rm", help = "Delete OSS object") public String rm(@CliOption(key = {""}, mandatory = true, help = "OSS object uri or key: support suffix wild match") final ObjectKey objectKey) { try { String filePath = objectKey.getKey(); if (filePath.endsWith("*") || filePath.endsWith("/")) { ObjectListing list = aliyunOssService.list(currentBucket.getBucket(), filePath); int size = list.getObjectSummaries().size(); for (OSSObjectSummary objectSummary : list.getObjectSummaries()) { OSSUri objectToDeleted = currentBucket.getChildObjectUri(objectSummary.getKey()); aliyunOssService.delete(objectToDeleted); System.out.println("Deleted: " + objectToDeleted.toString()); } if (size > 1) { return size + " objects deleted!"; } else { return "1 object deleted!"; } } else { OSSUri destObject = currentBucket.getChildObjectUri(filePath); aliyunOssService.delete(destObject); return "Deleted: " + destObject.toString(); } } catch (Exception e) { log.error("rm", e); return wrappedAsRed(e.getMessage()); } } /** * copy object * * @return content */ @CliCommand(value = "cp", help = "Copy OSS object") public String cp(@CliOption(key = {"object"}, mandatory = true, help = "Source object key or uri") final ObjectKey sourceObjectKey, @CliOption(key = {"dest"}, mandatory = true, help = "Dest object key") final String destFilePath) { try { OSSUri sourceUri = currentBucket.getChildObjectUri(sourceObjectKey.getKey()); OSSUri destUri = currentBucket.getChildObjectUri(destFilePath); aliyunOssService.copy(sourceUri, destUri); return MessageFormat.format("''{0}'' has been copied to ''{1}''", sourceUri.toString(), destUri.toString()); } catch (Exception e) { log.error("cp", e); return wrappedAsRed(e.getMessage()); } } /** * move object * * @return content */ @CliCommand(value = "mv", help = "Move OSS Object") public String mv(@CliOption(key = {"object"}, mandatory = true, help = "Source object key") final ObjectKey sourceObjectKey, @CliOption(key = {""}, mandatory = true, help = "Dest object key") final String destFilePath) { try { OSSUri sourceUri = currentBucket.getChildObjectUri(sourceObjectKey.getKey()); OSSUri destUri = currentBucket.getChildObjectUri(destFilePath); aliyunOssService.copy(sourceUri, destUri); aliyunOssService.delete(sourceUri); return MessageFormat.format("''{0}'' has been moved to ''{1}''", sourceUri.toString(), destUri.toString()); } catch (Exception e) { log.error("mv", e); return e.getMessage(); } } /** * set object meta data * * @return content */ @CliCommand(value = "set", help = "Set object metadata") public String set(@CliOption(key = {"key"}, mandatory = true, help = "Metadata key") final HttpHeader httpHeader, @CliOption(key = {"value"}, mandatory = true, help = "Metadata value") final String value, @CliOption(key = {""}, mandatory = true, help = "Object key") final String filePath) { try { String key = httpHeader.getName(); aliyunOssService.setObjectMetadata(currentBucket.getChildObjectUri(filePath), key, value); } catch (Exception e) { log.error("set", e); return e.getMessage(); } return file(new ObjectKey(filePath)); } /** * set object meta data * * @return content */ @CliCommand(value = "demo", help = "Set object metadata") public String demo(@CliOption(key = {"key"}, mandatory = true, help = "Metadata key") final HttpHeader httpHeader, @CliOption(key = {""}, mandatory = true, help = "bucket name") final BucketEnum bucketEnum) { return null; } /** * wrapped as red with Jansi * * @param text text * @return wrapped text */ private String wrappedAsRed(String text) { return Ansi.ansi().fg(Ansi.Color.RED).a(text).toString(); } /** * wrapped as yellow with Jansi * * @param text text * @return wrapped text */ private String wrappedAsYellow(String text) { return Ansi.ansi().fg(Ansi.Color.YELLOW).a(text).toString(); } }
package org.voltdb; import java.io.IOException; import java.lang.reflect.Constructor; import java.nio.ByteBuffer; import org.voltcore.utils.DBBPool; import org.voltcore.utils.DBBPool.BBContainer; import org.voltdb.iv2.SpScheduler.DurableUniqueIdListener; import org.voltdb.licensetool.LicenseApi; import com.google_voltpatches.common.collect.ImmutableMap; /** * Stub class that provides a gateway to the InvocationBufferServer when * DR is enabled. If no DR, then it acts as a noop stub. * */ public class PartitionDRGateway implements DurableUniqueIdListener { public enum DRRecordType { INSERT, DELETE, UPDATE, BEGIN_TXN, END_TXN, TRUNCATE_TABLE, DELETE_BY_INDEX, UPDATE_BY_INDEX; } public static enum DRRowType { EXISTING_ROW, EXPECTED_ROW, NEW_ROW } public static enum DRConflictResolutionFlag { ACCEPT_CHANGE, CONVERGENT } // Keep sync with EE DRConflictType at types.h public static enum DRConflictType { NO_CONFLICT, CONSTRIANT_VIOLATION, EXPECTED_ROW_MISSING, EXPECTED_ROW_TIMESTAMP_MISMATCH } public static ImmutableMap<Integer, PartitionDRGateway> m_partitionDRGateways = ImmutableMap.of(); /** * Load the full subclass if it should, otherwise load the * noop stub. * @param partitionId partition id * @param overflowDir * @return Instance of PartitionDRGateway */ public static PartitionDRGateway getInstance(int partitionId, ProducerDRGateway producerGateway, StartAction startAction) { final VoltDBInterface vdb = VoltDB.instance(); LicenseApi api = vdb.getLicenseApi(); final boolean licensedToDR = api.isDrReplicationAllowed(); // if this is a primary cluster in a DR-enabled scenario // try to load the real version of this class PartitionDRGateway pdrg = null; if (licensedToDR && producerGateway != null) { pdrg = tryToLoadProVersion(); } if (pdrg == null) { pdrg = new PartitionDRGateway(); } // init the instance and return try { pdrg.init(partitionId, producerGateway, startAction); } catch (IOException e) { VoltDB.crashLocalVoltDB(e.getMessage(), false, e); } // Regarding apparent lack of thread safety: this is called serially // while looping over the SPIs during database initialization assert !m_partitionDRGateways.containsKey(partitionId); ImmutableMap.Builder<Integer, PartitionDRGateway> builder = ImmutableMap.builder(); builder.putAll(m_partitionDRGateways); builder.put(partitionId, pdrg); m_partitionDRGateways = builder.build(); return pdrg; } private static PartitionDRGateway tryToLoadProVersion() { try { Class<?> pdrgiClass = null; pdrgiClass = Class.forName("org.voltdb.dr2.PartitionDRGatewayImpl"); Constructor<?> constructor = pdrgiClass.getConstructor(); Object obj = constructor.newInstance(); return (PartitionDRGateway) obj; } catch (Exception e) { } return null; } // empty methods for community edition protected void init(int partitionId, ProducerDRGateway producerGateway, StartAction startAction) throws IOException {} public void onSuccessfulProcedureCall(long txnId, long uniqueId, int hash, StoredProcedureInvocation spi, ClientResponseImpl response) {} public void onSuccessfulMPCall(long spHandle, long txnId, long uniqueId, int hash, StoredProcedureInvocation spi, ClientResponseImpl response) {} public long onBinaryDR(int partitionId, long startSequenceNumber, long lastSequenceNumber, long lastSpUniqueId, long lastMpUniqueId, ByteBuffer buf) { final BBContainer cont = DBBPool.wrapBB(buf); DBBPool.registerUnsafeMemory(cont.address()); cont.discard(); return -1; } @Override public void lastUniqueIdsMadeDurable(long spUniqueId, long mpUniqueId) {} public int processDRConflict(int partitionId, int remoteClusterId, long remoteTimestamp, String tableName, DRRecordType action, DRConflictType deleteConflict, ByteBuffer existingTableForDelete, ByteBuffer expectedTableForDelete, DRConflictType insertConflict, ByteBuffer existingTableForInsert, ByteBuffer newTableForInsert) { return 0; } public static long pushDRBuffer( int partitionId, long startSequenceNumber, long lastSequenceNumber, long lastSpUniqueId, long lastMpUniqueId, ByteBuffer buf) { final PartitionDRGateway pdrg = m_partitionDRGateways.get(partitionId); if (pdrg == null) { VoltDB.crashLocalVoltDB("No PRDG when there should be", true, null); } return pdrg.onBinaryDR(partitionId, startSequenceNumber, lastSequenceNumber, lastSpUniqueId, lastMpUniqueId, buf); } public void forceAllDRNodeBuffersToDisk(final boolean nofsync) {} public static int reportDRConflict(int partitionId, int remoteClusterId, long remoteTimestamp, String tableName, int action, int deleteConflict, ByteBuffer existingTableForDelete, ByteBuffer expectedTableForDelete, int insertConflict, ByteBuffer existingTableForInsert, ByteBuffer newTableForInsert) { final PartitionDRGateway pdrg = m_partitionDRGateways.get(partitionId); if (pdrg == null) { VoltDB.crashLocalVoltDB("No PRDG when there should be", true, null); } return pdrg.processDRConflict(partitionId, remoteClusterId, remoteTimestamp, tableName, DRRecordType.values()[action], DRConflictType.values()[deleteConflict], existingTableForDelete, expectedTableForDelete, DRConflictType.values()[insertConflict], existingTableForInsert, newTableForInsert); } }
package org.yaz4j;
package robowars.server.controller; import java.io.Serializable; /** * Represents a command sent from a mobile client to the RoboWars server. * This includes functionality such as setting spectator status, setting * ready status, setting the current gametype, and sending gameplay commands. * * Valid command formats: * CHAT_MESSAGE - String<Chat Message> * READY_STATUS - Boolean * SPECTATOR_STATUS - Boolean * GAME_TYPE_CHANGE - String<Name of Game Type> * LAUNCH_GAME - No Data * GAMEPLAY_COMMAND - Orientation Floats, String<Optional - Buttons Pressed> * DISCONNECT - No Data */ public class ClientCommand implements Serializable { private static final long serialVersionUID = 1832713935557007848L; /** Constants used to indicate command type */ public static final int CHAT_MESSAGE = 0; public static final int READY_STATUS = 1; public static final int SPECTATOR_STATUS = 2; public static final int GAME_TYPE_CHANGE = 3; public static final int LAUNCH_GAME = 4; public static final int GAMEPLAY_COMMAND = 5; public static final int DISCONNECT = 6; /** * Boolean flag used to indicate status for status changing messages * (Changing ready or spectator status) */ private Boolean boolData; /** * String field used for holding data for commands requiring a string * (Chat messages, game type changes, and an optional "buttons pressed" * string for gameplay commands) */ private String stringData; /** The type of the command (constants defined in ClientCommand) */ private Integer commandType; /** * Floats storing the orientation of the phone (normalized to a +1 to -1 range). * These should only be non-null for gameplay commands. */ private Float azimuth, pitch, roll; /** * Generates a new ClientCommand with all fields (except commandType) * set to null. * @param commandType The type of ClientCommand to generate */ public ClientCommand(int commandType) { this.commandType = commandType; boolData = null; stringData = null; azimuth = null; pitch = null; roll = null; } /** * @return The type of the command (constants defined in ClientCommand) */ public int getCommandType() { return commandType; } /** * Sets the boolean data carried by the command. * @param data The boolean value to be carried by the command */ public void setBoolData(Boolean data) { boolData = data; } /** * @return The boolean data carried by the command. */ public Boolean getBoolData() { return boolData; } /** * Sets the string data carried by the command. * @param data The string value to be carried by the command */ public void setStringData(String data) { stringData = data; } /** * @return The string data carried by the command */ public String getStringData() { return stringData; } /** * Sets the orientation data carried by the command. All orientation values * should be scaled to a range of 1 to -1. * @param azimuth The azimuth (compass heading) of the client (usually not used) * @param pitch The pitch of the client * @param roll The roll of the client */ public void setOrientation(float azimuth, float pitch, float roll) { this.azimuth = azimuth; this.pitch = pitch; this.roll = roll; } /** * @return The azimuth value carried by the command (or null if none was set) */ public Float getAzimuth() { return azimuth; } /** * @return The pitch value carried by the command (or null if none was set) */ public Float getPitch() { return pitch; } /** * @return The roll value carried by the command (or null if none was set) */ public Float getRoll() { return roll; } /** * Converts a string from the RoboWars V0.1 command format into a ClientCommand * object. Valid formats are: * * m:<message> - chat message * r:<t or f> - set ready state * s:<t or f> - set pure spectator state * g:<game_type_string> - set game type * c:<x,y,z> or c:<x,y,z>button_string or c:button_string * a command string to be passed to a paired robot * (Note: If no gyro is available tilt should always be <0,0,0> * l - launch game * q - disconnect * * @param commandString The string to generate a command from (WARNING: case sensitive) * @return The generated client command, or null if no command could be generated. */ public static ClientCommand parse(String commandString) { if(commandString.equals("l")) { return new ClientCommand(LAUNCH_GAME); } else if (commandString.equals("q")) { return new ClientCommand(DISCONNECT); } else if (commandString.startsWith("r:")) { ClientCommand readyCmd = new ClientCommand(READY_STATUS); if(commandString.substring(2, 3).equals("t")) { readyCmd.setBoolData(true); return readyCmd; } else if (commandString.substring(2,3).equals("f")) { readyCmd.setBoolData(false); return readyCmd; } } else if (commandString.startsWith("s:")) { ClientCommand specCmd = new ClientCommand(SPECTATOR_STATUS); if(commandString.substring(2, 3).equals("t")) { specCmd.setBoolData(true); return specCmd; } else if (commandString.substring(2,3).equals("f")) { specCmd.setBoolData(false); return specCmd; } } else if (commandString.startsWith("g:")) { ClientCommand gameCmd = new ClientCommand(GAME_TYPE_CHANGE); gameCmd.setStringData(commandString.substring(2)); return gameCmd; } else if (commandString.startsWith("m:")) { ClientCommand chatCmd = new ClientCommand(CHAT_MESSAGE); chatCmd.setStringData(commandString.substring(2)); return chatCmd; } else if (commandString.startsWith("c:")) { ClientCommand gameplayCmd = new ClientCommand(GAMEPLAY_COMMAND); if(commandString.substring(2,3).equals("<") && commandString.contains(">")) { // Orientation vector was provided String vectorString = commandString.substring(3, commandString.indexOf(">")); commandString = commandString.substring(commandString.indexOf(">") + 1); Float azimuth, pitch, roll = null; try { // Read float values from string azimuth = Float.parseFloat(vectorString.substring(0, vectorString.indexOf(","))); vectorString = vectorString.substring(vectorString.indexOf(",") + 1); pitch = Float.parseFloat(vectorString.substring(0, vectorString.indexOf(","))); vectorString = vectorString.substring(vectorString.indexOf(",") + 1); roll = Float.parseFloat(vectorString); gameplayCmd.setOrientation(azimuth, pitch, roll); } catch (NumberFormatException e) { // Error reading orientation values, return null return null; } } // If any string was supplied beyond the orientation string, add it to the generated command if(commandString.length() > 0) { gameplayCmd.setStringData(commandString); } return gameplayCmd; } return null; } }
package org.openlmis.referencedata.util.messagekeys; public abstract class TradeItemMessageKeys extends MessageKeys { private static final String ERROR = join(SERVICE_ERROR, TRADE_ITEM); public static final String ERROR_NOT_FOUND_WITH_ID = join(ERROR, NOT_FOUND, WITH, ID); public static final String ERROR_NULL = join(ERROR, NULL); public static final String ERROR_MANUFACTURER_REQUIRED = join(ERROR, "manufacturerOfTradeItem", REQUIRED); public static final String ERROR_GTIN_NUMERIC = join(ERROR, "gtin", NUMERIC); public static final String ERROR_GTIN_INVALID_LENGTH = join(ERROR, "gtin", INVALID_LENGTH); public static final String ERROR_GTIN_DUPLICATED = join(ERROR, "gtin", DUPLICATED); }
package utils; import java.util.ArrayList; import org.apache.commons.validator.routines.InetAddressValidator; import serial.MessageFromServer; import serial.MessageToServer; public class MessageControler { public MessageControler() { // do nothing } public void process(String s) { MessageToServer msg = new MessageToServer(s); } // Function to call if Message is a command public void processCommand(String command, ArrayList<String> args) throws MessageControlerException { // Case #CONNECT : we expect 2 args (ip, nick) if (command.toUpperCase() == "#CONNECT") { if (args.size() == 2) { String serverIP = args.get(0); String nickname = args.get(1); //check if args are OK boolean isValidIP = this.isValidIpAddress(serverIP); boolean isValidNickname = this.isValidNickname(nickname); // if not maybe in wrong order? //if ok try to connect if (isValidIP && isValidNickname) { try { this.connectToServer(serverIP, nickname); } catch (ConnectionHandlerException e) { throw new MessageControlerException( "An error occured attempting to connect to IP \"" + serverIP + "\" with nickname \"" + nickname + "\".", e); } } } else { throw new MessageControlerException("#CONNECT expects two args, the target server ip and a nickname."); } } else if (command.toUpperCase() == "#JOIN") { if (args.size() == 1) { String channel = args.get(0); //check if args are OK //if ok try to connect try { this.connectToChannel(channel); } catch (ConnectionHandlerException e) { // TODO Auto-generated catch block throw new MessageControlerException( "Unabled to join channel \"" + channel + "\".", e); } } else { throw new MessageControlerException("#JOIN expects 1 args, the target channel name."); } } else if (command.toUpperCase() == "#QUIT") { } else if (command.toUpperCase() == "#EXIT") { } else { throw new MessageControlerException("Not a valid command. RTFM :)"); } } // TODO nothing to do here private boolean isValidIpAddress(String serverIP) { InetAddressValidator validator = new InetAddressValidator(); return (validator.isValidInet4Address(serverIP) || validator.isValidInet6Address(serverIP)); } private boolean isValidNickname(String nickname) { return nickname.length() > 3; } private void connectToServer(String serverIP, String nickname) throws ConnectionHandlerException { // connect to server // TODO singleton getInstance + check isOpened connection ConnectionHandler handler = new ConnectionHandler(); handler.openConnection(serverIP); // init MSG ArrayList<String> args = new ArrayList<String>(); args.add(serverIP); args.add(nickname); MessageToServer msg = new MessageToServer(nickname, "#connect", args); // write msg handler.write(msg.toString()); // read response -> wait x second, then timeout // is username ok etc... String s = handler.read(); this.processServerMessage(s); } private void processServerMessage(String s) { // init server message MessageFromServer msgFromServer = new MessageFromServer(s); // check is valid ? boolean isValid = msgFromServer.isValid(); if (! isValid) { } // server or user ? boolean isFromServer = msgFromServer.isFromServer(); // case 1 Server if (isFromServer) { } // case 2 User else { } } private void connectToChannel(String channel) throws ConnectionHandlerException { // TODO Auto-generated method stub ConnectionHandler handler = new ConnectionHandler(); } }
package org.sagebionetworks.web.client.widget.entity; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.sagebionetworks.evaluation.model.Evaluation; import org.sagebionetworks.evaluation.model.Submission; import org.sagebionetworks.repo.model.Challenge; import org.sagebionetworks.repo.model.Entity; import org.sagebionetworks.repo.model.Reference; import org.sagebionetworks.repo.model.Team; import org.sagebionetworks.repo.model.TeamHeader; import org.sagebionetworks.repo.model.Versionable; import org.sagebionetworks.repo.model.table.PaginatedIds; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.web.client.DisplayConstants; import org.sagebionetworks.web.client.DisplayUtils; import org.sagebionetworks.web.client.GlobalApplicationState; import org.sagebionetworks.web.client.SynapseClientAsync; import org.sagebionetworks.web.client.place.LoginPlace; import org.sagebionetworks.web.client.place.Profile; import org.sagebionetworks.web.client.security.AuthenticationController; import org.sagebionetworks.web.client.transform.NodeModelCreator; import org.sagebionetworks.web.client.widget.entity.EvaluationSubmitterView.Presenter; import org.sagebionetworks.web.shared.EntityWrapper; import org.sagebionetworks.web.shared.PaginatedResults; import org.sagebionetworks.web.shared.exceptions.RestServiceException; import org.sagebionetworks.web.shared.exceptions.UnknownErrorException; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class EvaluationSubmitter implements Presenter { private EvaluationSubmitterView view; private SynapseClientAsync synapseClient; private NodeModelCreator nodeModelCreator; private GlobalApplicationState globalApplicationState; private AuthenticationController authenticationController; private Entity submissionEntity; private String submissionEntityId, submissionName; private Long submissionEntityVersion; List<Team> teams; private Evaluation evaluation; private Challenge challenge; private Team selectedTeam; private String selectedTeamMemberStateHash; private List<Long> selectedTeamEligibleMembers; @Inject public EvaluationSubmitter(EvaluationSubmitterView view, SynapseClientAsync synapseClient, NodeModelCreator nodeModelCreator, GlobalApplicationState globalApplicationState, AuthenticationController authenticationController) { this.view = view; this.view.setPresenter(this); this.synapseClient = synapseClient; this.nodeModelCreator = nodeModelCreator; this.globalApplicationState = globalApplicationState; this.authenticationController = authenticationController; } /** * * @param submissionEntity set to null if an entity finder should be shown * @param evaluationIds set to null if we should query for all available evaluations */ public void configure(Entity submissionEntity, Set<String> evaluationIds) { challenge = null; evaluation = null; selectedTeam = null; teams = new ArrayList<Team>(); selectedTeamEligibleMembers = new ArrayList<Long>(); view.showLoading(); this.submissionEntity = submissionEntity; try { if (evaluationIds == null) synapseClient.getAvailableEvaluations(getEvalCallback()); else synapseClient.getAvailableEvaluations(evaluationIds, getEvalCallback()); } catch (RestServiceException e) { view.showErrorMessage(e.getMessage()); } } private AsyncCallback<String> getEvalCallback() { return new AsyncCallback<String>() { @Override public void onSuccess(String jsonString) { try { PaginatedResults<Evaluation> results = nodeModelCreator.createPaginatedResults(jsonString, Evaluation.class); List<Evaluation> evaluations = results.getResults(); if (evaluations == null || evaluations.size() == 0) { //no available evaluations, pop up an info dialog view.showErrorMessage(DisplayConstants.NOT_PARTICIPATING_IN_ANY_EVALUATIONS); } else { view.showModal1(submissionEntity == null, evaluations); } } catch (JSONObjectAdapterException e) { onFailure(new UnknownErrorException(DisplayConstants.ERROR_INCOMPATIBLE_CLIENT_VERSION)); } } @Override public void onFailure(Throwable caught) { if(!DisplayUtils.handleServiceException(caught, globalApplicationState, authenticationController.isLoggedIn(), view)) view.showErrorMessage(caught.getMessage()); } }; } @Override public void nextClicked(Reference selectedReference, String submissionName, Evaluation evaluation) { //in any case look up the entity (to make sure we have the most recent version, for the current etag submissionEntityVersion = null; if (submissionEntity != null) { submissionEntityId = submissionEntity.getId(); if (submissionEntity instanceof Versionable) submissionEntityVersion = ((Versionable)submissionEntity).getVersionNumber(); } else { submissionEntityId = selectedReference.getTargetId(); submissionEntityVersion = selectedReference.getTargetVersionNumber(); } this.submissionName = submissionName; this.evaluation = evaluation; //The standard is to attach access requirements to the associated team, and show them when joining the team. //So access requirements are not checked again here. view.hideModal1(); if (evaluation.getContentSource() == null) { //no need to show second page, this is a submission to a non-challenge eval queue. doneClicked(); } else { queryForChallenge(); } } public void queryForChallenge() { synapseClient.getChallenge(evaluation.getContentSource(), new AsyncCallback<Challenge>() { @Override public void onSuccess(Challenge result) { challenge = result; getAvailableTeams(); } @Override public void onFailure(Throwable caught) { view.showErrorMessage("Unable to find associated challenge: " + caught.getMessage()); } }); } public void getAvailableTeams() { synapseClient.getSubmissionTeams(authenticationController.getCurrentUserPrincipalId(), challenge.getId(), getTeamsCallback()); } @Override public void teamAdded() { //when a team is added, we need to refresh the teams list getAvailableTeams(); } @Override public void createNewTeamClicked() { if (authenticationController.isLoggedIn()) globalApplicationState.getPlaceChanger().goTo(new Profile(authenticationController.getCurrentUserPrincipalId())); else { globalApplicationState.getPlaceChanger().goTo(new LoginPlace(LoginPlace.LOGIN_TOKEN)); } } @Override public void registerMyTeamLinkClicked() { view.showRegisterTeamDialog(challenge.getId()); } private AsyncCallback<List<Team>> getTeamsCallback() { return new AsyncCallback<List<Team>>() { @Override public void onSuccess(List<Team> results) { teams = results; view.setTeams(teams); view.showModal2(); } @Override public void onFailure(Throwable caught) { if(!DisplayUtils.handleServiceException(caught, globalApplicationState, authenticationController.isLoggedIn(), view)) view.showErrorMessage(caught.getMessage()); } }; } @Override public void doneClicked() { if (!view.isIndividual()) { //team submission if (selectedTeam == null) { view.showErrorMessage("Please select a team"); return; } } lookupEtagAndCreateSubmission(submissionEntityId, submissionEntityVersion); } @Override public void teamSelected(String selectedTeamName) { selectedTeam = null; selectedTeamMemberStateHash = null; selectedTeamEligibleMembers.clear(); view.clearContributors(); view.setTeamInEligibleErrorVisible(false, ""); //resolve team from team name for (Team team : teams) { if(selectedTeamName.equals(team.getName())) { selectedTeam = team; break; } } if (selectedTeam != null) { //get contributor list for this team synapseClient.getTeamSubmissionEligibility(evaluation.getId(), selectedTeam.getId(), new AsyncCallback<TeamSubmissionEligibility>() { @Override public void onSuccess(TeamSubmissionEligibility teamState) { //is the team eligible??? if (!teamState.isEligible()) { //show the error String reason = ""; //unknown reason if (!teamState.isRegistered()) { reason = selectedTeam.getName() + " is not registered for this challenge. Please register this team, or select a different team."; } else if (teamState.isQuotaFilled) { reason = selectedTeam.getName() + " has exceeded the submission quota."; } view.setTeamInEligibleErrorVisible(true, reason); } else { selectedTeamMemberStateHash = teamState.getMemberStateHash(); for (MemberSubmissionEligibility memberState : teamState.getTeamMemberEligibilityList()) { if (memberState.isEligible()) { selectedTeamEligibleMembers.add(memberState.getPrincipalId()); view.addEligibleContributor(memberState.getPrincipalId()); } else { String reason = ""; //unknown reason if (!memberState.isRegistered()) { reason = "Not registered for the challenge."; } else if (memberState.isQuotaFilled) { reason = "Exceeded the submission quota."; } view.addInEligibleContributor(memberState.getPrincipalId(), reason); } } } }; @Override public void onFailure(Throwable caught) { if(!DisplayUtils.handleServiceException(caught, globalApplicationState, authenticationController.isLoggedIn(), view)) view.showErrorMessage(caught.getMessage()); } }); } } public void lookupEtagAndCreateSubmission(final String id, final Long ver) { //look up entity for the current etag synapseClient.getEntity(id, new AsyncCallback<EntityWrapper>() { public void onSuccess(EntityWrapper result) { Entity entity; try { entity = nodeModelCreator.createEntity(result); Long v = null; if (ver != null) v = ver; else if (entity instanceof Versionable) v = ((Versionable)entity).getVersionNumber(); else { //entity is not versionable, the service will not accept null, but will accept a version of 1 v = 1L; } submitToEvaluation(id, v, entity.getEtag()); } catch (JSONObjectAdapterException e) { onFailure(new UnknownErrorException(DisplayConstants.ERROR_INCOMPATIBLE_CLIENT_VERSION)); } } @Override public void onFailure(Throwable caught) { if(!DisplayUtils.handleServiceException(caught, globalApplicationState, authenticationController.isLoggedIn(), view)) view.showErrorMessage(caught.getMessage()); } }); } public void submitToEvaluation(final String entityId, final Long versionNumber, final String etag) { //set up shared values across all submissions Submission newSubmission = new Submission(); newSubmission.setEntityId(entityId); newSubmission.setUserId(authenticationController.getCurrentUserPrincipalId()); newSubmission.setVersionNumber(versionNumber); if (submissionName != null && submissionName.trim().length() > 0) newSubmission.setName(submissionName); if (!selectedTeamEligibleMembers.isEmpty()) { newSubmission.setContributors(selectedTeamEligibleMembers); } submitToEvaluation(newSubmission, etag); } public void submitToEvaluation(final Submission newSubmission, final String etag) { //and create a new submission for each evaluation newSubmission.setEvaluationId(evaluation.getId()); try { String teamId = null; String memberStateHash = null; if (!view.isIndividual()) { //team is selected teamId = selectedTeam.getId(); memberStateHash = selectedTeamMemberStateHash; } synapseClient.createSubmission(newSubmission, etag, teamId, memberStateHash, new AsyncCallback<Submission>() { @Override public void onSuccess(Submission result) { //result is the updated submission String message = evaluation.getSubmissionReceiptMessage(); if (message == null || message.length()==0) message = DisplayConstants.SUBMISSION_RECEIVED_TEXT; view.hideModal2(); view.showSubmissionAcceptedDialogs(message); } @Override public void onFailure(Throwable caught) { if(!DisplayUtils.handleServiceException(caught, globalApplicationState, authenticationController.isLoggedIn(), view)) view.showErrorMessage(caught.getMessage()); } }); } catch (RestServiceException e) { view.showErrorMessage(e.getMessage()); } } public Widget asWidget() { return view.asWidget(); } }
package net.java.sip.communicator.impl.protocol.irc; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; /** * An IRC implementation of the ProtocolProviderService. * * @author Loic Kempf * @author Stephane Remy * @author Danny van Heumen */ public class ProtocolProviderServiceIrcImpl extends AbstractProtocolProviderService { /** * The default secure IRC server port. */ private static final int DEFAULT_SECURE_IRC_PORT = 6697; /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(ProtocolProviderServiceIrcImpl.class); /** * The irc server. */ private IrcStack ircstack = null; /** * The id of the account that this protocol provider represents. */ private AccountID accountID = null; /** * We use this to lock access to initialization. */ private final Object initializationLock = new Object(); /** * The operation set managing multi user chat. */ private OperationSetMultiUserChatIrcImpl multiUserChat; /** * The operation set for instant messaging. */ private OperationSetBasicInstantMessagingIrcImpl instantMessaging; /** * The operation set for persistent presence. */ private OperationSetPersistentPresenceIrcImpl persistentPresence; /** * Indicates whether or not the provider is initialized and ready for use. */ private boolean isInitialized = false; /** * The icon corresponding to the irc protocol. */ private final ProtocolIconIrcImpl ircIcon = new ProtocolIconIrcImpl(); /** * Keeps our current registration state. */ private RegistrationState currentRegistrationState = RegistrationState.UNREGISTERED; /** * The default constructor for the IRC protocol provider. */ public ProtocolProviderServiceIrcImpl() { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Creating a irc provider."); } } /** * Initializes the service implementation, and puts it in a state where it * could operate with other services. It is strongly recommended that * properties in this Map be mapped to property names as specified by * <tt>AccountProperties</tt>. * * @param userID the user id of the IRC account we're currently * initializing * @param accountID the identifier of the account that this protocol * provider represents. * * @see net.java.sip.communicator.service.protocol.AccountID */ protected void initialize(final String userID, final AccountID accountID) { synchronized (initializationLock) { this.accountID = accountID; //Initialize instant message transform support. addSupportedOperationSet(OperationSetInstantMessageTransform.class, new OperationSetInstantMessageTransformImpl()); //Initialize the multi user chat support multiUserChat = new OperationSetMultiUserChatIrcImpl(this); addSupportedOperationSet( OperationSetMultiUserChat.class, multiUserChat); // Initialize basic instant messaging this.instantMessaging = new OperationSetBasicInstantMessagingIrcImpl(this); // Register basic instant messaging support. addSupportedOperationSet(OperationSetBasicInstantMessaging.class, this.instantMessaging); // Register basic instant messaging transport support. addSupportedOperationSet( OperationSetBasicInstantMessagingTransport.class, this.instantMessaging); //Initialize persistent presence persistentPresence = new OperationSetPersistentPresenceIrcImpl(this); // Register persistent presence support. addSupportedOperationSet(OperationSetPersistentPresence.class, persistentPresence); // Also register for (simple) presence support. addSupportedOperationSet(OperationSetPresence.class, persistentPresence); // TODO Implement OperationSetChangePassword and channel password // changes to IRC remote identity services such as NickServ final String user = getAccountID().getUserID(); ircstack = new IrcStack(this, user, user, "Jitsi", user); isInitialized = true; } } /** * Get the Multi User Chat implementation. * * @return returns the Multi User Chat implementation */ public OperationSetMultiUserChatIrcImpl getMUC() { return this.multiUserChat; } /** * Get the Basic Instant Messaging implementation. * * @return returns the Basic Instant Messaging implementation */ public OperationSetBasicInstantMessagingIrcImpl getBasicInstantMessaging() { return this.instantMessaging; } /** * Get the Persistent Presence implementation. * * @return returns the Persistent Presence implementation. */ public OperationSetPersistentPresenceIrcImpl getPersistentPresence() { return this.persistentPresence; } /** * Returns the AccountID that uniquely identifies the account represented * by this instance of the ProtocolProviderService. * * @return the id of the account represented by this provider. */ public AccountID getAccountID() { return accountID; } /** * Returns the short name of the protocol that the implementation of this * provider is based upon (like SIP, Jabber, ICQ/AIM, or others for * example). * * @return a String containing the short name of the protocol this * service is implementing (most often that would be a name in * ProtocolNames). */ public String getProtocolName() { return ProtocolNames.IRC; } /** * Returns the state of the registration of this protocol provider with * the corresponding registration service. * * @return ProviderRegistrationState */ public RegistrationState getRegistrationState() { return currentRegistrationState; } /** * Starts the registration process. * * @param authority the security authority that will be used for * resolving any security challenges that may be returned during the * registration or at any moment while wer're registered. * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void register(final SecurityAuthority authority) throws OperationFailedException { AccountID accountID = getAccountID(); String serverAddress = accountID .getAccountPropertyString( ProtocolProviderFactory.SERVER_ADDRESS); int serverPort = accountID .getAccountPropertyInt( ProtocolProviderFactory.SERVER_PORT, DEFAULT_SECURE_IRC_PORT); //Verify whether a password has already been stored for this account String serverPassword = IrcActivator. getProtocolProviderFactory().loadPassword(getAccountID()); boolean autoNickChange = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.AUTO_CHANGE_USER_NAME, true); boolean passwordRequired = !accountID.getAccountPropertyBoolean( ProtocolProviderFactory.NO_PASSWORD_REQUIRED, true); boolean secureConnection = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.DEFAULT_ENCRYPTION, true); //if we don't - retrieve it from the user through the security authority if (serverPassword == null && passwordRequired) { //create a default credentials object UserCredentials credentials = new UserCredentials(); credentials.setUserName(getAccountID().getUserID()); //request a password from the user credentials = authority.obtainCredentials( ProtocolNames.IRC, credentials, SecurityAuthority.AUTHENTICATION_REQUIRED); char[] pass = null; if (credentials != null) { // extract the password the user passed us. pass = credentials.getPassword(); } // the user didn't provide us a password (canceled the operation) if (pass == null) { fireRegistrationStateChanged( getRegistrationState(), RegistrationState.UNREGISTERED, RegistrationStateChangeEvent.REASON_USER_REQUEST, ""); return; } serverPassword = new String(pass); //if the user indicated that the password should be saved, we'll ask //the proto provider factory to store it for us. if (credentials.isPasswordPersistent()) { IrcActivator.getProtocolProviderFactory() .storePassword(getAccountID(), serverPassword); } } try { this.ircstack.connect(serverAddress, serverPort, serverPassword, secureConnection, autoNickChange); } catch (Exception e) { throw new OperationFailedException(e.getMessage(), 0, e); } } /** * Makes the service implementation close all open sockets and release * any resources that it might have taken and prepare for * shutdown/garbage collection. */ public void shutdown() { if (!isInitialized) { return; } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Killing the Irc Protocol Provider."); } try { synchronized (this.initializationLock) { unregister(); this.ircstack.dispose(); ircstack = null; } } catch (OperationFailedException ex) { // we're shutting down so we need to silence the exception here LOGGER.error("Failed to properly unregister before shutting down. " + getAccountID(), ex); } } /** * Ends the registration of this protocol provider with the current * registration service. * * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void unregister() throws OperationFailedException { if (this.ircstack == null) { return; } this.ircstack.disconnect(); } /** * {@inheritDoc} * * @return returns true in case of secure transport, or false if transport * is not secure */ @Override public boolean isSignalingTransportSecure() { final IrcConnection connection = this.ircstack.getConnection(); return connection != null && connection.isSecureConnection(); } /** * Returns the "transport" protocol of this instance used to carry the * control channel for the current protocol service. * * @return The "transport" protocol of this instance: TCP. */ public TransportProtocol getTransportProtocol() { return TransportProtocol.TCP; } /** * Returns the icon for this protocol. * * @return the icon for this protocol */ public ProtocolIcon getProtocolIcon() { return ircIcon; } /** * Returns the IRC stack implementation. * * @return the IRC stack implementation. */ public IrcStack getIrcStack() { return ircstack; } /** * Returns the current registration state of this protocol provider. * * @return the current registration state of this protocol provider */ protected RegistrationState getCurrentRegistrationState() { return currentRegistrationState; } /** * Sets the current registration state of this protocol provider. * * @param regState the new registration state to set */ protected void setCurrentRegistrationState( final RegistrationState regState) { final RegistrationState oldState = this.currentRegistrationState; this.currentRegistrationState = regState; fireRegistrationStateChanged( oldState, this.currentRegistrationState, RegistrationStateChangeEvent.REASON_USER_REQUEST, null); } }
package org.mtransit.parser.ca_gtha_go_transit_train; import java.util.HashSet; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.Utils; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.mt.data.MTrip; import org.mtransit.parser.mt.data.MTripStop; public class GTHAGOTransitTrainAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-gtha-go-transit-train-android/res/raw/"; args[2] = ""; // files-prefix } new GTHAGOTransitTrainAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { System.out.printf("\nGenerating GO Transit train data..."); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this); super.start(args); System.out.printf("\nGenerating GO Transit train data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludeCalendar(GCalendar gCalendar) { if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } @Override public boolean excludeTrip(GTrip gTrip) { if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_TRAIN; } private static final Pattern DIGITS = Pattern.compile("[\\d]+"); private static final long LW_RID = 1l; // Lakeshore West private static final long MI_RID = 2l; // Milton private static final long GT_RID = 3l; // Kitchener private static final long BR_RID = 5l; // Barrie private static final long RH_RID = 6l; // Richmond Hill private static final long ST_RID = 7l; // Stouffville private static final long LE_RID = 9l; // Lakeshore East @Override public long getRouteId(GRoute gRoute) { if (ST_RSN.equals(gRoute.getRouteShortName())) { return ST_RID; } else if (RH_RSN.equals(gRoute.getRouteShortName())) { return RH_RID; } else if (MI_RSN.equals(gRoute.getRouteShortName())) { return MI_RID; } else if (LW_RSN.equals(gRoute.getRouteShortName())) { return LW_RID; } else if (LE_RSN.equals(gRoute.getRouteShortName())) { return LE_RID; } else if (GT_RSN.equals(gRoute.getRouteShortName())) { return GT_RID; } else if (BR_RSN.equals(gRoute.getRouteShortName())) { return BR_RID; } else { System.out.println("Unexpected route ID " + gRoute); System.exit(-1); return -1l; } } @Override public String getRouteLongName(GRoute gRoute) { String routeLongName = gRoute.getRouteLongName(); routeLongName = CleanUtils.cleanStreetTypes(routeLongName); return CleanUtils.cleanLabel(routeLongName); } private static final String ST_RSN = "ST"; // Stouffville private static final String RH_RSN = "RH"; // Richmond Hill private static final String MI_RSN = "MI"; // Milton private static final String LW_RSN = "LW"; // Lakeshore West private static final String LE_RSN = "LE"; // Lakeshore East private static final String GT_RSN = "GT"; // Kitchener private static final String BR_RSN = "BR"; // Barrie private static final String AGENCY_COLOR = "387C2B"; // GREEN (AGENCY WEB SITE CSS) @Override public String getAgencyColor() { return AGENCY_COLOR; } private static final String COLOR_BC6277 = "BC6277"; private static final String COLOR_F46F1A = "F46F1A"; private static final String COLOR_098137 = "098137"; private static final String COLOR_0B335E = "0B335E"; private static final String COLOR_0098C9 = "0098C9"; private static final String COLOR_713907 = "713907"; private static final String COLOR_96092B = "96092B"; private static final String COLOR_EE3124 = "EE3124"; @Override public String getRouteColor(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.getRouteColor())) { Matcher matcher = DIGITS.matcher(gRoute.getRouteId()); matcher.find(); int routeId = Integer.parseInt(matcher.group()); switch (routeId) { // @formatter:off case 1: return COLOR_96092B; // Lakeshore West case 2: return COLOR_F46F1A; // Milton case 3: return COLOR_098137; // Kitchener case 5: return COLOR_0B335E; // Barrie case 6: return COLOR_0098C9; // Richmond Hill case 7: return COLOR_713907; // Stouffville case 8: return COLOR_BC6277; // Niagara Falls case 9: return COLOR_EE3124; // Lakeshore East // @formatter:on default: System.out.println("getRouteColor() > Unexpected route ID color '" + routeId + "' (" + gRoute + ")"); System.exit(-1); return null; } } return super.getRouteColor(gRoute); } @Override public int compare(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { if (routeId == LW_RID) { if (ts1.getTripId() == 101) { if (SID_EX.equals(ts1GStop.getStopId()) && SID_UN.equals(ts2GStop.getStopId())) { return +1; } } } System.out.printf("\n%s: Unexpected compare early route!\n", routeId); System.exit(-1); return -1; } private static final String STOUFFVILLE = "Stouffville"; private static final String BARRIE = "Barrie"; private static final String KITCHENER = "Kitchener"; private static final String UNION = "Union"; private static final String EAST = "East"; private static final String WEST = "West"; @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (mRoute.getId() == LW_RID) { // Lakeshore West if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(UNION, gTrip.getDirectionId()); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(WEST, gTrip.getDirectionId()); return; } } else if (mRoute.getId() == GT_RID) { // Kitchener if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(KITCHENER, gTrip.getDirectionId()); return; } } else if (mRoute.getId() == BR_RID) { // Barrie if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(BARRIE, gTrip.getDirectionId()); return; } } else if (mRoute.getId() == ST_RID) { // Stouffville if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(STOUFFVILLE, gTrip.getDirectionId()); return; } } else if (mRoute.getId() == LE_RID) { // Lakeshore East if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(EAST, gTrip.getDirectionId()); return; } } mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId()); } private static final Pattern START_WITH_RSN = Pattern.compile("(^[A-Z]{2}\\-)", Pattern.CASE_INSENSITIVE); @Override public String cleanTripHeadsign(String tripHeadsign) { tripHeadsign = START_WITH_RSN.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY); tripHeadsign = GO.matcher(tripHeadsign).replaceAll(GO_REPLACEMENT); tripHeadsign = STATION.matcher(tripHeadsign).replaceAll(STATION_REPLACEMENT); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } private static final Pattern GO = Pattern.compile("(^|\\s){1}(go)($|\\s){1}", Pattern.CASE_INSENSITIVE); private static final String GO_REPLACEMENT = " "; private static final Pattern VIA = Pattern.compile("(^|\\s){1}(via)($|\\s){1}", Pattern.CASE_INSENSITIVE); private static final String VIA_REPLACEMENT = " "; private static final Pattern RAIL = Pattern.compile("(^|\\s){1}(rail)($|\\s){1}", Pattern.CASE_INSENSITIVE); private static final String RAIL_REPLACEMENT = " "; private static final Pattern STATION = Pattern.compile("(^|\\s){1}(station)($|\\s){1}", Pattern.CASE_INSENSITIVE); private static final String STATION_REPLACEMENT = " "; @Override public String cleanStopName(String gStopName) { gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); gStopName = VIA.matcher(gStopName).replaceAll(VIA_REPLACEMENT); gStopName = GO.matcher(gStopName).replaceAll(GO_REPLACEMENT); gStopName = RAIL.matcher(gStopName).replaceAll(RAIL_REPLACEMENT); gStopName = STATION.matcher(gStopName).replaceAll(STATION_REPLACEMENT); gStopName = CleanUtils.cleanNumbers(gStopName); gStopName = CleanUtils.cleanStreetTypes(gStopName); return CleanUtils.cleanLabel(gStopName); } private static final String SID_UN = "UN"; private static final int UN_SID = 9021; private static final String SID_EX = "EX"; private static final int EX_SID = 9022; private static final String SID_MI = "MI"; private static final int MI_SID = 9031; private static final String SID_LO = "LO"; private static final int LO_SID = 9033; private static final String SID_DA = "DA"; private static final int DA_SID = 9061; private static final String SID_SC = "SC"; private static final int SC_SID = 9062; private static final String SID_EG = "EG"; private static final int EG_SID = 9063; private static final String SID_GU = "GU"; private static final int GU_SID = 9081; private static final String SID_RO = "RO"; private static final int RO_SID = 9091; private static final String SID_PO = "PO"; private static final int PO_SID = 9111; private static final String SID_CL = "CL"; private static final int CL_SID = 9121; private static final String SID_OA = "OA"; private static final int OA_SID = 9131; private static final String SID_BO = "BO"; private static final int BO_SID = 9141; private static final String SID_AP = "AP"; private static final int AP_SID = 9151; private static final String SID_BU = "BU"; private static final int BU_SID = 9161; private static final String SID_AL = "AL"; private static final int AL_SID = 9171; private static final String SID_PIN = "PIN"; private static final int PIN_SID = 9911; private static final String SID_AJ = "AJ"; private static final int AJ_SID = 9921; private static final String SID_WH = "WH"; private static final int WH_SID = 9939; private static final String SID_OS = "OS"; private static final int OS_SID = 9941; private static final String SID_BL = "BL"; private static final int BL_SID = 9023; private static final String SID_KP = "KP"; private static final int KP_SID = 9032; private static final String SID_WE = "WE"; private static final int WE_SID = 9041; private static final String SID_ET = "ET"; private static final int ET_SID = 9042; private static final String SID_OR = "OR"; private static final int OR_SID = 9051; private static final String SID_OL = "OL"; private static final int OL_SID = 9052; private static final String SID_AG = "AG"; private static final int AG_SID = 9071; private static final String SID_DI = "DI"; private static final int DI_SID = 9113; private static final String SID_CO = "CO"; private static final int CO_SID = 9114; private static final String SID_ER = "ER"; private static final int ER_SID = 9123; private static final String SID_HA = "HA"; private static final int HA_SID = 9181; private static final String SID_YO = "YO"; private static final int YO_SID = 9191; private static final String SID_SR = "SR"; private static final int SR_SID = 9211; private static final String SID_ME = "ME"; private static final int ME_SID = 9221; private static final String SID_LS = "LS"; private static final int LS_SID = 9231; private static final String SID_ML = "ML"; private static final int ML_SID = 9241; private static final String SID_KI = "KI"; private static final int KI_SID = 9271; private static final String SID_MA = "MA"; private static final int MA_SID = 9311; private static final String SID_BE = "BE"; private static final int BE_SID = 9321; private static final String SID_BR = "BR"; private static final int BR_SID = 9331; private static final String SID_MO = "MO"; private static final int MO_SID = 9341; private static final String SID_GE = "GE"; private static final int GE_SID = 9351; private static final String SID_AC = "AC"; private static final int AC_SID = 9371; private static final String SID_GL = "GL"; private static final int GL_SID = 9391; private static final String SID_EA = "EA"; private static final int EA_SID = 9441; private static final String SID_LA = "LA"; private static final int LA_SID = 9601; private static final String SID_RI = "RI"; private static final int RI_SID = 9612; private static final String SID_MP = "MP"; private static final int MP_SID = 9613; private static final String SID_RU = "RU"; private static final int RU_SID = 9614; private static final String SID_KC = "KC"; private static final int KC_SID = 9621; private static final String SID_AU = "AU"; private static final int AU_SID = 9631; private static final String SID_NE = "NE"; private static final int NE_SID = 9641; private static final String SID_BD = "BD"; private static final int BD_SID = 9651; private static final String SID_BA = "BA"; private static final int BA_SID = 9681; private static final String SID_AD = "AD"; private static final int AD_SID = 9691; private static final String SID_MK = "MK"; private static final int MK_SID = 9701; private static final String SID_UI = "UI"; private static final int UI_SID = 9712; private static final String SID_MR = "MR"; private static final int MR_SID = 9721; private static final String SID_CE = "CE"; private static final int CE_SID = 9722; private static final String SID_MJ = "MJ"; private static final int MJ_SID = 9731; private static final String SID_ST = "ST"; private static final int ST_SID = 9741; private static final String SID_LI = "LI"; private static final int LI_SID = 9742; private static final String SID_KE = "KE"; private static final int KE_SID = 9771; private static final String SID_WR = "WR"; private static final int WR_SID = 100001; private static final String SID_USBT = "USBT"; private static final int USBT_SID = 100002; private static final String SID_NI = "NI"; private static final int NI_SID = 100003; private static final String SID_PA = "PA"; private static final int PA_SID = 100004; private static final String SID_SCTH = "SCTH"; private static final int SCTH_SID = 100005; @Override public int getStopId(GStop gStop) { if (!Utils.isDigitsOnly(gStop.getStopId())) { if (SID_UN.equals(gStop.getStopId())) { return UN_SID; } else if (SID_EX.equals(gStop.getStopId())) { return EX_SID; } else if (SID_MI.equals(gStop.getStopId())) { return MI_SID; } else if (SID_LO.equals(gStop.getStopId())) { return LO_SID; } else if (SID_DA.equals(gStop.getStopId())) { return DA_SID; } else if (SID_SC.equals(gStop.getStopId())) { return SC_SID; } else if (SID_EG.equals(gStop.getStopId())) { return EG_SID; } else if (SID_GU.equals(gStop.getStopId())) { return GU_SID; } else if (SID_RO.equals(gStop.getStopId())) { return RO_SID; } else if (SID_PO.equals(gStop.getStopId())) { return PO_SID; } else if (SID_CL.equals(gStop.getStopId())) { return CL_SID; } else if (SID_OA.equals(gStop.getStopId())) { return OA_SID; } else if (SID_BO.equals(gStop.getStopId())) { return BO_SID; } else if (SID_AP.equals(gStop.getStopId())) { return AP_SID; } else if (SID_BU.equals(gStop.getStopId())) { return BU_SID; } else if (SID_AL.equals(gStop.getStopId())) { return AL_SID; } else if (SID_PIN.equals(gStop.getStopId())) { return PIN_SID; } else if (SID_AJ.equals(gStop.getStopId())) { return AJ_SID; } else if (SID_WH.equals(gStop.getStopId())) { return WH_SID; } else if (SID_OS.equals(gStop.getStopId())) { return OS_SID; } else if (SID_BL.equals(gStop.getStopId())) { return BL_SID; } else if (SID_KP.equals(gStop.getStopId())) { return KP_SID; } else if (SID_WE.equals(gStop.getStopId())) { return WE_SID; } else if (SID_ET.equals(gStop.getStopId())) { return ET_SID; } else if (SID_OR.equals(gStop.getStopId())) { return OR_SID; } else if (SID_OL.equals(gStop.getStopId())) { return OL_SID; } else if (SID_AG.equals(gStop.getStopId())) { return AG_SID; } else if (SID_DI.equals(gStop.getStopId())) { return DI_SID; } else if (SID_CO.equals(gStop.getStopId())) { return CO_SID; } else if (SID_ER.equals(gStop.getStopId())) { return ER_SID; } else if (SID_HA.equals(gStop.getStopId())) { return HA_SID; } else if (SID_YO.equals(gStop.getStopId())) { return YO_SID; } else if (SID_SR.equals(gStop.getStopId())) { return SR_SID; } else if (SID_ME.equals(gStop.getStopId())) { return ME_SID; } else if (SID_LS.equals(gStop.getStopId())) { return LS_SID; } else if (SID_ML.equals(gStop.getStopId())) { return ML_SID; } else if (SID_KI.equals(gStop.getStopId())) { return KI_SID; } else if (SID_MA.equals(gStop.getStopId())) { return MA_SID; } else if (SID_BE.equals(gStop.getStopId())) { return BE_SID; } else if (SID_BR.equals(gStop.getStopId())) { return BR_SID; } else if (SID_MO.equals(gStop.getStopId())) { return MO_SID; } else if (SID_GE.equals(gStop.getStopId())) { return GE_SID; } else if (SID_AC.equals(gStop.getStopId())) { return AC_SID; } else if (SID_GL.equals(gStop.getStopId())) { return GL_SID; } else if (SID_EA.equals(gStop.getStopId())) { return EA_SID; } else if (SID_LA.equals(gStop.getStopId())) { return LA_SID; } else if (SID_RI.equals(gStop.getStopId())) { return RI_SID; } else if (SID_MP.equals(gStop.getStopId())) { return MP_SID; } else if (SID_RU.equals(gStop.getStopId())) { return RU_SID; } else if (SID_KC.equals(gStop.getStopId())) { return KC_SID; } else if (SID_AU.equals(gStop.getStopId())) { return AU_SID; } else if (SID_NE.equals(gStop.getStopId())) { return NE_SID; } else if (SID_BD.equals(gStop.getStopId())) { return BD_SID; } else if (SID_BA.equals(gStop.getStopId())) { return BA_SID; } else if (SID_AD.equals(gStop.getStopId())) { return AD_SID; } else if (SID_MK.equals(gStop.getStopId())) { return MK_SID; } else if (SID_UI.equals(gStop.getStopId())) { return UI_SID; } else if (SID_MR.equals(gStop.getStopId())) { return MR_SID; } else if (SID_CE.equals(gStop.getStopId())) { return CE_SID; } else if (SID_MJ.equals(gStop.getStopId())) { return MJ_SID; } else if (SID_ST.equals(gStop.getStopId())) { return ST_SID; } else if (SID_LI.equals(gStop.getStopId())) { return LI_SID; } else if (SID_KE.equals(gStop.getStopId())) { return KE_SID; } else if (SID_WR.equals(gStop.getStopId())) { return WR_SID; } else if (SID_USBT.equals(gStop.getStopId())) { return USBT_SID; } else if (SID_NI.equals(gStop.getStopId())) { return NI_SID; } else if (SID_PA.equals(gStop.getStopId())) { return PA_SID; } else if (SID_SCTH.equals(gStop.getStopId())) { return SCTH_SID; } else { System.out.printf("\nUnexpected stop ID %s.\n", gStop); System.exit(-1); return -1; } } return super.getStopId(gStop); } }
package org.ow2.proactive.resourcemanager.utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.security.KeyException; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.Parser; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.objectweb.proactive.core.config.xml.ProActiveConfigurationParser; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeFactory; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.ow2.proactive.authentication.crypto.Credentials; import org.ow2.proactive.resourcemanager.authentication.RMAuthentication; import org.ow2.proactive.resourcemanager.common.RMConstants; import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties; import org.ow2.proactive.resourcemanager.exception.AddingNodesException; import org.ow2.proactive.resourcemanager.frontend.RMConnection; import org.ow2.proactive.resourcemanager.frontend.ResourceManager; import org.ow2.proactive.utils.console.JVMPropertiesPreloader; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * This class is responsible for creating a local node. You can define different settings to * register the node to an apropriate Resource Manager, ping it... * * @author ProActive team */ public class RMNodeStarter { protected Credentials credentials = null; protected String rmURL = null; protected String nodeName = RMNodeStarter.PAAGENT_DEFAULT_NODE_NAME; protected String nodeSourceName = null; /** Class' logger */ protected static final Logger logger = ProActiveLogger.getLogger(RMLoggers.RMNODE); /** The default name of the node */ protected static final String PAAGENT_DEFAULT_NODE_NAME = "PA-AGENT_NODE"; /** Prefix for temp files that store nodes URL */ protected static final String URL_TMPFILE_PREFIX = "PA-AGENT_URL"; /** Name of the java property to set the rank */ protected final static String RANK_PROP_NAME = "pa.agent.rank"; /** * The starter will try to connect to the Resource Manager before killing * itself that means that it will try to connect during * WAIT_ON_JOIN_TIMEOUT_IN_MS milliseconds */ protected static int WAIT_ON_JOIN_TIMEOUT_IN_MS = 60000; /** * The ping delay used in RMPinger that pings the RM and exists if the * Resource Manager is down */ protected static long PING_DELAY_IN_MS = 30000; /** The number of attempts to add the local node to the RM before quitting */ protected static int NB_OF_ADD_NODE_ATTEMPTS = 10; /** The delay, in millis, between two attempts to add a node */ protected static int ADD_NODE_ATTEMPTS_DELAY_IN_MS = 5000; // The url of the created node protected String nodeURL = "Not defined"; // the rank of this node protected int rank; // if true, previous nodes with different URLs are removed from the RM protected boolean removePrevious; public static final char OPTION_CREDENTIAL_FILE = 'f'; public static final char OPTION_CREDENTIAL_ENV = 'e'; public static final char OPTION_CREDENTIAL_VAL = 'v'; public static final char OPTION_RM_URL = 'r'; public static final char OPTION_NODE_NAME = 'n'; public static final char OPTION_SOURCE_NAME = 's'; public static final char OPTION_WAIT_AND_JOIN_TIMEOUT = 'w'; public static final char OPTION_PING_DELAY = 'p'; public static final char OPTION_ADD_NODE_ATTEMPTS = 'a'; public static final char OPTION_ADD_NODE_ATTEMPTS_DELAY = 'd'; public static final char OPTION_HELP = 'h'; public RMNodeStarter() { } /** * Returns the rank of this node * @return the rank of this node */ public int getRank() { return rank; } /** * Returns the URL of the node handled by this starter. * @return the URL of the node handled by this starter. */ public String getNodeURL() { return this.nodeURL; } /** * Fills the command line options. * @param options the options to fill */ protected void fillOptions(final Options options) { // The path to the file that contains the credential final Option credentialFile = new Option(new Character(OPTION_CREDENTIAL_FILE).toString(), "credentialFile", true, "path to file that contains the credential"); credentialFile.setRequired(false); credentialFile.setArgName("path"); options.addOption(credentialFile); // The credential passed as environment variable final Option credentialEnv = new Option(new Character(OPTION_CREDENTIAL_ENV).toString(), "credentialEnv", true, "name of the environment variable that contains the credential"); credentialEnv.setRequired(false); credentialEnv.setArgName("name"); options.addOption(credentialEnv); // The credential passed as value final Option credVal = new Option(new Character(OPTION_CREDENTIAL_VAL).toString(), "credentialVal", true, "explicit value of the credential"); credVal.setRequired(false); credVal.setArgName("credential"); options.addOption(credVal); // The url of the resource manager final Option rmURL = new Option(new Character(OPTION_RM_URL).toString(), "rmURL", true, "URL of the resource manager. If no URL is provided, the node won't register."); rmURL.setRequired(false); rmURL.setArgName("url"); options.addOption(rmURL); // The node name final Option nodeName = new Option(new Character(OPTION_NODE_NAME).toString(), "nodeName", true, "node name (default is " + PAAGENT_DEFAULT_NODE_NAME + ")"); nodeName.setRequired(false); nodeName.setArgName("name"); options.addOption(nodeName); // The node source name final Option sourceName = new Option(new Character(OPTION_SOURCE_NAME).toString(), "sourceName", true, "node source name"); sourceName.setRequired(false); sourceName.setArgName("name"); options.addOption(sourceName); // The wait on join timeout in millis final Option waitOnJoinTimeout = new Option(new Character(OPTION_WAIT_AND_JOIN_TIMEOUT).toString(), "waitOnJoinTimeout", true, "wait on join the resource manager timeout in millis (default is " + WAIT_ON_JOIN_TIMEOUT_IN_MS + ")"); waitOnJoinTimeout.setRequired(false); waitOnJoinTimeout.setArgName("millis"); options.addOption(waitOnJoinTimeout); // The ping delay in millis final Option pingDelay = new Option( new Character(OPTION_PING_DELAY).toString(), "pingDelay", true, "ping delay in millis used by RMPinger thread that calls System.exit(1) if the resource manager is down (default is " + PING_DELAY_IN_MS + "). A nul or negative frequence means no ping at all."); pingDelay.setRequired(false); pingDelay.setArgName("millis"); options.addOption(pingDelay); // The number of attempts option final Option addNodeAttempts = new Option(new Character(OPTION_ADD_NODE_ATTEMPTS).toString(), "addNodeAttempts", true, "number of attempts to add the local node to the resource manager before quitting (default is " + NB_OF_ADD_NODE_ATTEMPTS + ")"); addNodeAttempts.setRequired(false); addNodeAttempts.setArgName("number"); options.addOption(addNodeAttempts); // The delay between attempts option final Option addNodeAttemptsDelay = new Option(new Character(OPTION_ADD_NODE_ATTEMPTS_DELAY) .toString(), "addNodeAttemptsDelay", true, "delay in millis between attempts to add the local node to the resource manager (default is " + ADD_NODE_ATTEMPTS_DELAY_IN_MS + ")"); addNodeAttemptsDelay.setRequired(false); addNodeAttemptsDelay.setArgName("millis"); options.addOption(addNodeAttemptsDelay); // Displays the help final Option help = new Option(new Character(OPTION_HELP).toString(), "help", false, "to display this help"); help.setRequired(false); options.addOption(help); } /** * Creates a new instance of this class and calls registersInRm method. * @param args The arguments needed to join the Resource Manager */ public static void main(String[] args) { //this call takes JVM properties into account args = JVMPropertiesPreloader.overrideJVMProperties(args); checkLog4jConfiguration(); RMNodeStarter starter = new RMNodeStarter(); starter.doMain(args); } protected void doMain(final String args[]) { this.parseCommandLine(args); this.readAndSetTheRank(); Node node = this.createLocalNode(nodeName); this.nodeURL = node.getNodeInformation().getURL(); System.out.println(this.nodeURL); if (rmURL != null) { ResourceManager rm = this.registerInRM(credentials, rmURL, nodeName, nodeSourceName); if (rm != null) { System.out.println("Connected to the Resource Manager at " + rmURL + System.getProperty("line.separator")); // start pinging... // ping the im to see if we are still connected // if not connected just exit // isActive throws an exception is not connected // ping is optional, that allows other implementation // of RMNodeStarter to be cached for futur use by the // infrastructure manager if (PING_DELAY_IN_MS > 0) { try { while (rm.nodeIsAvailable(this.getNodeURL()).getBooleanValue()) { try { Thread.sleep(PING_DELAY_IN_MS); } catch (InterruptedException e) { } }// while connected } catch (Throwable e) { // no more connected to the RM System.out .println("The connection to the Resource Manager has been lost. The application will exit."); e.printStackTrace(); System.exit(ExitStatus.RM_NO_PING.exitCode); } // if we are here it means we lost the connection. just exit.. System.out.println("The Resource Manager has been shutdown. The application will exit. "); System.err.println(ExitStatus.RM_IS_SHUTDOWN.description); System.exit(ExitStatus.RM_IS_SHUTDOWN.exitCode); } } else { // Force system exit to bypass daemon threads System.err.println(ExitStatus.RMNODE_EXIT_FORCED.description); System.exit(ExitStatus.RMNODE_EXIT_FORCED.exitCode); } } } protected void fillParameters(final CommandLine cl, final Options options) { boolean printHelp = false; try { // Optional rmURL option if (cl.hasOption(OPTION_RM_URL)) { rmURL = cl.getOptionValue(OPTION_RM_URL); } // if the user doesn't provide a rm URL, we don't care about the credentials if (rmURL != null) { // The path to the file that contains the credential if (cl.hasOption(OPTION_CREDENTIAL_FILE)) { try { credentials = Credentials.getCredentials(cl.getOptionValue(OPTION_CREDENTIAL_FILE)); } catch (KeyException ke) { System.err.println(ExitStatus.CRED_UNREADABLE.description); System.exit(ExitStatus.CRED_UNREADABLE.exitCode); } // The name of the env variable that contains } else if (cl.hasOption(OPTION_CREDENTIAL_ENV)) { final String variableName = cl.getOptionValue(OPTION_CREDENTIAL_ENV); final String value = System.getenv(variableName); if (value == null) { System.err.println(ExitStatus.CRED_ENVIRONMENT.description); System.exit(ExitStatus.CRED_ENVIRONMENT.exitCode); } try { credentials = Credentials.getCredentialsBase64(value.getBytes()); } catch (KeyException ke) { ke.printStackTrace(); System.exit(ExitStatus.CRED_DECODE.exitCode); } // Read the credentials directly from the command-line argument } else if (cl.hasOption(OPTION_CREDENTIAL_VAL)) { final String str = cl.getOptionValue(OPTION_CREDENTIAL_VAL); try { credentials = Credentials.getCredentialsBase64(str.getBytes()); } catch (KeyException ke) { ke.printStackTrace(); System.exit(ExitStatus.CRED_DECODE.exitCode); } } else { try { credentials = Credentials.getCredentials(); } catch (KeyException ke) { ke.printStackTrace(); System.exit(ExitStatus.CRED_UNREADABLE.exitCode); } } } // Optional node name if (cl.hasOption(OPTION_NODE_NAME)) { nodeName = cl.getOptionValue(OPTION_NODE_NAME); } // Optional node source name if (cl.hasOption(OPTION_SOURCE_NAME)) { nodeSourceName = cl.getOptionValue(OPTION_SOURCE_NAME); } // Optional wait on join option if (cl.hasOption(OPTION_WAIT_AND_JOIN_TIMEOUT)) { RMNodeStarter.WAIT_ON_JOIN_TIMEOUT_IN_MS = Integer.valueOf(cl .getOptionValue(OPTION_WAIT_AND_JOIN_TIMEOUT)); } // Optional ping delay if (cl.hasOption(OPTION_PING_DELAY)) { RMNodeStarter.PING_DELAY_IN_MS = Integer.valueOf(cl.getOptionValue(OPTION_PING_DELAY)); } // Optional number of add node attempts before quitting if (cl.hasOption(OPTION_ADD_NODE_ATTEMPTS)) { RMNodeStarter.NB_OF_ADD_NODE_ATTEMPTS = Integer.valueOf(cl .getOptionValue(OPTION_ADD_NODE_ATTEMPTS)); } // Optional delay between add node attempts if (cl.hasOption(OPTION_ADD_NODE_ATTEMPTS_DELAY)) { RMNodeStarter.ADD_NODE_ATTEMPTS_DELAY_IN_MS = Integer.valueOf(cl .getOptionValue(OPTION_ADD_NODE_ATTEMPTS_DELAY)); } // Optional help option if (cl.hasOption(OPTION_HELP)) { printHelp = true; } } catch (Throwable t) { printHelp = true; System.out.println(t.getMessage()); t.printStackTrace(); System.exit(ExitStatus.FAILED_TO_LAUNCH.exitCode); } finally { if (printHelp) { // Automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); // Prints usage formatter.printHelp("java " + RMNodeStarter.class.getName(), options); } } } protected void parseCommandLine(String[] args) { final Options options = new Options(); //we fill int the options object, child classes can override this method //to add new options... fillOptions(options); final Parser parser = new GnuParser(); CommandLine cl; try { cl = parser.parse(options, args); //now we update this object's fields given the options. fillParameters(cl, options); } catch (ParseException pe) { pe.printStackTrace(); System.exit(ExitStatus.RMNODE_PARSE_ERROR.exitCode); } } /** * To define the default log4j configuration if log4j.configuration property has not been set. */ public static void checkLog4jConfiguration() { try { String log4jPath = System.getProperty("log4j.configuration"); if (log4jPath == null) { //either sched-home/dist/lib/PA-RM.jar or sched-home/classes/resource-manager/ File origin = new File(RMNodeStarter.class.getProtectionDomain().getCodeSource() .getLocation().getFile()); File parent = origin.getParentFile(); configuration: { while (parent != null && parent.isDirectory()) { File[] childs = parent.listFiles(); for (File child : childs) { if ("config".equals(child.getName())) { //we have found the sched-home/config/ directory! log4jPath = child.getAbsolutePath() + File.separator + "log4j" + File.separator + "defaultNode-log4j"; File log4j = new File(log4jPath); if (log4j.exists()) { URL log4jURL; try { log4jURL = log4j.toURL(); PropertyConfigurator.configure(log4jURL); System.setProperty("log4j.configuration", log4jPath); logger.trace("log4j.configuration not set, " + log4jPath + " defiined as default log4j configuration."); } catch (MalformedURLException e) { logger.trace("Cannot configure log4j", e); } } else { logger.trace("Log4J configuration not found. Cannot configure log4j"); } break configuration; } } parent = parent.getParentFile(); } } } else { logger.trace("Does not override log4j.configuration"); } } catch (Exception ex) { logger.trace("Cannot set log4j Configuration", ex); } } /** * Tries to join to the Resource Manager with a specified timeout * at the given URL, logs with provided credentials and adds the local node to * the Resource Manager. Handles all errors/exceptions. */ protected ResourceManager registerInRM(final Credentials credentials, final String rmURL, final String nodeName, final String nodeSourceName) { // Create the full url to contact the Resource Manager final String fullUrl = rmURL.endsWith("/") ? rmURL + RMConstants.NAME_ACTIVE_OBJECT_RMAUTHENTICATION : rmURL + "/" + RMConstants.NAME_ACTIVE_OBJECT_RMAUTHENTICATION; // Try to join the Resource Manager with a specified timeout RMAuthentication auth = null; try { auth = RMConnection.waitAndJoin(fullUrl, WAIT_ON_JOIN_TIMEOUT_IN_MS); if (auth == null) { System.out.println(ExitStatus.RMAUTHENTICATION_NULL.description); System.err.println(ExitStatus.RMAUTHENTICATION_NULL.description); System.exit(ExitStatus.RMAUTHENTICATION_NULL.exitCode); } } catch (Throwable t) { System.out.println("Unable to join the Resource Manager at " + rmURL); t.printStackTrace(); System.exit(ExitStatus.RMNODE_ADD_ERROR.exitCode); } ResourceManager rm = null; // 3 - Log using credential try { rm = auth.login(credentials); if (rm == null) { System.out.println(ExitStatus.RM_NULL.description); System.err.println(ExitStatus.RM_NULL.description); System.exit(ExitStatus.RM_NULL.exitCode); } } catch (Throwable t) { System.out.println("Unable to log into the Resource Manager at " + rmURL); t.printStackTrace(); System.exit(ExitStatus.RMNODE_ADD_ERROR.exitCode); } // 4 - Add the created node to the Resource Manager with a specified // number of attempts and a timeout between each attempt boolean isNodeAdded = false; int attempts = 0; while ((!isNodeAdded) && (attempts < NB_OF_ADD_NODE_ATTEMPTS)) { attempts++; try { if (this.nodeSourceName != null) { isNodeAdded = rm.addNode(this.nodeURL, this.nodeSourceName).getBooleanValue(); } else { isNodeAdded = rm.addNode(this.nodeURL).getBooleanValue(); } } catch (AddingNodesException addException) { addException.printStackTrace(); System.exit(ExitStatus.RMNODE_ADD_ERROR.exitCode); } if (isNodeAdded) { if (removePrevious) { // try to remove previous URL if different... String previousURL = this.getAndDeleteNodeURL(nodeName, rank); if (previousURL != null && !previousURL.equals(this.nodeURL)) { System.out .println("Different previous URL registered by this agent has been found. Remove previous registration."); rm.removeNode(previousURL, true); } // store the node URL this.storeNodeURL(nodeName, rank, this.nodeURL); System.out.println("Node " + this.nodeURL + " added. URL is stored in " + getNodeURLFilename(nodeName, rank)); } else { System.out.println("Node " + this.nodeURL + " added."); } } else { // not yet registered System.out.println("Attempt number " + attempts + " out of " + NB_OF_ADD_NODE_ATTEMPTS + " to add the local node to the Resource Manager at " + rmURL + " has failed."); try { Thread.sleep(ADD_NODE_ATTEMPTS_DELAY_IN_MS); } catch (InterruptedException e) { e.printStackTrace(); } } }// while if (!isNodeAdded) { System.out.println("The Resource Manager was unable to add the local node " + this.nodeURL + " after " + NB_OF_ADD_NODE_ATTEMPTS + " attempts. The application will exit."); System.err.println(ExitStatus.RMNODE_ADD_ERROR.description); System.exit(ExitStatus.RMNODE_ADD_ERROR.exitCode); }// if not registered return rm; } protected void readAndSetTheRank() { String rankAsString = System.getProperty(RANK_PROP_NAME); if (rankAsString == null) { System.out.println("[WARNING] Rank is not set. Previous URLs will not be stored"); this.removePrevious = false; } else { try { this.rank = Integer.parseInt(rankAsString); this.removePrevious = true; System.out.println("Rank is " + this.rank); } catch (Throwable e) { System.out.println("[WARNING] Rank cannot be read due to " + e.getMessage() + ". Previous URLs will not be stored"); this.removePrevious = false; } } } /** * Creates the node with the name given as parameter and returns it. * @param nodeName The expected name of the node * @return the newly created node. */ protected Node createLocalNode(String nodeName) { Node localNode = null; try { localNode = NodeFactory.createLocalNode(nodeName, false, null, null); if (localNode == null) { System.out.println("The node returned by the NodeFactory is null"); System.err.println(RMNodeStarter.ExitStatus.RMNODE_NULL.description); System.exit(RMNodeStarter.ExitStatus.RMNODE_NULL.exitCode); } } catch (Throwable t) { System.out.println("Unable to create the local node " + nodeName); t.printStackTrace(); System.exit(RMNodeStarter.ExitStatus.RMNODE_ADD_ERROR.exitCode); } return localNode; } /** * Store in a temp file the current URL of the node started by the agent * @param nodeName the name of the node * @param rank the rank of the node * @param nodeURL the URL of the node */ protected void storeNodeURL(String nodeName, int rank, String nodeURL) { try { File f = new File(getNodeURLFilename(nodeName, rank)); if (f.exists()) { System.out.println("[WARNING] NodeURL file already exists ; delete it."); f.delete(); } BufferedWriter out = new BufferedWriter(new FileWriter(f)); out.write(nodeURL); out.write(System.getProperty("line.separator")); out.close(); } catch (IOException e) { System.out.println("[WARNING] NodeURL cannot be created."); e.printStackTrace(); } } /** * Return the previous URL of this node * @param nodeName the name of the node started by the Agent * @param rank the rank of the node * @return the previous URL of this node, null if none can be found */ protected String getAndDeleteNodeURL(String nodeName, int rank) { try { File f = new File(getNodeURLFilename(nodeName, rank)); if (f.exists()) { BufferedReader in = new BufferedReader(new FileReader(f)); String read = in.readLine(); in.close(); f.delete(); return read; } } catch (IOException e) { e.printStackTrace(); } return null; } /** * Create the name of the temp file for storing node URL. */ protected String getNodeURLFilename(String nodeName, int rank) { final String tmpDir = System.getProperty("java.io.tmpdir"); final String tmpFile = tmpDir + "_" + URL_TMPFILE_PREFIX + "_" + nodeName + "-" + rank; return tmpFile; } /** * This enum stands for the entire set of possible exit values of RMNodeStarter */ public enum ExitStatus { OK(0, "Exit success."), //mustn't be changed, return value set in the JVM itself JVM_ERROR(1, "Problem with the Java process itself ( classpath, main method... )."), RM_NO_PING(100, "Cannot ping the Resource Manager because of a Throwable."), RM_IS_SHUTDOWN(101, "The Resource Manager has been shutdown."), CRED_UNREADABLE(200, "Cannot read the submited credential's key."), CRED_DECODE(201, "Cannot decode credential's key from base64."), CRED_ENVIRONMENT(202, "Environment variable not set for credential but it should be."), RMNODE_NULL(300, "NodeFactory returned null as RMNode."), RMAUTHENTICATION_NULL(301, "RMAuthentication instance is null."), RM_NULL(302, "Resource Manager instance is null."), RMNODE_ADD_ERROR( 303, "Was not able to add RMNode the the Resource Manager."), RMNODE_PARSE_ERROR(304, "Problem encountered while parsing " + RMNodeStarter.class.getName() + " command line."), RMNODE_EXIT_FORCED( 305, "Was not able to add RMNode to the Resource Manager. Force system to exit to bypass daemon threads."), FAILED_TO_LAUNCH( -1, RMNodeStarter.class.getSimpleName() + " process hasn't been started at all."), UNKNOWN( -2, "Cannot determine exit status."); public final int exitCode; public final String description; private ExitStatus(int exitCode, String description) { this.exitCode = exitCode; this.description = description; } public String getDescription() { return this.description; } public int getExitCode() { return this.exitCode; } } /** * CommandLineBuilder is an utility class that provide users with the capability to automatise * the RMNodeStarter command line building. We encourage Infrastructure Manager providers to * use this class as it is used as central point for applying changes to the RMNodeStarter * properties, for instance, if the classpath needs to bu updated, a call to * {@link #getRequiredJARs()} will reflect the change. * */ public static final class CommandLineBuilder implements Cloneable { private String nodeName, sourceName, javaPath, rmURL, credentialsFile, credentialsValue, credentialsEnv, rmHome; private long pingDelay = 30000; private Properties paPropProperties; private String paPropString; private int addAttempts = -1, addAttemptsDelay = -1; private final String[] requiredJARs = { "script-js.jar", "jruby-engine.jar", "jython-engine.jar", "commons-logging-1.1.1.jar", "ProActive_SRM-common.jar", "ProActive_ResourceManager.jar", "ProActive_Scheduler-worker.jar", "commons-httpclient-3.1.jar", "commons-codec-1.3.jar", "ProActive.jar" }; private OperatingSystem targetOS = OperatingSystem.UNIX; /** * Returns the jars required by RMNodeStarter in the right order. * @return Returns the jars required by RMNodeStarter in the right order. */ public String[] getRequiredJARs() { return requiredJARs; } /** * To get the RMHome from a previous call to the method {@link #setRmHome(String)}. If such a call has not been made, * one manages to retrieve it from the PAProperties set thanks to a previous call to the method {@link #setPaProperties(byte[])} or {@link #setPaProperties(File)} of {@link #setPaProperties(Map)}. * @return the RMHome which will be used to build the command line. */ public String getRmHome() { if (this.rmHome != null) { return rmHome; } else { if (paPropProperties != null) { String rmHome = null; if (paPropProperties.getProperty(PAResourceManagerProperties.RM_HOME.getKey()) != null && !paPropProperties.getProperty(PAResourceManagerProperties.RM_HOME.getKey()) .equals("")) { rmHome = paPropProperties.getProperty(PAResourceManagerProperties.RM_HOME.getKey()); if (!rmHome.endsWith(String.valueOf(this.targetOS.fs))) { rmHome += String.valueOf(this.targetOS.fs); } } else { if (PAResourceManagerProperties.RM_HOME.isSet()) { rmHome = PAResourceManagerProperties.RM_HOME.getValueAsString(); if (!rmHome.endsWith(String.valueOf(this.targetOS.fs))) { rmHome += String.valueOf(this.targetOS.fs); } } else { logger .warn("No RM Home property found in the supplied configuration. You have to launch RMNodeStarter at the root of the RM Home by yourself."); rmHome = ""; } } return rmHome; } } return rmHome; } /** * @param rmHome the resource manager's home */ public void setRmHome(String rmHome) { this.rmHome = rmHome; } /** * @param nodeName the node's name */ public void setNodeName(String nodeName) { this.nodeName = nodeName; } /** * @param sourceName the node source's name to which one the node will be added */ public void setSourceName(String sourceName) { this.sourceName = sourceName; } /** * @param javaPath the path to the java executable used to launch the node */ public void setJavaPath(String javaPath) { this.javaPath = javaPath; } /** * @param targetOS the operating system on which one the node will run */ public void setTargetOS(OperatingSystem targetOS) { this.targetOS = targetOS; } /** * @param rmURL the url of the resource manager to which one the node must be added */ public void setRmURL(String rmURL) { this.rmURL = rmURL; } /** * To set a String standing for the ProActive Properties, appended to the built command line without any modification. * If a call to {@link #setPaProperties(byte[])} or {@link #setPaProperties(File)} of {@link #setPaProperties(Map)} has already been made, the PAProperties structure will be cleaned up... * @param paProp A String standing for the PAProperties ( for instance -Dlog4j.configuration=... or -Dproactive.net.netmask=... ) */ public void setPaProperties(String paProp) { if (this.paPropProperties != null) { this.paPropProperties = null; } this.paPropString = paProp; } /** * To set the PAproperties of the node. If a previsous call to * {@link #setPaProperties(byte[])} or {@link #setPaProperties(File)} of {@link #setPaProperties(Map)} has already been made, * this one will overide the previous call. This file must be a valid ProActive XML configuration file. * @param paPropertiesFile the ProActive configuration file * @throws IOException if the file is not a ProActive regular file */ public void setPaProperties(File paPropertiesFile) throws IOException { this.paPropProperties = new Properties(); if (paPropertiesFile != null) { if (paPropertiesFile.exists() && paPropertiesFile.isFile()) { this.paPropProperties = ProActiveConfigurationParser.parse(paPropertiesFile .getAbsolutePath(), paPropProperties); } else { throw new IOException("The supplied file is not a regular file: " + paPropertiesFile.getAbsolutePath()); } } } /** * To set the PAproperties of the node. If a previsous call to * {@link #setPaProperties(byte[])} or {@link #setPaProperties(File)} of {@link #setPaProperties(Map)} has already been made, * this one will overide the previous call. * Every properties will be appended to the command line this way: -Dkey=value * @param paProp a map containing valid java properties */ public void setPaProperties(Map<String, String> paProp) { this.paPropProperties = new Properties(); for (String key : paProp.keySet()) { this.paPropProperties.put(key, paProp.get(key)); } } /** * To set the PAproperties of the node. If a previsous call to * {@link #setPaProperties(byte[])} or {@link #setPaProperties(File)} of {@link #setPaProperties(Map)} has already been made, * this one will overide the previous call. * @param ba the content of a valid ProActive xml configuration file. */ public void setPaProperties(byte[] ba) { this.paPropProperties = new Properties(); if (ba == null) { return; } InputStream is = null; try { is = new ByteArrayInputStream(ba); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(is); NodeList props = doc.getElementsByTagName("prop"); for (int i = 0; i < props.getLength(); i++) { Element prop = (Element) props.item(i); String key = prop.getAttribute("key"); String value = prop.getAttribute("value"); paPropProperties.put(key, value); } } catch (Exception e) { throw new IllegalArgumentException("Cannot read ProActive configuration from supplied file."); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { logger.warn(e); } } } /** * To retrieve the credentials file from a previous {@link #setCredentialsFileAndNullOthers(String)}. If no such call has already been made, will try to retrieve the credentials file path * from the PAProperties set thanks to the methods: {@link #setPaProperties(byte[])} or {@link #setPaProperties(File)} of {@link #setPaProperties(Map)} * @return The credentials file used to build the command line */ public String getCredentialsFile() { if (this.credentialsFile != null) { logger.trace("Credentials file retrieved from previously set value."); return credentialsFile; } else { if (this.credentialsEnv == null && this.credentialsValue == null) { String paRMKey = PAResourceManagerProperties.RM_CREDS.getKey(); if (paPropProperties != null && paPropProperties.getProperty(paRMKey) != null && !paPropProperties.getProperty(paRMKey).equals("")) { logger.trace(paRMKey + " property retrieved from PA properties supplied by " + RMNodeStarter.CommandLineBuilder.class.getName()); return paPropProperties.getProperty(paRMKey); } else { if (PAResourceManagerProperties.RM_CREDS.isSet()) { logger.trace(paRMKey + " property retrieved from PA Properties of parent Resource Manager"); return PAResourceManagerProperties.RM_CREDS.getValueAsString(); } } } } return credentialsFile; } /** * Sets the credentials file field to the supplied parameter and set * the other field related to credentials setup to null; * @param credentialsEnv */ public void setCredentialsFileAndNullOthers(String credentialsFile) { this.credentialsFile = credentialsFile; this.credentialsEnv = null; this.credentialsValue = null; } /** * @return the value of the credentials used to connect as a string */ public String getCredentialsValue() { return credentialsValue; } /** * Sets the credentials value field to the supplied parameter and set * the other field related to credentials setup to null; * @param credentialsEnv */ public void setCredentialsValueAndNullOthers(String credentialsValue) { this.credentialsValue = credentialsValue; this.credentialsEnv = null; this.credentialsFile = null; } /** * @return the value of the credentials used to connect as an environment variable */ public String getCredentialsEnv() { return credentialsEnv; } /** * Sets the credentials environment field to the supplied parameter and set * the other field related to credentials setup to null; * @param credentialsEnv */ public void setCredentialsEnvAndNullOthers(String credentialsEnv) { this.credentialsEnv = credentialsEnv; this.credentialsFile = null; this.credentialsValue = null; } /** * @return the ping delay used to maintain connectivity with the RM. -1 means no ping */ public long getPingDelay() { return pingDelay; } /** * @param pingDelay the ping delay used to detect rm shutdown. -1 means no ping */ public void setPingDelay(long pingDelay) { this.pingDelay = pingDelay; } /** * @return the number of attempts made to add the node to the core */ public int getAddAttempts() { return addAttempts; } /** * @param addAttempts the number of attempts made to add the node to the core */ public void setAddAttempts(int addAttempts) { this.addAttempts = addAttempts; } /** * @return the delay between two add attempts */ public int getAddAttemptsDelay() { return addAttemptsDelay; } /** * * @param addAttemptsDelay the delay between two add attempts */ public void setAddAttemptsDelay(int addAttemptsDelay) { this.addAttemptsDelay = addAttemptsDelay; } /** * @return the name of the node */ public String getNodeName() { return nodeName; } /** * @return the name of the node source to which one the node will be added */ public String getSourceName() { return sourceName; } /** * @return the path of the java executable used to launch the node */ public String getJavaPath() { return javaPath; } /** * @return the url of the resource manager to which one the node will be added */ public String getRmURL() { return rmURL; } /** * @return the operating system on which one the node will run */ public OperatingSystem getTargetOS() { return targetOS; } /** * To retrieve the PaProperties set thanks to a call to {@link #setPaProperties(byte[])} or {@link #setPaProperties(File)} of {@link #setPaProperties(Map)} * @return */ public Properties getPaProperties() { return paPropProperties; } /** * To retrieved the PAProperties set thanks to the method {@link #setPaProperties(String)}; * @return */ public String getPaPropertiesString() { return paPropString; } /** * Build the command to launch the RMNode. * The required pieces of information that need to be set in order to allow the RMNode to start properly are:<br /> * <ul><li>{@link RMNodeStarter.CommandLineBuilder#rmURL}</li><li>{@link RMNodeStarter.CommandLineBuilder#nodeName}</li> * <li>one of {@link RMNodeStarter.CommandLineBuilder#credentialsEnv}, {@link RMNodeStarter.CommandLineBuilder#credentialsFile} or {@link RMNodeStarter.CommandLineBuilder#credentialsValue}</li></ul> * @return The RMNodeStarter command line. * @throws IOException if you supplied a ProActive Configuration file that doesn't exist. */ public String buildCommandLine() throws IOException { Properties paProp = this.getPaProperties(); String rmHome = this.getRmHome(); if (rmHome != null) { if (!rmHome.endsWith(this.targetOS.fs)) { rmHome = rmHome + this.targetOS.fs; } } else { rmHome = ""; } String libRoot = rmHome + "dist" + this.targetOS.fs + "lib" + this.targetOS.fs; StringBuilder sb = new StringBuilder(); if (this.getJavaPath() != null) { sb.append(this.getJavaPath()); } else { logger.warn("java path isn't set in RMNodeStarter configuration."); sb.append("java"); } //building configuration if (paProp != null) { Set<Object> keys = paProp.keySet(); for (Object key : keys) { sb.append(" -D"); sb.append(key.toString()); sb.append("="); sb.append(paProp.get(key).toString()); } } else { if (this.getPaPropertiesString() != null) { sb.append(" "); sb.append(this.getPaPropertiesString()); sb.append(" "); } } //building classpath sb.append(" -cp "); if (this.getTargetOS().equals(OperatingSystem.CYGWIN) || this.getTargetOS().equals(OperatingSystem.WINDOWS)) { sb.append("\"");//especially on cygwin, we need to quote the cp } sb.append("."); for (String jar : this.requiredJARs) { sb.append(this.targetOS.ps); sb.append(libRoot); sb.append(jar); } if (this.getTargetOS().equals(OperatingSystem.CYGWIN) || this.getTargetOS().equals(OperatingSystem.WINDOWS)) { sb.append("\"");//especially on cygwin, we need to quote the cp } sb.append(" "); sb.append(RMNodeStarter.class.getName()); //appending options if (this.getAddAttempts() != -1) { sb.append(" -"); sb.append(OPTION_ADD_NODE_ATTEMPTS); sb.append(" "); sb.append(this.getAddAttempts()); } if (this.getAddAttemptsDelay() != -1) { sb.append(" -"); sb.append(OPTION_ADD_NODE_ATTEMPTS_DELAY); sb.append(" "); sb.append(this.getAddAttemptsDelay()); } if (this.getCredentialsEnv() != null) { sb.append(" -"); sb.append(OPTION_CREDENTIAL_ENV); sb.append(" "); sb.append(this.getCredentialsEnv()); } if (this.getCredentialsFile() != null) { sb.append(" -"); sb.append(OPTION_CREDENTIAL_FILE); sb.append(" "); sb.append(this.getCredentialsFile()); } if (this.getCredentialsValue() != null) { sb.append(" -"); sb.append(OPTION_CREDENTIAL_VAL); sb.append(" "); sb.append(this.getCredentialsValue()); } sb.append(" -"); sb.append(OPTION_NODE_NAME); sb.append(" "); sb.append(this.getNodeName()); sb.append(" -"); sb.append(OPTION_PING_DELAY); sb.append(" "); sb.append(this.getPingDelay()); if (this.getSourceName() != null) { sb.append(" -"); sb.append(OPTION_SOURCE_NAME); sb.append(" "); sb.append(this.getSourceName()); } sb.append(" -"); sb.append(OPTION_RM_URL); sb.append(" "); sb.append(this.getRmURL()); return sb.toString(); } @Override public String toString() { try { return buildCommandLine(); } catch (IOException e) { return RMNodeStarter.CommandLineBuilder.class.getName() + " with invalid configuration"; } } } /** * Private inner enum which represents supported operating systems */ public enum OperatingSystem { WINDOWS(";", "\\\\"), UNIX(":", "/"), CYGWIN(";", "/"); /** the path separator, ie. ";" on windows systems and ":" on unix systems */ public final String ps; /** the file path separator, ie. "/" on unix systems and "\" on windows systems */ public final String fs; private OperatingSystem(String ps, String fs) { this.fs = fs; this.ps = ps; } /** * Returns the operating system corresponding to the provided String parameter: 'LINUX', 'WINDOWS' or 'CYGWIN' * @param desc one of 'LINUX', 'WINDOWS' or 'CYGWIN' * @return the appropriate Operating System of null if no system is found */ public static OperatingSystem getOperatingSystem(String desc) { if (desc == null) { throw new IllegalArgumentException("String description of operating system cannot be null"); } desc = desc.toUpperCase(); if ("LINUX".equals(desc) || "UNIX".equals(desc)) { return OperatingSystem.UNIX; } if ("WINDOWS".equals(desc)) { return OperatingSystem.WINDOWS; } if ("CYGWIN".equals(desc)) { return OperatingSystem.CYGWIN; } return null; } } }
package info.justaway.adapter; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import info.justaway.BuildConfig; import info.justaway.JustawayApplication; import info.justaway.MainActivity; import info.justaway.PostActivity; import info.justaway.ProfileActivity; import info.justaway.R; import info.justaway.ScaleImageActivity; import info.justaway.model.Row; import twitter4j.DirectMessage; import twitter4j.MediaEntity; import twitter4j.Status; import twitter4j.URLEntity; import twitter4j.User; import twitter4j.UserMentionEntity; public class TwitterAdapter extends ArrayAdapter<Row> { static class ViewHolder { LinearLayout action; TextView action_icon; TextView action_by_display_name; TextView action_by_screen_name; ImageView icon; TextView display_name; TextView screen_name; TextView fontello_lock; TextView datetime_relative; TextView status; LinearLayout images; TableLayout menu_and_via; TextView do_reply; TextView do_retweet; TextView retweet_count; TextView do_fav; TextView fav_count; TextView via; TextView datetime; LinearLayout retweet; ImageView retweet_icon; TextView retweet_by; } private JustawayApplication mApplication; private Context mContext; private ArrayList<Row> mStatuses = new ArrayList<Row>(); private LayoutInflater mInflater; private int mLayout; private Boolean isMain; private static final int LIMIT = 100; private int mLimit = LIMIT; private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM'/'dd' 'HH':'mm':'ss", Locale.ENGLISH); public TwitterAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.mContext = context; this.mLayout = textViewResourceId; this.mApplication = (JustawayApplication) context.getApplicationContext(); this.isMain = mContext.getClass().getName().equals("info.justaway.MainActivity"); } public void extensionAdd(Row row) { super.add(row); this.filter(row); this.mStatuses.add(row); mLimit++; } @Override public void add(Row row) { super.add(row); this.filter(row); this.mStatuses.add(row); this.limitation(); } @Override public void insert(Row row, int index) { super.insert(row, index); this.filter(row); this.mStatuses.add(index, row); this.limitation(); } @Override public void remove(Row row) { super.remove(row); this.mStatuses.remove(row); } private void filter(Row row) { Status status = row.getStatus(); if (status != null && status.isRetweeted()) { Status retweet = status.getRetweetedStatus(); if (retweet != null && status.getUser().getId() == mApplication.getUserId()) { mApplication.setRtId(retweet.getId(), status.getId()); } } } @SuppressWarnings("unused") public void replaceStatus(Status status) { for (Row row : mStatuses) { if (!row.isDirectMessage() && row.getStatus().getId() == status.getId()) { row.setStatus(status); notifyDataSetChanged(); break; } } } public void removeStatus(long statusId) { for (Row row : mStatuses) { if (!row.isDirectMessage() && row.getStatus().getId() == statusId) { remove(row); break; } } } public void removeDirectMessage(long directMessageId) { for (Row row : mStatuses) { if (row.isDirectMessage() && row.getMessage().getId() == directMessageId) { remove(row); break; } } } public void limitation() { int size = this.mStatuses.size(); if (size > mLimit) { int count = size - mLimit; for (int i = 0; i < count; i++) { super.remove(this.mStatuses.remove(size - i - 1)); } } } @Override public void clear() { super.clear(); this.mStatuses.clear(); mLimit = LIMIT; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; View view = convertView; if (view == null) { // null view = mInflater.inflate(this.mLayout, null); if (view == null) { return null; } holder = new ViewHolder(); holder.action = (LinearLayout) view.findViewById(R.id.action); holder.action_icon = (TextView) view.findViewById(R.id.action_icon); holder.action_by_display_name = (TextView) view.findViewById(R.id.action_by_display_name); holder.action_by_screen_name = (TextView) view.findViewById(R.id.action_by_screen_name); holder.icon = (ImageView) view.findViewById(R.id.icon); holder.display_name = (TextView) view.findViewById(R.id.display_name); holder.screen_name = (TextView) view.findViewById(R.id.screen_name); holder.fontello_lock = (TextView) view.findViewById(R.id.fontello_lock); holder.datetime_relative = (TextView) view.findViewById(R.id.datetime_relative); holder.status = (TextView) view.findViewById(R.id.status); holder.status.setTag(12); holder.images = (LinearLayout) view.findViewById(R.id.images); holder.menu_and_via = (TableLayout) view.findViewById(R.id.menu_and_via); holder.do_reply = (TextView) view.findViewById(R.id.do_reply); holder.do_retweet = (TextView) view.findViewById(R.id.do_retweet); holder.retweet_count = (TextView) view.findViewById(R.id.retweet_count); holder.do_fav = (TextView) view.findViewById(R.id.do_fav); holder.fav_count = (TextView) view.findViewById(R.id.fav_count); holder.via = (TextView) view.findViewById(R.id.via); holder.datetime = (TextView) view.findViewById(R.id.datetime); holder.retweet = (LinearLayout) view.findViewById(R.id.retweet); holder.retweet_icon = (ImageView) view.findViewById(R.id.retweet_icon); holder.retweet_by = (TextView) view.findViewById(R.id.retweet_by); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } if (mApplication.getFontSize() != (Integer) holder.status.getTag()) { holder.status.setTag(mApplication.getFontSize()); holder.status.setTextSize(TypedValue.COMPLEX_UNIT_SP, mApplication.getFontSize()); holder.display_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, mApplication.getFontSize()); holder.screen_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, mApplication.getFontSize() - 2); holder.datetime_relative.setTextSize(TypedValue.COMPLEX_UNIT_SP, mApplication.getFontSize() - 2); } Row row = mStatuses.get(position); if (row.isDirectMessage()) { DirectMessage message = row.getMessage(); if (message == null) { return view; } renderMessage(holder, message); } else { Status status = row.getStatus(); if (status == null) { return view; } Status retweet = status.getRetweetedStatus(); if (row.isFavorite()) { renderStatus(holder, status, null, row.getSource()); } else if (retweet == null) { renderStatus(holder, status, null, null); } else { renderStatus(holder, retweet, status, null); } } if (isMain && position == 0) { ((MainActivity) mContext).showTopView(); } return view; } private void renderMessage(ViewHolder holder, final DirectMessage message) { Typeface fontello = JustawayApplication.getFontello(); long userId = JustawayApplication.getApplication().getUserId(); holder.do_retweet.setVisibility(View.GONE); holder.do_fav.setVisibility(View.GONE); holder.retweet_count.setVisibility(View.GONE); holder.fav_count.setVisibility(View.GONE); holder.menu_and_via.setVisibility(View.VISIBLE); if (message.getSender().getId() == userId) { holder.do_reply.setVisibility(View.GONE); } else { holder.do_reply.setVisibility(View.VISIBLE); holder.do_reply.setTypeface(fontello); holder.do_reply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String text = "D " + message.getSender().getScreenName() + " "; if (mContext.getClass().getName().equals("info.justaway.MainActivity")) { MainActivity activity = (MainActivity) mContext; View singleLineTweet = activity.findViewById(R.id.quick_tweet_layout); if (singleLineTweet != null && singleLineTweet.getVisibility() == View.VISIBLE) { EditText editStatus = (EditText) activity.findViewById(R.id.quick_tweet_edit); editStatus.setText(text); editStatus.setSelection(text.length()); editStatus.requestFocus(); mApplication.showKeyboard(editStatus); activity.setInReplyToStatusId((long) 0); return; } } Intent intent = new Intent(mContext, PostActivity.class); intent.putExtra("status", text); intent.putExtra("selection", text.length()); mContext.startActivity(intent); } }); } holder.display_name.setText(message.getSender().getName()); holder.screen_name.setText("@" + message.getSender().getScreenName()); holder.status.setText("D " + message.getRecipientScreenName() + " " + message.getText()); holder.datetime .setText(getAbsoluteTime(message.getCreatedAt())); holder.datetime_relative.setText(getRelativeTime(message.getCreatedAt())); holder.via.setVisibility(View.GONE); holder.retweet.setVisibility(View.GONE); holder.images.setVisibility(View.GONE); mApplication.displayUserIcon(message.getSender(), holder.icon); holder.icon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), ProfileActivity.class); intent.putExtra("screenName", message.getSender().getScreenName()); mContext.startActivity(intent); } }); holder.action.setVisibility(View.GONE); holder.fontello_lock.setVisibility(View.INVISIBLE); } private void renderStatus(final ViewHolder holder, final Status status, Status retweet, User favorite) { long userId = JustawayApplication.getApplication().getUserId(); Typeface fontello = JustawayApplication.getFontello(); if (status.getFavoriteCount() > 0) { holder.fav_count.setText(String.valueOf(status.getFavoriteCount())); holder.fav_count.setVisibility(View.VISIBLE); } else { holder.fav_count.setText("0"); holder.fav_count.setVisibility(View.INVISIBLE); } if (status.getRetweetCount() > 0) { holder.retweet_count.setText(String.valueOf(status.getRetweetCount())); holder.retweet_count.setVisibility(View.VISIBLE); } else { holder.retweet_count.setText("0"); holder.retweet_count.setVisibility(View.INVISIBLE); } holder.do_reply.setTypeface(fontello); holder.do_reply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UserMentionEntity[] mentions = status.getUserMentionEntities(); Intent intent = new Intent(mContext, PostActivity.class); String text; if (status.getUser().getId() == mApplication.getUserId() && mentions.length == 1) { text = "@" + mentions[0].getScreenName() + " "; } else { text = "@" + status.getUser().getScreenName() + " "; } if (mContext.getClass().getName().equals("info.justaway.MainActivity")) { MainActivity activity = (MainActivity) mContext; View singleLineTweet = activity.findViewById(R.id.quick_tweet_layout); if (singleLineTweet != null && singleLineTweet.getVisibility() == View.VISIBLE) { EditText editStatus = (EditText) activity.findViewById(R.id.quick_tweet_edit); editStatus.setText(text); editStatus.setSelection(text.length()); editStatus.requestFocus(); mApplication.showKeyboard(editStatus); activity.setInReplyToStatusId(status.getId()); return; } } intent.putExtra("status", text); intent.putExtra("selection", text.length()); intent.putExtra("inReplyToStatusId", status.getId()); mContext.startActivity(intent); } }); holder.do_retweet.setTypeface(fontello); holder.do_retweet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (status.getUser().isProtected()) { JustawayApplication.showToast(R.string.toast_protected_tweet_can_not_share); return; } Long id = mApplication.getRtId(status); if (id != null) { if (id == 0) { JustawayApplication.showToast(R.string.toast_destroy_retweet_progress); } else { DialogFragment dialog = new DialogFragment() { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.confirm_destroy_retweet); builder.setMessage(status.getText()); builder.setPositiveButton(getString(R.string.button_destroy_retweet), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { holder.do_retweet.setTextColor(Color.parseColor("#666666")); mApplication.doDestroyRetweet(status); if (isMain) { ((MainActivity) mContext).notifyDataSetChanged(); } dismiss(); } }); builder.setNegativeButton(getString(R.string.button_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }); return builder.create(); } }; FragmentActivity activity = (FragmentActivity) mContext; dialog.show(activity.getSupportFragmentManager(), "dialog"); } } else { DialogFragment dialog = new DialogFragment() { private Runnable mOnDismiss; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.confirm_retweet); builder.setMessage(status.getText()); builder.setNeutralButton(getString(R.string.button_quote), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { FragmentActivity activity = (FragmentActivity) mContext; EditText editStatus = null; View singleLineTweet = activity.findViewById(R.id.quick_tweet_layout); if (singleLineTweet != null && singleLineTweet.getVisibility() == View.VISIBLE) { editStatus = (EditText) activity.findViewById(R.id.quick_tweet_edit); } String text = " https://twitter.com/" + status.getUser().getScreenName() + "/status/" + String.valueOf(status.getId()); if (editStatus != null) { editStatus.requestFocus(); editStatus.setText(text); final View view = editStatus; mOnDismiss = new Runnable() { @Override public void run() { mApplication.showKeyboard(view); } }; return; } Intent intent = new Intent(activity, PostActivity.class); intent.putExtra("status", text); intent.putExtra("inReplyToStatusId", status.getId()); startActivity(intent); dismiss(); } }); builder.setPositiveButton(getString(R.string.button_retweet), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { holder.do_retweet.setTextColor(mContext.getResources() .getColor(R.color.holo_green_light)); mApplication.doRetweet(status.getId()); if (isMain) { ((MainActivity) mContext).notifyDataSetChanged(); } dismiss(); } }); builder.setNegativeButton(getString(R.string.button_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }); return builder.create(); } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); if (mOnDismiss != null) { mOnDismiss.run(); } } }; FragmentActivity activity = (FragmentActivity) mContext; dialog.show(activity.getSupportFragmentManager(), "dialog"); } } }); holder.do_fav.setTypeface(fontello); holder.do_fav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (holder.do_fav.getTag().equals("is_fav")) { holder.do_fav.setTag("no_fav"); holder.do_fav.setTextColor(Color.parseColor("#666666")); mApplication.doDestroyFavorite(status.getId()); } else { holder.do_fav.setTag("is_fav"); holder.do_fav.setTextColor(mContext.getResources().getColor(R.color.holo_orange_light)); mApplication.doFavorite(status.getId()); } if (isMain) { ((MainActivity) mContext).notifyDataSetChanged(); } } }); if (mApplication.getRtId(status) != null) { holder.do_retweet.setTextColor(mContext.getResources().getColor(R.color.holo_green_light)); } else { holder.do_retweet.setTextColor(Color.parseColor("#666666")); } if (mApplication.isFav(status)) { holder.do_fav.setTag("is_fav"); holder.do_fav.setTextColor(mContext.getResources().getColor(R.color.holo_orange_light)); } else { holder.do_fav.setTag("no_fav"); holder.do_fav.setTextColor(Color.parseColor("#666666")); } holder.display_name.setText(status.getUser().getName()); holder.screen_name.setText("@" + status.getUser().getScreenName()); holder.datetime_relative.setText(getRelativeTime(status.getCreatedAt())); holder.datetime.setText(getAbsoluteTime(status.getCreatedAt())); String via = mApplication.getClientName(status.getSource()); holder.via.setText("via " + via); holder.via.setVisibility(View.VISIBLE); /** * Justaway for Android */ if (BuildConfig.DEBUG) { if (via.equals("Justaway for Android")) { holder.via.setTextColor(mContext.getResources().getColor(R.color.holo_blue_light)); } else { holder.via.setTextColor(Color.parseColor("#666666")); } } holder.action_icon.setTypeface(fontello); // fav if (favorite != null) { holder.action_icon.setText(R.string.fontello_star); holder.action_icon.setTextColor(mContext.getResources().getColor(R.color.holo_orange_light)); holder.action_by_display_name.setText(favorite.getName()); holder.action_by_screen_name.setText("@" + favorite.getScreenName()); holder.retweet.setVisibility(View.GONE); holder.menu_and_via.setVisibility(View.VISIBLE); holder.action.setVisibility(View.VISIBLE); } else if (retweet != null) { if (userId == status.getUser().getId()) { holder.action_icon.setText(R.string.fontello_retweet); holder.action_icon.setTextColor(mContext.getResources().getColor(R.color.holo_green_light)); holder.action_by_display_name.setText(retweet.getUser().getName()); holder.action_by_screen_name.setText("@" + retweet.getUser().getScreenName()); holder.retweet.setVisibility(View.GONE); holder.menu_and_via.setVisibility(View.VISIBLE); holder.action.setVisibility(View.VISIBLE); } else { mApplication.displayRoundedImage(retweet.getUser().getProfileImageURL(), holder.retweet_icon); holder.retweet_by.setText("RT by " + retweet.getUser().getName() + " @" + retweet.getUser().getScreenName()); holder.action.setVisibility(View.GONE); holder.menu_and_via.setVisibility(View.VISIBLE); holder.retweet.setVisibility(View.VISIBLE); } } else { if (mApplication.isMentionForMe(status)) { holder.action_icon.setText(R.string.fontello_at); holder.action_icon.setTextColor(mContext.getResources().getColor(R.color.holo_red_light)); holder.action_by_display_name.setText(status.getUser().getName()); holder.action_by_screen_name.setText("@" + status.getUser().getScreenName()); holder.action.setVisibility(View.VISIBLE); holder.retweet.setVisibility(View.GONE); } else { holder.action.setVisibility(View.GONE); holder.retweet.setVisibility(View.GONE); } holder.menu_and_via.setVisibility(View.VISIBLE); } if (status.getUser().isProtected()) { holder.fontello_lock.setTypeface(fontello); holder.fontello_lock.setVisibility(View.VISIBLE); } else { holder.fontello_lock.setVisibility(View.INVISIBLE); } mApplication.displayUserIcon(status.getUser(), holder.icon); holder.icon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), ProfileActivity.class); intent.putExtra("screenName", status.getUser().getScreenName()); mContext.startActivity(intent); } }); MediaEntity[] medias = retweet != null ? retweet.getMediaEntities() : status .getMediaEntities(); URLEntity[] urls = retweet != null ? retweet.getURLEntities() : status.getURLEntities(); ArrayList<String> imageUrls = new ArrayList<String>(); Pattern twitpic_pattern = Pattern.compile("^http://twitpic\\.com/(\\w+)$"); Pattern twipple_pattern = Pattern.compile("^http://p\\.twipple\\.jp/(\\w+)$"); Pattern instagram_pattern = Pattern.compile("^http://instagram\\.com/p/([^/]+)/$"); Pattern images_pattern = Pattern.compile("^https?://.*\\.(png|gif|jpeg|jpg)$"); Pattern youtube_pattern = Pattern.compile("^https?://(?:www\\.youtube\\.com/watch\\?.*v=|youtu\\.be/)([\\w-]+)"); Pattern niconico_pattern = Pattern.compile("^http://(?:www\\.nicovideo\\.jp/watch|nico\\.ms)/sm(\\d+)$"); String statusString = status.getText(); for (URLEntity url : urls) { Pattern p = Pattern.compile(url.getURL()); Matcher m = p.matcher(statusString); statusString = m.replaceAll(url.getExpandedURL()); Matcher twitpic_matcher = twitpic_pattern.matcher(url.getExpandedURL()); if (twitpic_matcher.find()) { imageUrls.add("http://twitpic.com/show/full/" + twitpic_matcher.group(1)); continue; } Matcher twipple_matcher = twipple_pattern.matcher(url.getExpandedURL()); if (twipple_matcher.find()) { imageUrls.add("http://p.twpl.jp/show/orig/" + twipple_matcher.group(1)); continue; } Matcher instagram_matcher = instagram_pattern.matcher(url.getExpandedURL()); if (instagram_matcher.find()) { imageUrls.add(url.getExpandedURL() + "media?size=l"); continue; } Matcher youtube_matcher = youtube_pattern.matcher(url.getExpandedURL()); if (youtube_matcher.find()) { imageUrls.add("http://i.ytimg.com/vi/" + youtube_matcher.group(1) + "/hqdefault.jpg"); continue; } Matcher niconico_matcher = niconico_pattern.matcher(url.getExpandedURL()); if (niconico_matcher.find()) { int id = Integer.valueOf(niconico_matcher.group(1)); int host = id % 4 + 1; imageUrls.add("http://tn-skr" + host + ".smilevideo.jp/smile?i=" + id + ".L"); continue; } Matcher images_matcher = images_pattern.matcher(url.getExpandedURL()); if (images_matcher.find()) { imageUrls.add(url.getExpandedURL()); } } holder.status.setText(statusString); for (MediaEntity media : medias) { imageUrls.add(media.getMediaURL()); } holder.images.removeAllViews(); if (imageUrls.size() > 0) { for (final String url : imageUrls) { ImageView image = new ImageView(mContext); image.setScaleType(ImageView.ScaleType.CENTER_CROP); holder.images.addView(image, new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, 120)); mApplication.displayRoundedImage(url, image); image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), ScaleImageActivity.class); intent.putExtra("url", url); mContext.startActivity(intent); } }); } holder.images.setVisibility(View.VISIBLE); } else { holder.images.setVisibility(View.GONE); } } private String getRelativeTime(Date date) { int diff = (int) (((new Date()).getTime() - date.getTime()) / 1000); if (diff < 1) { return "now"; } else if (diff < 60) { return diff + "s"; } else if (diff < 3600) { return (diff / 60) + "m"; } else if (diff < 86400) { return (diff / 3600) + "h"; } else { return (diff / 86400) + "d"; } } private String getAbsoluteTime(Date date) { return DATE_FORMAT.format(date); } }
package codechicken.lib.gui; import codechicken.lib.math.MathHelper; import codechicken.lib.render.CCRenderState; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class GuiDraw { public static class GuiHook extends Gui { public void setZLevel(float f) { zLevel = f; } public float getZLevel() { return zLevel; } public void incZLevel(float f) { zLevel += f; } @Override public void drawGradientRect(int par1, int par2, int par3, int par4, int par5, int par6) { super.drawGradientRect(par1, par2, par3, par4, par5, par6); } } public static final GuiHook gui = new GuiHook(); public static FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; public static TextureManager renderEngine = Minecraft.getMinecraft().renderEngine; public static void drawRect(int x, int y, int w, int h, int colour) { drawGradientRect(x, y, w, h, colour, colour); } public static void drawGradientRect(int x, int y, int w, int h, int colour1, int colour2) { gui.drawGradientRect(x, y, x + w, y + h, colour1, colour2); } public static void drawTexturedModalRect(int x, int y, int tx, int ty, int w, int h) { gui.drawTexturedModalRect(x, y, tx, ty, w, h); } public static void drawString(String text, int x, int y, int colour, boolean shadow) { if (shadow) fontRenderer.drawStringWithShadow(text, x, y, colour); else fontRenderer.drawString(text, x, y, colour); } public static void drawString(String text, int x, int y, int colour) { drawString(text, x, y, colour, true); } public static void drawStringC(String text, int x, int y, int w, int h, int colour, boolean shadow) { drawString(text, x + (w - getStringWidth(text)) / 2, y + (h - 8) / 2, colour, shadow); } public static void drawStringC(String text, int x, int y, int w, int h, int colour) { drawStringC(text, x, y, w, h, colour, true); } public static void drawStringC(String text, int x, int y, int colour, boolean shadow) { drawString(text, x - getStringWidth(text) / 2, y, colour, shadow); } public static void drawStringC(String text, int x, int y, int colour) { drawStringC(text, x, y, colour, true); } public static void drawStringR(String text, int x, int y, int colour, boolean shadow) { drawString(text, x - getStringWidth(text), y, colour, shadow); } public static void drawStringR(String text, int x, int y, int colour) { drawStringR(text, x, y, colour, true); } public static int getStringWidth(String s) { if (s == null || s.equals("")) return 0; return fontRenderer.getStringWidth(EnumChatFormatting.getTextWithoutFormattingCodes(s)); } public static Dimension displaySize() { Minecraft mc = Minecraft.getMinecraft(); ScaledResolution res = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); return new Dimension(res.getScaledWidth(), res.getScaledHeight()); } public static Dimension displayRes() { Minecraft mc = Minecraft.getMinecraft(); return new Dimension(mc.displayWidth, mc.displayHeight); } public static Point getMousePosition() { Dimension size = displaySize(); Dimension res = displayRes(); return new Point(Mouse.getX() * size.width / res.width, size.height - Mouse.getY() * size.height / res.height - 1); } public static void changeTexture(String s) { CCRenderState.changeTexture(s); } public static void changeTexture(ResourceLocation r) { CCRenderState.changeTexture(r); } public static void drawTip(int x, int y, String text) { drawMultilineTip(x, y, Arrays.asList(text)); } /** * Append a string in the tooltip list with TOOLTIP_LINESPACE to have a small gap between it and the next line */ public static final String TOOLTIP_LINESPACE = "\u00A7h"; /** * Have a string in the tooltip list with TOOLTIP_HANDLER + getTipLineId(handler) for a custom handler */ public static final String TOOLTIP_HANDLER = "\u00A7x"; private static List<ITooltipLineHandler> tipLineHandlers = new ArrayList<ITooltipLineHandler>(); public static interface ITooltipLineHandler { public Dimension getSize(); public void draw(int x, int y); } public static int getTipLineId(ITooltipLineHandler handler) { tipLineHandlers.add(handler); return tipLineHandlers.size()-1; } public static ITooltipLineHandler getTipLine(String line) { if(!line.startsWith(TOOLTIP_HANDLER)) return null; return tipLineHandlers.get(Integer.parseInt(line.substring(2))); } public static void drawMultilineTip(int x, int y, List<String> list) { if (list.isEmpty()) return; GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glDisable(GL11.GL_DEPTH_TEST); RenderHelper.disableStandardItemLighting(); int w = 0; int h = -2; for (int i = 0; i < list.size(); i++) { String s = list.get(i); ITooltipLineHandler line = getTipLine(s); Dimension d = line != null ? line.getSize() : new Dimension(getStringWidth(s), list.get(i).endsWith(TOOLTIP_LINESPACE) && i + 1 < list.size() ? 12 : 10); w = Math.max(w, d.width); h += d.height; } if (x < 8) x = 8; else if (x > displaySize().width - w - 8) { x -= 24 + w;//flip side of cursor if(x < 8) x = 8; } y = (int) MathHelper.clip(y, 8, displaySize().height - 8 - h); gui.incZLevel(300); drawTooltipBox(x - 4, y - 4, w + 7, h + 7); for (String s : list) { ITooltipLineHandler line = getTipLine(s); if(line != null) { line.draw(x, y); y += line.getSize().height; } else { fontRenderer.drawStringWithShadow(s, x, y, -1); y += s.endsWith(TOOLTIP_LINESPACE) ? 12 : 10; } } tipLineHandlers.clear(); gui.incZLevel(-300); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glEnable(GL12.GL_RESCALE_NORMAL); RenderHelper.enableGUIStandardItemLighting(); } public static void drawTooltipBox(int x, int y, int w, int h) { int bg = 0xf0100010; drawGradientRect(x + 1, y, w - 1, 1, bg, bg); drawGradientRect(x + 1, y + h, w - 1, 1, bg, bg); drawGradientRect(x + 1, y + 1, w - 1, h - 1, bg, bg);//center drawGradientRect(x, y + 1, 1, h - 1, bg, bg); drawGradientRect(x + w, y + 1, 1, h - 1, bg, bg); int grad1 = 0x505000ff; int grad2 = 0x5028007F; drawGradientRect(x + 1, y + 2, 1, h - 3, grad1, grad2); drawGradientRect(x + w - 1, y + 2, 1, h - 3, grad1, grad2); drawGradientRect(x + 1, y + 1, w - 1, 1, grad1, grad1); drawGradientRect(x + 1, y + h - 1, w - 1, 1, grad2, grad2); } }
package com.github.cstroe.svndumpgui.internal.utility; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class FastCharStreamTest { private FastCharStream charStream; @Test public void parse_tokens() throws IOException { final InputStream inputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("FastCharStreamTokens.txt"); charStream = new FastCharStream(new InputStreamReader(inputStream)); int number; READ(); COLON(); SPACE(); number = NUMBER(); NEWLINE(); assertThat(number, is(16)); assertThat(readData(number), is(equalTo("abcdefghijklmnop"))); NEWLINE(); READ(); COLON(); SPACE(); number = NUMBER(); NEWLINE(); assertThat(number, is(3)); assertThat(readData(number), is(equalTo("abc"))); NEWLINE(); READ(); COLON(); SPACE(); number = NUMBER(); NEWLINE(); assertThat(number, is(5)); assertThat(readData(number), is(equalTo("abcde"))); assertThat(charStream.buffer.length, is(FastCharStream.INITAL_BUFFER_LENGTH)); } private void READ() throws IOException { charStream.BeginToken(); charStream.readChar(); charStream.readChar(); charStream.readChar(); assertThat(charStream.GetImage(), is(equalTo("READ"))); } private void COLON() throws IOException { charStream.BeginToken(); assertThat(charStream.GetImage(), is(equalTo(":"))); } private void SPACE() throws IOException { charStream.BeginToken(); assertThat(charStream.GetImage(), is(equalTo(" "))); } private int NUMBER() throws IOException { boolean tokenBegun = false; while(true) { char currentChar; if(tokenBegun) { currentChar = charStream.readChar(); } else { currentChar = charStream.BeginToken(); tokenBegun = true; } if(currentChar < '0' || currentChar > '9') { break; } } charStream.backup(1); return Integer.parseInt(charStream.GetImage()); } private void NEWLINE() throws IOException { charStream.BeginToken(); assertThat(charStream.GetImage(), is(equalTo("\n"))); } private String readData(int length) throws IOException { charStream.BeginToken(); for(int i = 0; i < length - 1; i++) { charStream.readChar(); } return charStream.GetImage(); } @Test public void parse_tokens_and_small_data() throws IOException { final InputStream inputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("FastCharStreamTokens.txt"); charStream = new FastCharStream(new InputStreamReader(inputStream)); int number; READ(); COLON(); SPACE(); number = NUMBER(); NEWLINE(); assertThat(number, is(16)); assertThat(new String(charStream.readChars(number)), is(equalTo("abcdefghijklmnop"))); NEWLINE(); READ(); COLON(); SPACE(); number = NUMBER(); NEWLINE(); assertThat(number, is(3)); assertThat(new String(charStream.readChars(number)), is(equalTo("abc"))); NEWLINE(); READ(); COLON(); SPACE(); number = NUMBER(); NEWLINE(); assertThat(number, is(5)); assertThat(new String(charStream.readChars(number)), is(equalTo("abcde"))); assertThat(charStream.buffer.length, is(FastCharStream.INITAL_BUFFER_LENGTH)); } @Test public void parse_tokens_and_big_data() throws IOException, NoSuchAlgorithmException { StringBuilder builder = new StringBuilder(); byte[] md5sum_8192; { builder.append("READ: 8192\n"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < 8192; i++) { char nextChar = (char)('a' + i % 8); md5.update((byte) nextChar); builder.append(nextChar); } builder.append("\n"); md5sum_8192 = md5.digest(); } byte[] md5sum_10000; { builder.append("READ: 10000\n"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < 10000; i++) { char nextChar = (char)('a' + i % 8); md5.update((byte)nextChar); builder.append(nextChar); } builder.append("\n"); md5sum_10000 = md5.digest(); } builder.append("READ: 4\n"); for(int i = 0; i < 4; i++) { char nextChar = (char)('a' + i % 8); builder.append(nextChar); } builder.append("\n"); charStream = new FastCharStream(new StringReader(builder.toString())); int number; { READ(); COLON(); SPACE(); number = NUMBER(); NEWLINE(); assertThat(number, is(8192)); char[] firstBuffer = charStream.readChars(number); assertThat(firstBuffer.length, is(8192)); MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] md5sum_firstBuffer = md5.digest(convert(firstBuffer)); assertTrue(Arrays.equals(md5sum_8192, md5sum_firstBuffer)); } { NEWLINE(); READ(); COLON(); SPACE(); number = NUMBER(); NEWLINE(); assertThat(number, is(10000)); char[] secondBuffer = charStream.readChars(number); assertThat(secondBuffer.length, is(10000)); MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] md5sum_secondbuffer = md5.digest(convert(secondBuffer)); assertTrue(Arrays.equals(md5sum_10000, md5sum_secondbuffer)); NEWLINE(); } READ(); COLON(); SPACE(); number = NUMBER(); NEWLINE(); assertThat(number, is(4)); assertThat(new String(charStream.readChars(number)), is(equalTo("abcd"))); assertThat(charStream.buffer.length, is(FastCharStream.INITAL_BUFFER_LENGTH)); } private byte[] convert(char[] array) { return new String(array).getBytes(StandardCharsets.US_ASCII); } @Test public void parse_tokens_and_two_consecutive_read_chars() throws IOException { StringBuilder builder = new StringBuilder(); char[] firstHalf = new char[8192/2]; char[] secondHalf = new char[8192/2]; { builder.append("READ: 8192\n"); for (int i = 0; i < 8192; i++) { char nextChar = (char)('a' + i % 8); if( i < 8192/2) { firstHalf[i] = nextChar; } else { secondHalf[i - (8192/2)] = nextChar; } builder.append(nextChar); } builder.append("\n"); } charStream = new FastCharStream(new StringReader(builder.toString())); int number; READ(); COLON(); SPACE(); number = NUMBER(); NEWLINE(); assertThat(number, is(8192)); char[] readChars = charStream.readChars(8192/2); assertTrue(Arrays.equals(firstHalf, readChars)); readChars = charStream.readChars(8192/2); assertTrue(Arrays.equals(secondHalf, readChars)); NEWLINE(); } }
package info.tregmine.listeners; import java.util.List; import java.util.regex.Pattern; import org.bukkit.ChatColor; import org.bukkit.event.*; import info.tregmine.*; import info.tregmine.api.Rank; import info.tregmine.api.TregminePlayer; import info.tregmine.database.*; import info.tregmine.events.TregmineChatEvent; public class ChatListener implements Listener { private Tregmine plugin; public ChatListener(Tregmine instance) { this.plugin = instance; } @EventHandler public void onTregmineChat(TregmineChatEvent event) { TregminePlayer sender = event.getPlayer(); String channel = sender.getChatChannel(); try (IContext ctx = plugin.createContext()) { IPlayerDAO playerDAO = ctx.getPlayerDAO(); for (TregminePlayer to : plugin.getOnlinePlayers()) { if (to.getChatState() == TregminePlayer.ChatState.SETUP) { continue; } if (!sender.getRank().canNotBeIgnored()) { if (playerDAO.doesIgnore(to, sender)) { continue; } } ChatColor txtColor = ChatColor.WHITE; if (sender.getRank() == Rank.JUNIOR_ADMIN || sender.getRank() == Rank.SENIOR_ADMIN){ txtColor = ChatColor.LIGHT_PURPLE; }else if(sender.getRank() != Rank.JUNIOR_ADMIN && sender.getRank() != Rank.SENIOR_ADMIN){ if (sender.equals(to)) { txtColor = ChatColor.GRAY; }} String text = event.getMessage(); for (TregminePlayer online : plugin.getOnlinePlayers()) { if (text.contains(online.getRealName()) && !online.hasFlag(TregminePlayer.Flags.INVISIBLE)) { text = text.replaceAll(online.getRealName(), online.getChatName() + txtColor); } } List<String> player_keywords = playerDAO.getKeywords(to); if (player_keywords.size() > 0 && player_keywords != null) { for (String keyword : player_keywords) { if (text.toLowerCase().contains(keyword.toLowerCase())) { text = text.replaceAll(Pattern.quote(keyword), ChatColor.AQUA + keyword + txtColor); } } } String senderChan = sender.getChatChannel(); String toChan = to.getChatChannel(); if (senderChan.equalsIgnoreCase(toChan) || to.hasFlag(TregminePlayer.Flags.CHANNEL_VIEW)) { if (event.isWebChat()) { if ("GLOBAL".equalsIgnoreCase(senderChan)) { to.sendMessage("(" + sender.getChatName() + ChatColor.WHITE + ") " + txtColor + text); } else { to.sendMessage(channel + " (" + sender.getChatName() + ChatColor.WHITE + ") " + txtColor + text); } } else { if ("GLOBAL".equalsIgnoreCase(senderChan)) { to.sendMessage("<" + sender.getChatName() + ChatColor.WHITE + "> " + txtColor + text); } else { to.sendMessage(channel + " <" + sender.getChatName() + ChatColor.WHITE + "> " + txtColor + text); } } } if (text.contains(to.getRealName()) && "GLOBAL".equalsIgnoreCase(senderChan) && !"GLOBAL".equalsIgnoreCase(toChan)) { to.sendMessage(ChatColor.BLUE + "You were mentioned in GLOBAL by " + sender.getNameColor() + sender.getChatName()); } } } catch (DAOException e) { throw new RuntimeException(e); } if (event.isWebChat()) { Tregmine.LOGGER.info(channel + " (" + sender.getRealName() + ") " + event.getMessage()); } else { Tregmine.LOGGER.info(channel + " <" + sender.getRealName() + "> " + event.getMessage()); } try (IContext ctx = plugin.createContext()) { //ILogDAO logDAO = ctx.getLogDAO(); //logDAO.insertChatMessage(sender, channel, event.getMessage()); } catch (DAOException e) { throw new RuntimeException(e); } event.setCancelled(true); WebServer server = plugin.getWebServer(); server.executeChatAction(new WebServer.ChatMessage(sender, channel, event.getMessage())); } }
package com.lithium.dbi.rdbi.recipes.scheduler; import com.lithium.dbi.rdbi.RDBI; import org.joda.time.Instant; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import redis.clients.jedis.JedisPool; import java.util.List; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; @Test(groups = "integration") public class ExclusiveJobSchedulerTest { private ExclusiveJobScheduler scheduledJobSystem = null; private static final String TEST_TUBE = "mytube"; @BeforeMethod public void setupTest(){ scheduledJobSystem = new ExclusiveJobScheduler(new RDBI(new JedisPool("localhost")), "myprefix:"); scheduledJobSystem.nukeForTest(TEST_TUBE); } @Test public void testBasicSchedule() throws InterruptedException { scheduledJobSystem.schedule(TEST_TUBE, "{hello:world}", 0); JobInfo result2 = scheduledJobSystem.reserveSingle(TEST_TUBE, 1000); assertEquals(result2.getJobStr(), "{hello:world}"); JobInfo result3 = scheduledJobSystem.reserveSingle(TEST_TUBE, 1000); assertNull(result3); } @Test public void testCull() throws InterruptedException { scheduledJobSystem.schedule(TEST_TUBE, "{hello:world}", 0); JobInfo result3 = scheduledJobSystem.reserveSingle(TEST_TUBE, 1000); assertNotNull(result3); Thread.sleep(2000); List<JobInfo> infos = scheduledJobSystem.removeExpiredJobs(TEST_TUBE); assertEquals(infos.size(), 1); assertNotNull(infos.get(0).getTime()); } @Test public void testDelete() throws InterruptedException { scheduledJobSystem.schedule(TEST_TUBE, "{hello:world}", 0); JobInfo result2 = scheduledJobSystem.reserveSingle(TEST_TUBE, 1000); assertEquals(result2.getJobStr(), "{hello:world}"); //while in the running queue scheduledJobSystem.deleteJob(TEST_TUBE, result2.getJobStr()); JobInfo result3 = scheduledJobSystem.reserveSingle(TEST_TUBE, 1000); assertNull(result3); scheduledJobSystem.schedule(TEST_TUBE, "{hello:world}", 1000); //while in ready queue scheduledJobSystem.deleteJob(TEST_TUBE, "{hello:world}"); Thread.sleep(2000L); JobInfo result4 = scheduledJobSystem.reserveSingle(TEST_TUBE, 1000); assertNull(result4); } @Test public void testBasicStates() throws InterruptedException { scheduledJobSystem.schedule(TEST_TUBE, "{hello:world}", 1000); List<JobInfo> jobInfos = scheduledJobSystem.peakDelayed(TEST_TUBE, 0, 1 ); assertEquals(jobInfos.get(0).getJobStr(), "{hello:world}"); Thread.sleep(1500); List<JobInfo> jobInfos2 = scheduledJobSystem.peakDelayed(TEST_TUBE, 0, 1); assertEquals(jobInfos2.size(), 0); List<JobInfo> jobInfos3 = scheduledJobSystem.peakReady(TEST_TUBE, 0, 1); assertEquals(jobInfos3.get(0).getJobStr(), "{hello:world}"); scheduledJobSystem.reserveSingle("mytube", 1000L); List<JobInfo> jobInfos4 = scheduledJobSystem.peakRunning(TEST_TUBE, 0, 1); assertEquals(jobInfos4.get(0).getJobStr(), "{hello:world}"); Thread.sleep(1500); List<JobInfo> jobInfos6 = scheduledJobSystem.peakRunning(TEST_TUBE, 0, 1); assertEquals(jobInfos6.size(), 0); List<JobInfo> jobInfos5 = scheduledJobSystem.peakExpired(TEST_TUBE, 0, 1); assertEquals(jobInfos5.get(0).getJobStr(), "{hello:world}"); scheduledJobSystem.deleteJob(TEST_TUBE, "{hello:world}"); assertEquals(scheduledJobSystem.peakDelayed(TEST_TUBE, 1, 0).size(), 0); assertEquals(scheduledJobSystem.peakReady(TEST_TUBE, 1, 0).size(), 0); assertEquals(scheduledJobSystem.peakRunning(TEST_TUBE, 1, 0).size(), 0); assertEquals(scheduledJobSystem.peakExpired(TEST_TUBE, 1, 0).size(), 0); } @Test public void testBasicPerformance() throws InterruptedException { Instant before = new Instant(); for ( int i = 0; i < 10000; i++) { scheduledJobSystem.schedule(TEST_TUBE, "{hello:world} " + i, 0); } Instant after = new Instant(); System.out.println("final " + after.minus(before.getMillis()).getMillis()); Thread.sleep(2000); Instant before2 = new Instant(); for ( int i = 0; i < 10000; i++) { scheduledJobSystem.reserveSingle(TEST_TUBE, 1); } Instant after2 = new Instant(); System.out.println("final " + after2.minus(before2.getMillis()).getMillis()); } }
package io.empowerhack.hub.definitions.helpers; import cucumber.api.java.en.Given; import io.empowerhack.hub.HubApplicationTests; import io.empowerhack.hub.domain.User; import io.empowerhack.hub.repository.UserRepository; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.springframework.beans.factory.annotation.Autowired; public class AuthenticationDefinitions extends HubApplicationTests { @Autowired private UserRepository userRepository; @Given("^I am logged in$") public void I_am_logged_in() { driver.get(withBaseUrl("/login")); driver.findElement(By.name("submit")).click(); String logout = driver.findElement(By.id("logout")).getAttribute("value"); Assert.assertEquals("Logout", logout); } @Given("^I am not logged in$") public void I_am_not_logged_in() { driver.get(withBaseUrl("/")); try { driver.findElement(By.id("logout")).submit(); } catch (NoSuchElementException e) { } } @Given("^I have not logged in before") public void I_have_not_logged_in_before() { User user = userRepository.findByUid(getUser().getUid()); if (user != null) { userRepository.delete(user); } } }
package com.amplitude.api; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.location.Location; import android.location.LocationManager; import android.os.Build; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.util.Pair; public class Amplitude { public static final String TAG = "com.amplitude.api.Amplitude"; private static Context context; private static String apiKey; private static String userId; private static String deviceId; private static boolean newDeviceIdPerInstall = false; private static int versionCode; private static String versionName; private static int buildVersionSdk; private static String buildVersionRelease; private static String phoneBrand; private static String phoneManufacturer; private static String phoneModel; private static String phoneCarrier; private static String country; private static String language; private static JSONObject userProperties; private static long sessionId = -1; private static boolean sessionOpen = false; private static long sessionTimeoutMillis = Constants.SESSION_TIMEOUT_MILLIS; private static Runnable endSessionRunnable; private static AtomicBoolean updateScheduled = new AtomicBoolean(false); private static AtomicBoolean uploadingCurrently = new AtomicBoolean(false); public static final String START_SESSION_EVENT = "session_start"; public static final String END_SESSION_EVENT = "session_end"; public static final String REVENUE_EVENT = "revenue_amount"; static WorkerThread logThread = new WorkerThread("logThread"); static WorkerThread httpThread = new WorkerThread("httpThread"); static { logThread.start(); httpThread.start(); } private Amplitude() {} public static void initialize(Context context, String apiKey) { initialize(context, apiKey, null); } public static void initialize(Context context, String apiKey, String userId) { if (context == null) { Log.e(TAG, "Argument context cannot be null in initialize()"); return; } if (TextUtils.isEmpty(apiKey)) { Log.e(TAG, "Argument apiKey cannot be null or blank in initialize()"); return; } Amplitude.context = context.getApplicationContext(); Amplitude.apiKey = apiKey; SharedPreferences preferences = context.getSharedPreferences(getSharedPreferencesName(), Context.MODE_PRIVATE); if (userId != null) { Amplitude.userId = userId; preferences.edit().putString(Constants.PREFKEY_USER_ID, userId).commit(); } else { Amplitude.userId = preferences.getString(Constants.PREFKEY_USER_ID, null); } Amplitude.deviceId = getDeviceId(); PackageInfo packageInfo; try { packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); versionCode = packageInfo.versionCode; versionName = packageInfo.versionName; } catch (NameNotFoundException e) { } buildVersionSdk = Build.VERSION.SDK_INT; buildVersionRelease = Build.VERSION.RELEASE; phoneBrand = Build.BRAND; phoneManufacturer = Build.MANUFACTURER; phoneModel = Build.MODEL; TelephonyManager manager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); phoneCarrier = manager.getNetworkOperatorName(); country = Locale.getDefault().getCountry(); language = Locale.getDefault().getLanguage(); } public static void enableNewDeviceIdPerInstall(boolean newDeviceIdPerInstall) { Amplitude.newDeviceIdPerInstall = newDeviceIdPerInstall; } public static void setSessionTimeoutMillis(long sessionTimeoutMillis) { Amplitude.sessionTimeoutMillis = sessionTimeoutMillis; } public static void logEvent(String eventType) { logEvent(eventType, null); } public static void logEvent(String eventType, JSONObject eventProperties) { checkedLogEvent(eventType, eventProperties, null, System.currentTimeMillis(), true); } private static void checkedLogEvent(final String eventType, final JSONObject eventProperties, final JSONObject apiProperties, final long timestamp, final boolean checkSession) { if (TextUtils.isEmpty(eventType)) { Log.e(TAG, "Argument eventType cannot be null or blank in logEvent()"); return; } if (!contextAndApiKeySet("logEvent()")) { return; } runOnLogThread(new Runnable() { @Override public void run() { logEvent(eventType, eventProperties, apiProperties, timestamp, checkSession); } }); } private static long logEvent(String eventType, JSONObject eventProperties, JSONObject apiProperties, long timestamp, boolean checkSession) { if (checkSession) { startNewSessionIfNeeded(timestamp); } setLastEventTime(timestamp); JSONObject event = new JSONObject(); try { event.put("event_type", replaceWithJSONNull(eventType)); event.put("custom_properties", (eventProperties == null) ? new JSONObject() : eventProperties); event.put("api_properties", (apiProperties == null) ? new JSONObject() : apiProperties); event.put("global_properties", (userProperties == null) ? new JSONObject() : userProperties); addBoilerplate(event, timestamp); } catch (JSONException e) { Log.e(TAG, e.toString()); } return logEvent(event); } private static long logEvent(JSONObject event) { DatabaseHelper dbHelper = DatabaseHelper.getDatabaseHelper(context); long eventId = dbHelper.addEvent(event.toString()); if (dbHelper.getEventCount() >= Constants.EVENT_MAX_COUNT) { dbHelper.removeEvents(dbHelper.getNthEventId(Constants.EVENT_REMOVE_BATCH_SIZE)); } if (dbHelper.getEventCount() >= Constants.EVENT_UPLOAD_THRESHOLD) { updateServer(); } else { updateServerLater(Constants.EVENT_UPLOAD_PERIOD_MILLIS); } return eventId; } private static void runOnLogThread(Runnable r) { if (Thread.currentThread() != logThread) { logThread.post(r); } else { r.run(); } } private static void addBoilerplate(JSONObject event, long timestamp) throws JSONException { event.put("timestamp", timestamp); event.put("user_id", (userId == null) ? replaceWithJSONNull(deviceId) : replaceWithJSONNull(userId)); event.put("device_id", replaceWithJSONNull(deviceId)); event.put("session_id", sessionId); event.put("version_code", versionCode); event.put("version_name", replaceWithJSONNull(versionName)); event.put("build_version_sdk", buildVersionSdk); event.put("build_version_release", replaceWithJSONNull(buildVersionRelease)); event.put("phone_brand", replaceWithJSONNull(phoneBrand)); event.put("phone_manufacturer", replaceWithJSONNull(phoneManufacturer)); event.put("phone_model", replaceWithJSONNull(phoneModel)); event.put("phone_carrier", replaceWithJSONNull(phoneCarrier)); event.put("country", replaceWithJSONNull(country)); event.put("language", replaceWithJSONNull(language)); event.put("client", "android"); JSONObject apiProperties = event.getJSONObject("api_properties"); Location location = getMostRecentLocation(); if (location != null) { JSONObject JSONLocation = new JSONObject(); JSONLocation.put("lat", location.getLatitude()); JSONLocation.put("lng", location.getLongitude()); apiProperties.put("location", JSONLocation); } } public static void uploadEvents() { if (!contextAndApiKeySet("uploadEvents()")) { return; } logThread.post(new Runnable() { public void run() { updateServer(); } }); } private static void updateServerLater(long delayMillis) { if (!updateScheduled.getAndSet(true)) { logThread.postDelayed(new Runnable() { public void run() { updateScheduled.set(false); updateServer(); } }, delayMillis); } } private static long getLastEventTime() { SharedPreferences preferences = context.getSharedPreferences(getSharedPreferencesName(), Context.MODE_PRIVATE); return preferences.getLong(Constants.PREFKEY_PREVIOUS_SESSION_TIME, -1); } private static void setLastEventTime(long timestamp) { SharedPreferences preferences = context.getSharedPreferences(getSharedPreferencesName(), Context.MODE_PRIVATE); preferences.edit().putLong(Constants.PREFKEY_PREVIOUS_SESSION_TIME, timestamp).commit(); } private static void clearEndSession() { SharedPreferences preferences = context.getSharedPreferences(getSharedPreferencesName(), Context.MODE_PRIVATE); preferences.edit().remove(Constants.PREFKEY_PREVIOUS_END_SESSION_TIME) .remove(Constants.PREFKEY_PREVIOUS_END_SESSION_ID).commit(); } private static long getEndSessionTime() { SharedPreferences preferences = context.getSharedPreferences(getSharedPreferencesName(), Context.MODE_PRIVATE); return preferences.getLong(Constants.PREFKEY_PREVIOUS_END_SESSION_TIME, -1); } private static long getEndSessionId() { SharedPreferences preferences = context.getSharedPreferences(getSharedPreferencesName(), Context.MODE_PRIVATE); return preferences.getLong(Constants.PREFKEY_PREVIOUS_END_SESSION_ID, -1); } private static void openSession() { clearEndSession(); sessionOpen = true; } private static void closeSession() { // Close the session. Events within the next MIN_TIME_BETWEEN_SESSIONS_MILLIS seconds // will stay in the session. // A startSession call within the next MIN_TIME_BETWEEN_SESSIONS_MILLIS seconds // will reopen the session. sessionOpen = false; } private static void startNewSession(long timestamp) { // Log session start in events openSession(); sessionId = timestamp; SharedPreferences preferences = context.getSharedPreferences(getSharedPreferencesName(), Context.MODE_PRIVATE); preferences.edit().putLong(Constants.PREFKEY_PREVIOUS_SESSION_ID, sessionId).commit(); JSONObject apiProperties = new JSONObject(); try { apiProperties.put("special", START_SESSION_EVENT); } catch (JSONException e) { } logEvent(START_SESSION_EVENT, null, apiProperties, timestamp, false); } private static void startNewSessionIfNeeded(long timestamp) { if (!sessionOpen) { long lastEndSessionTime = getEndSessionTime(); if (timestamp - lastEndSessionTime < Constants.MIN_TIME_BETWEEN_SESSIONS_MILLIS) { // Sessions close enough, set sessionId to previous sessionId SharedPreferences preferences = context.getSharedPreferences( getSharedPreferencesName(), Context.MODE_PRIVATE); long previousSessionId = preferences.getLong(Constants.PREFKEY_PREVIOUS_SESSION_ID, timestamp); if (previousSessionId == -1) { // Invalid session Id, create new sessionId startNewSession(timestamp); } else { sessionId = previousSessionId; } } else { // Sessions not close enough, create new sessionId startNewSession(timestamp); } } else { long lastEventTime = getLastEventTime(); if (timestamp - lastEventTime > sessionTimeoutMillis || sessionId == -1) { startNewSession(timestamp); } } } public static void startSession() { if (!contextAndApiKeySet("startSession()")) { return; } final long now = System.currentTimeMillis(); runOnLogThread(new Runnable() { @Override public void run() { logThread.removeCallbacks(endSessionRunnable); long previousEndSessionId = getEndSessionId(); if (previousEndSessionId != -1) { DatabaseHelper dbHelper = DatabaseHelper.getDatabaseHelper(context); dbHelper.removeEvent(previousEndSessionId); } startNewSessionIfNeeded(now); openSession(); // Update last event time setLastEventTime(now); uploadEvents(); } }); } public static void endSession() { if (!contextAndApiKeySet("endSession()")) { return; } final long timestamp = System.currentTimeMillis(); runOnLogThread(new Runnable() { @Override public void run() { JSONObject apiProperties = new JSONObject(); try { apiProperties.put("special", END_SESSION_EVENT); } catch (JSONException e) { } long eventId = logEvent(END_SESSION_EVENT, null, apiProperties, timestamp, false); SharedPreferences preferences = context.getSharedPreferences( getSharedPreferencesName(), Context.MODE_PRIVATE); preferences.edit().putLong(Constants.PREFKEY_PREVIOUS_END_SESSION_ID, eventId) .putLong(Constants.PREFKEY_PREVIOUS_END_SESSION_TIME, timestamp).commit(); closeSession(); } }); // Queue up upload events 16 seconds later logThread.removeCallbacks(endSessionRunnable); endSessionRunnable = new Runnable() { @Override public void run() { clearEndSession(); uploadEvents(); } }; logThread.postDelayed(endSessionRunnable, Constants.MIN_TIME_BETWEEN_SESSIONS_MILLIS + 1000); } public static void logRevenue(double amount) { // Amount is in dollars // ex. $3.99 would be pass as logRevenue(3.99) if (!contextAndApiKeySet("logRevenue()")) { return; } // Log revenue in events JSONObject apiProperties = new JSONObject(); try { apiProperties.put("special", REVENUE_EVENT); apiProperties.put("revenue", amount); } catch (JSONException e) { } checkedLogEvent(REVENUE_EVENT, null, apiProperties, System.currentTimeMillis(), true); } public static void setUserProperties(JSONObject userProperties) { Amplitude.userProperties = userProperties; } public static void setUserId(String userId) { if (!contextAndApiKeySet("setUserId()")) { return; } Amplitude.userId = userId; SharedPreferences preferences = context.getSharedPreferences(getSharedPreferencesName(), Context.MODE_PRIVATE); preferences.edit().putString(Constants.PREFKEY_USER_ID, userId).commit(); } private static void updateServer() { updateServer(true); } // Always call this from logThread private static void updateServer(boolean limit) { if (!uploadingCurrently.getAndSet(true)) { DatabaseHelper dbHelper = DatabaseHelper.getDatabaseHelper(context); try { long endSessionId = getEndSessionId(); Pair<Long, JSONArray> pair = dbHelper.getEvents(endSessionId, limit ? Constants.EVENT_UPLOAD_MAX_BATCH_SIZE : -1); final long maxId = pair.first; final JSONArray events = pair.second; httpThread.post(new Runnable() { public void run() { makeEventUploadPostRequest(Constants.EVENT_LOG_URL, events.toString(), maxId); } }); } catch (JSONException e) { uploadingCurrently.set(false); Log.e(TAG, e.toString()); } } } private static void makeEventUploadPostRequest(String url, String events, final long maxId) { HttpPost postRequest = new HttpPost(url); List<NameValuePair> postParams = new ArrayList<NameValuePair>(); String apiVersionString = "" + Constants.API_VERSION; String timestampString = "" + System.currentTimeMillis(); String checksumString = ""; try { String preimage = apiVersionString + apiKey + events + timestampString; checksumString = bytesToHexString(MessageDigest.getInstance("MD5").digest( preimage.getBytes("UTF-8"))); } catch (NoSuchAlgorithmException e) { // According to // this will never be thrown Log.e(TAG, e.toString()); } catch (UnsupportedEncodingException e) { // According to // this will never be thrown Log.e(TAG, e.toString()); } postParams.add(new BasicNameValuePair("v", apiVersionString)); postParams.add(new BasicNameValuePair("client", apiKey)); postParams.add(new BasicNameValuePair("e", events)); postParams.add(new BasicNameValuePair("upload_time", timestampString)); postParams.add(new BasicNameValuePair("checksum", checksumString)); try { postRequest.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { // According to // this will never be thrown Log.e(TAG, e.toString()); } boolean uploadSuccess = false; HttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(postRequest); String stringResponse = EntityUtils.toString(response.getEntity()); if (stringResponse.equals("success")) { uploadSuccess = true; logThread.post(new Runnable() { public void run() { DatabaseHelper dbHelper = DatabaseHelper.getDatabaseHelper(context); dbHelper.removeEvents(maxId); uploadingCurrently.set(false); if (dbHelper.getEventCount() > Constants.EVENT_UPLOAD_THRESHOLD) { logThread.post(new Runnable() { public void run() { updateServer(false); } }); } } }); } else if (stringResponse.equals("invalid_api_key")) { Log.e(TAG, "Invalid API key, make sure your API key is correct in initialize()"); } else if (stringResponse.equals("bad_checksum")) { Log.w(TAG, "Bad checksum, post request was mangled in transit, will attempt to reupload later"); } else if (stringResponse.equals("request_db_write_failed")) { Log.w(TAG, "Couldn't write to request database on server, will attempt to reupload later"); } else { Log.w(TAG, "Upload failed, " + stringResponse + ", will attempt to reupload later"); } } catch (org.apache.http.conn.HttpHostConnectException e) { // Log.w(TAG, // "No internet connection found, unable to upload events"); } catch (java.net.UnknownHostException e) { // Log.w(TAG, // "No internet connection found, unable to upload events"); } catch (ClientProtocolException e) { Log.e(TAG, e.toString()); } catch (IOException e) { Log.e(TAG, e.toString()); } catch (AssertionError e) { // This can be caused by a NoSuchAlgorithmException thrown by DefaultHttpClient Log.e(TAG, "Exception:", e); } catch (Exception e) { // Just log any other exception so things don't crash on upload Log.e(TAG, "Exception:", e); } finally { if (client.getConnectionManager() != null) { client.getConnectionManager().shutdown(); } } if (!uploadSuccess) { uploadingCurrently.set(false); } } // Returns a unique identifier for tracking within the analytics system public static String getDeviceId() { Set<String> invalidIds = new HashSet<String>(); invalidIds.add(""); invalidIds.add("9774d56d682e549c"); invalidIds.add("unknown"); invalidIds.add("000000000000000"); // Common Serial Number invalidIds.add("Android"); invalidIds.add("DEFACE"); SharedPreferences preferences = context.getSharedPreferences(getSharedPreferencesName(), Context.MODE_PRIVATE); String deviceId = preferences.getString(Constants.PREFKEY_DEVICE_ID, null); if (!(TextUtils.isEmpty(deviceId) || invalidIds.contains(deviceId))) { return deviceId; } if (!newDeviceIdPerInstall) { // Android ID // Issues on 2.2, some phones have same Android ID due to // manufacturer error String androidId = android.provider.Settings.Secure.getString( context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); if (!(TextUtils.isEmpty(androidId) || invalidIds.contains(androidId))) { preferences.edit().putString(Constants.PREFKEY_DEVICE_ID, androidId).commit(); return androidId; } } // If this still fails, generate random identifier that does not persist // across installations String randomId = UUID.randomUUID().toString(); preferences.edit().putString(Constants.PREFKEY_DEVICE_ID, randomId).commit(); return randomId; } private static Location getMostRecentLocation() { LocationManager locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); List<String> providers = locationManager.getProviders(true); List<Location> locations = new ArrayList<Location>(); for (String provider : providers) { Location location = locationManager.getLastKnownLocation(provider); if (location != null) { locations.add(location); } } long maximumTimestamp = -1; Location bestLocation = null; for (Location location : locations) { if (location.getTime() > maximumTimestamp) { maximumTimestamp = location.getTime(); bestLocation = location; } } return bestLocation; } private static Object replaceWithJSONNull(Object obj) { return obj == null ? JSONObject.NULL : obj; } private static boolean contextAndApiKeySet(String methodName) { if (context == null) { Log.e(TAG, "context cannot be null, set context with initialize() before calling " + methodName); return false; } if (TextUtils.isEmpty(apiKey)) { Log.e(TAG, "apiKey cannot be null or empty, set apiKey with initialize() before calling " + methodName); return false; } return true; } private static String getSharedPreferencesName() { return Constants.SHARED_PREFERENCES_NAME_PREFIX + "." + context.getPackageName(); } private static String bytesToHexString(byte[] bytes) { final char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; char[] hexChars = new char[bytes.length * 2]; int v; for (int j = 0; j < bytes.length; j++) { v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } }
package net.gltd.gtms.client.openlink; import java.util.Collection; import java.util.HashMap; import java.util.Properties; import javax.xml.bind.JAXBException; import javax.xml.stream.XMLStreamException; import net.gltd.gtms.client.TestUtil; import net.gltd.gtms.extension.command.Command; import net.gltd.gtms.extension.command.Note; import net.gltd.gtms.extension.iodata.IoData; import net.gltd.gtms.extension.openlink.callstatus.Call; import net.gltd.gtms.extension.openlink.callstatus.Call.CallState; import net.gltd.gtms.extension.openlink.callstatus.CallFeature; import net.gltd.gtms.extension.openlink.callstatus.CallStatus; import net.gltd.gtms.extension.openlink.callstatus.CallerCallee; import net.gltd.gtms.extension.openlink.callstatus.Participant; import net.gltd.gtms.extension.openlink.callstatus.action.AddThirdParty; import net.gltd.gtms.extension.openlink.callstatus.action.AnswerCall; import net.gltd.gtms.extension.openlink.callstatus.action.CallAction; import net.gltd.gtms.extension.openlink.callstatus.action.ClearCall; import net.gltd.gtms.extension.openlink.callstatus.action.ClearConnection; import net.gltd.gtms.extension.openlink.callstatus.action.ConferenceFail; import net.gltd.gtms.extension.openlink.callstatus.action.ConnectSpeaker; import net.gltd.gtms.extension.openlink.callstatus.action.ConsultationCall; import net.gltd.gtms.extension.openlink.callstatus.action.DisconnectSpeaker; import net.gltd.gtms.extension.openlink.callstatus.action.HoldCall; import net.gltd.gtms.extension.openlink.callstatus.action.IntercomTransfer; import net.gltd.gtms.extension.openlink.callstatus.action.JoinCall; import net.gltd.gtms.extension.openlink.callstatus.action.PrivateCall; import net.gltd.gtms.extension.openlink.callstatus.action.PublicCall; import net.gltd.gtms.extension.openlink.callstatus.action.RemoveThirdParty; import net.gltd.gtms.extension.openlink.callstatus.action.RetrieveCall; import net.gltd.gtms.extension.openlink.callstatus.action.SendDigit; import net.gltd.gtms.extension.openlink.callstatus.action.SendDigits; import net.gltd.gtms.extension.openlink.callstatus.action.SingleStepTransfer; import net.gltd.gtms.extension.openlink.callstatus.action.StartVoiceDrop; import net.gltd.gtms.extension.openlink.callstatus.action.StopVoiceDrop; import net.gltd.gtms.extension.openlink.callstatus.action.TransferCall; import net.gltd.gtms.extension.openlink.command.RequestAction.RequestActionAction; import net.gltd.gtms.extension.openlink.features.Feature; import net.gltd.gtms.extension.openlink.features.Features; import net.gltd.gtms.extension.openlink.interests.Interest; import net.gltd.gtms.extension.openlink.interests.Interests; import net.gltd.gtms.extension.openlink.originatorref.Property; import net.gltd.gtms.extension.openlink.originatorref.Property2; import net.gltd.gtms.extension.openlink.profiles.Action; import net.gltd.gtms.extension.openlink.profiles.Profile; import net.gltd.gtms.extension.openlink.profiles.Profiles; import net.gltd.gtms.profiler.gtx.profile.GtxProfile; import net.gltd.gtms.profiler.gtx.profile.GtxSystem; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import rocks.xmpp.core.XmlTest; import rocks.xmpp.core.XmppException; import rocks.xmpp.core.stanza.model.client.IQ; import rocks.xmpp.core.stanza.model.client.Message; import rocks.xmpp.extensions.pubsub.model.Subscription; import rocks.xmpp.extensions.pubsub.model.event.Event; import rocks.xmpp.extensions.shim.model.Header; import rocks.xmpp.extensions.shim.model.Headers; public class OpenlinkClientIntegrationBatchTest extends XmlTest { protected static Logger logger = Logger.getLogger("net.gltd.gtms"); public static final String CLIENT_PROPERTIES = "clientbatch.properties"; private String username; private String domain; private String systemAndDomain; private HashMap<String, OpenlinkClient> clients = new HashMap<String, OpenlinkClient>();; private HashMap<String, Interest> interests = new HashMap<String, Interest>();; private Properties clientProperties; private int maxUsers = 0; private int startIndex = 0; public OpenlinkClientIntegrationBatchTest() throws JAXBException, XMLStreamException { super(Property2.class, Property.class, net.gltd.gtms.extension.openlink.properties.Property.class, Headers.class, Header.class, Event.class, Command.class, Note.class, Message.class, IQ.class, IoData.class, Profiles.class, Profile.class, Action.class, Interests.class, Interest.class, Features.class, Feature.class, CallStatus.class, Call.class, CallerCallee.class, CallFeature.class, Participant.class, CallAction.class, AddThirdParty.class, AnswerCall.class, ClearCall.class, ClearConnection.class, ConferenceFail.class, ConnectSpeaker.class, ConsultationCall.class, DisconnectSpeaker.class, HoldCall.class, IntercomTransfer.class, JoinCall.class, PrivateCall.class, PublicCall.class, RemoveThirdParty.class, RetrieveCall.class, SendDigit.class, SendDigits.class, SingleStepTransfer.class, RemoveThirdParty.class, SendDigits.class, StartVoiceDrop.class, StopVoiceDrop.class, TransferCall.class, net.gltd.gtms.profiler.gtx.profile.Feature.class, GtxProfile.class, GtxSystem.class, net.gltd.gtms.profiler.gtx.profile.Profile.class, net.gltd.gtms.profiler.gtx.profile.Property.class); } public void initialize() throws Exception { logger = TestUtil.initializeConsoleLogger("net.gltd.gtms", TestUtil.DEFAULT_DEBUG_CONVERSION_PATTERN, "DEBUG"); this.clientProperties = TestUtil.getProperties(this.getClass(), CLIENT_PROPERTIES); this.username = clientProperties.getProperty("client.xmpp.username"); this.domain = clientProperties.getProperty("client.xmpp.domain"); this.systemAndDomain = clientProperties.getProperty("client.xmpp.system") + "." + this.domain; this.maxUsers = Integer.valueOf(clientProperties.getProperty("client.maxusers")); this.startIndex = Integer.valueOf(clientProperties.getProperty("client.startindex")); for (int i = this.startIndex; i < startIndex + maxUsers; i++) { OpenlinkClient client = new OpenlinkClient(this.username + i, clientProperties.getProperty("client.xmpp.password") + i, clientProperties.getProperty("client.xmpp.resource"), this.domain, clientProperties.getProperty("client.xmpp.host")); client.setDebug(true); client.connect(); this.clients.put(this.username + i, client); logger.debug("CLIENT " + client.getBareJid() + " CONNECTING"); } } public void shutdown() { logger.debug("SHUTDOWN"); for (OpenlinkClient client : this.clients.values()) { if (client != null) { if (interests.get(client.getBareJid()) != null) { logger.debug("CLIENT " + client.getBareJid() + " UNSUBSCRIBE"); try { client.unsubscribe(interests.get(client.getBareJid())); } catch (XmppException e) { e.printStackTrace(); } } logger.debug("CLIENT " + client.getBareJid() + " DISCONNECTING"); client.disconnect(); } } LogManager.shutdown(); } public boolean isConnected(OpenlinkClient client) { boolean result = client != null && client.isConnected(); return result; } public Profile getPrimaryProfile(OpenlinkClient client, String to) throws Exception { Profile result = null; Collection<Profile> profiles = client.getProfiles(this.systemAndDomain); if (profiles != null && profiles.size() > 0) { for (Profile p : profiles) { if (p.isDefaultProfile()) { result = p; } } } return result; } public Interest getPrimaryInterest(OpenlinkClient client, String to, Profile profile) throws Exception { Interest result = null; Collection<Interest> interests = client.getInterests(this.systemAndDomain, profile); if (interests != null && interests.size() > 0) { for (Interest i : interests) { if (i.isDefaultInterest()) { result = i; } } } return result; } public HashMap<String, OpenlinkClient> getClients() { return clients; } public void setClients(HashMap<String, OpenlinkClient> clients) { this.clients = clients; } public void attachShutDownHook() { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { shutdown(); } catch (Exception e) { e.printStackTrace(); } } }); System.out.println("Shut Down Hook Attached."); } public static void main(String[] args) { OpenlinkClientIntegrationBatchTest test = null; try { test = new OpenlinkClientIntegrationBatchTest(); test.attachShutDownHook(); test.initialize(); for (OpenlinkClient client : test.getClients().values()) { client.addCallListener(test.new MyCallListener(client)); } while (true) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } public class MyCallListener implements CallListener { private OpenlinkClient client; public MyCallListener(OpenlinkClient client) { super(); this.client = client; try { if (!client.isConnected()) { throw new IllegalStateException("CLIENT " + client.getBareJid() + " NOT CONNECTED!"); } Profile p = getPrimaryProfile(client, systemAndDomain); if (p == null) { throw new IllegalStateException("CLIENT " + client.getBareJid() + " DEFAULT PROFILE NOT FOUND"); } Interest i = getPrimaryInterest(client, systemAndDomain, p); if (i == null) { throw new IllegalStateException("CLIENT " + client.getBareJid() + " DEFAULT INTEREST NOT FOUND"); } try { client.unsubscribe(i); } catch (XmppException e) { e.printStackTrace(); } Subscription s = client.subscribe(i); if (s == null) { throw new IllegalStateException("CLIENT " + client.getBareJid() + " SUBSCRIPTION FAILED"); } else { interests.put(client.getBareJid(), i); } logger.debug("CLIENT " + client.getBareJid() + " MONITORING: " + s.getNode() + " " + s.getSubId()); } catch (Exception e) { e.printStackTrace(); } } @Override public void callEvent(Collection<Call> calls) { for (Call c : calls) { logger.debug("CLIENT " + client.getBareJid() + " CALL EV: " + c.getId() + ": " + c); try { if (c.getState() == CallState.CallDelivered) { logger.debug("CLIENT " + client.getBareJid() + " ANSWER CALL: " + c.getId() + marshal(c)); client.requestAction(systemAndDomain, c, RequestActionAction.AnswerCall, null, null); } } catch (Exception e) { e.printStackTrace(); } } } } }
package com.dmdirc.util.io; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * Allows reading and writing to a plain text file via a list of lines. */ public class TextFile { /** * The file we're dealing with. */ private final Path path; /** * The input stream we're dealing with. */ private final InputStream is; /** * The charset to use to read the file. */ private final Charset charset; /** * The lines we've read from the file. */ private List<String> lines; /** * Creates a new instance of TextFile for the specified file, and uses the * default charset. * * @param filename The file to be read/written */ public TextFile(final String filename) { this(new File(filename)); } /** * Creates a new instance of TextFile for the specified File, and uses the * default charset. * * @param file The file to read */ public TextFile(final File file) { this(file, Charset.defaultCharset()); } /** * Creates a new instance of TextFile for the specified Path, and uses the * default charset. * * @param path The path to read */ public TextFile(final Path path) { this(path, Charset.defaultCharset()); } /** * Creates a new instance of TextFile for an input stream, and uses the * default charset. * * @param is The input stream to read from */ public TextFile(final InputStream is) { this(is, Charset.defaultCharset()); } /** * Creates a new instance of TextFile for the specified File, which is to be * read using the specified charset. * * @param file The file to read * @param charset The charset to read the file in * @since 0.6.3m1 */ public TextFile(final File file, final Charset charset) { this(file == null ? null : file.toPath(), charset); } /** * Creates a new instance of TextFile for the specified Path, which is to be * read using the specified charset. * * @param path The path to read * @param charset The charset to read the file in */ public TextFile(final Path path, final Charset charset) { this.path = path; this.is = null; this.charset = charset; } /** * Creates a new instance of TextFile for an input stream, which is to be * read using the specified charset. * * @param is The input stream to read from * @param charset The charset to read the file in * @since 0.6.3m1 */ public TextFile(final InputStream is, final Charset charset) { this.path = null; this.is = is; this.charset = charset; } /** * Retrieves the contents of the file as a list of lines. If getLines() or * readLines() has previously been called, a cached version is returned. * * @return An unmodifiable list of lines in the file * @throws IOException if an I/O exception occurs */ public List<String> getLines() throws IOException { if (lines == null) { readLines(); } return Collections.unmodifiableList(lines); } /** * Reads the contents of the file into this TextFile's line cache. * * @throws IOException If an I/O exception occurs */ public void readLines() throws IOException { if (path == null) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset))) { lines = reader.lines().collect(Collectors.toList()); } } else { lines = Files.readAllLines(path, charset); } } /** * Determines if this file is writable or not. * * @return True if the file is writable, false otherwise */ public boolean isWritable() { if (path == null) { return false; } if (Files.exists(path)) { return Files.isWritable(path); } else { return Files.isWritable(path.getParent()); } } /** * Writes the specified list of lines to the file. * * @param lines The lines to be written * @throws IOException if an I/O exception occurs */ public void writeLines(final Iterable<String> lines) throws IOException { if (path == null) { throw new UnsupportedOperationException("Cannot write to TextFile " + "opened with an InputStream"); } Files.write(path, lines, charset); } /** * Deletes the file associated with this textfile, if there is one. * * @throws IOException if the file is unable to be deleted */ public void delete() throws IOException { if (path == null) { throw new UnsupportedOperationException("Cannot delete TextFile " + "opened with an InputStream"); } Files.delete(path); } }
package net.katsuster.ememu.riscv; import net.katsuster.ememu.generic.*; import net.katsuster.ememu.riscv.core.*; /** * Core Local Interruptor (CLINT) * * : SiFive FU540-C000 Manual: v1p0 */ public class CLINT implements ParentCore { private RV64[] cores; private CLINTSlave slave; //4bytes registers public static final int REG_MSIP0 = 0x0000; public static final int REG_MSIP1 = 0x0004; public static final int REG_MSIP2 = 0x0008; public static final int REG_MSIP3 = 0x000c; public static final int REG_MSIP4 = 0x0010; public static final int REG_MSIP_RES5 = 0x0014; public static final int REG_MSIP_RES6 = 0x0018; public static final int REG_MSIP_RES7 = 0x001c; public static final int REG_MSIP_RES8 = 0x0020; public static final int REG_MSIP_RES9 = 0x0024; public static final int REG_MSIP_RES10 = 0x0028; public static final int REG_MSIP_RES11 = 0x002c; public static final int REG_MSIP_RES12 = 0x0030; public static final int REG_MSIP_RES13 = 0x0034; public static final int REG_MSIP_RES14 = 0x0038; public static final int REG_MSIP_RES15 = 0x003c; public static final int REG_MSIP_RES16 = 0x0040; public static final int REG_MSIP_RES17 = 0x0044; public static final int REG_MSIP_RES18 = 0x0048; public static final int REG_MSIP_RES19 = 0x004c; public static final int REG_MSIP_RES20 = 0x0050; public static final int REG_MSIP_RES21 = 0x0054; public static final int REG_MSIP_RES22 = 0x0058; public static final int REG_MSIP_RES23 = 0x005c; public static final int REG_MSIP_RES24 = 0x0060; public static final int REG_MSIP_RES25 = 0x0064; public static final int REG_MSIP_RES26 = 0x0068; public static final int REG_MSIP_RES27 = 0x006c; public static final int REG_MSIP_RES28 = 0x0070; public static final int REG_MSIP_RES29 = 0x0074; public static final int REG_MSIP_RES30 = 0x0078; public static final int REG_MSIP_RES31 = 0x007c; //8bytes registers public static final int REG_MTIMECMP0_L = 0x4000; public static final int REG_MTIMECMP0_H = 0x4004; public static final int REG_MTIMECMP1_L = 0x4008; public static final int REG_MTIMECMP1_H = 0x400c; public static final int REG_MTIMECMP2_L = 0x4010; public static final int REG_MTIMECMP2_H = 0x4014; public static final int REG_MTIMECMP3_L = 0x4018; public static final int REG_MTIMECMP3_H = 0x401c; public static final int REG_MTIMECMP4_L = 0x4020; public static final int REG_MTIMECMP4_H = 0x4024; public static final int REG_MTIME_L = 0xbff8; public static final int REG_MTIME_H = 0xbffc; public CLINT(RV64[] c) { cores = c; slave = new CLINTSlave(); } @Override public SlaveCore64 getSlaveCore() { return slave; } class CLINTSlave extends Controller32 { public CLINTSlave() { addReg(REG_MSIP0, "MSIP0", 0x00000000); addReg(REG_MSIP1, "MSIP1", 0x00000000); addReg(REG_MSIP2, "MSIP2", 0x00000000); addReg(REG_MSIP3, "MSIP3", 0x00000000); addReg(REG_MSIP4, "MSIP4", 0x00000000); addReg(REG_MSIP_RES5, "MSIP_RES5", 0x00000000); addReg(REG_MSIP_RES6, "MSIP_RES6", 0x00000000); addReg(REG_MSIP_RES7, "MSIP_RES7", 0x00000000); addReg(REG_MSIP_RES8, "MSIP_RES8", 0x00000000); addReg(REG_MSIP_RES9, "MSIP_RES9", 0x00000000); addReg(REG_MSIP_RES10, "MSIP_RES10", 0x00000000); addReg(REG_MSIP_RES11, "MSIP_RES11", 0x00000000); addReg(REG_MSIP_RES12, "MSIP_RES12", 0x00000000); addReg(REG_MSIP_RES13, "MSIP_RES13", 0x00000000); addReg(REG_MSIP_RES14, "MSIP_RES14", 0x00000000); addReg(REG_MSIP_RES15, "MSIP_RES15", 0x00000000); addReg(REG_MSIP_RES16, "MSIP_RES16", 0x00000000); addReg(REG_MSIP_RES17, "MSIP_RES17", 0x00000000); addReg(REG_MSIP_RES18, "MSIP_RES18", 0x00000000); addReg(REG_MSIP_RES19, "MSIP_RES19", 0x00000000); addReg(REG_MSIP_RES20, "MSIP_RES20", 0x00000000); addReg(REG_MSIP_RES21, "MSIP_RES21", 0x00000000); addReg(REG_MSIP_RES22, "MSIP_RES22", 0x00000000); addReg(REG_MSIP_RES23, "MSIP_RES23", 0x00000000); addReg(REG_MSIP_RES24, "MSIP_RES24", 0x00000000); addReg(REG_MSIP_RES25, "MSIP_RES25", 0x00000000); addReg(REG_MSIP_RES26, "MSIP_RES26", 0x00000000); addReg(REG_MSIP_RES27, "MSIP_RES27", 0x00000000); addReg(REG_MSIP_RES28, "MSIP_RES28", 0x00000000); addReg(REG_MSIP_RES29, "MSIP_RES29", 0x00000000); addReg(REG_MSIP_RES30, "MSIP_RES30", 0x00000000); addReg(REG_MSIP_RES31, "MSIP_RES31", 0x00000000); addReg(REG_MTIMECMP0_L, "MTIMECMP0_L", 0x00000000); addReg(REG_MTIMECMP0_H, "MTIMECMP0_H", 0x00000000); addReg(REG_MTIMECMP1_L, "MTIMECMP1_L", 0x00000000); addReg(REG_MTIMECMP1_H, "MTIMECMP1_H", 0x00000000); addReg(REG_MTIMECMP2_L, "MTIMECMP2_L", 0x00000000); addReg(REG_MTIMECMP2_H, "MTIMECMP2_H", 0x00000000); addReg(REG_MTIMECMP3_L, "MTIMECMP3_L", 0x00000000); addReg(REG_MTIMECMP3_H, "MTIMECMP3_H", 0x00000000); addReg(REG_MTIMECMP4_L, "MTIMECMP4_L", 0x00000000); addReg(REG_MTIMECMP4_H, "MTIMECMP4_H", 0x00000000); addReg(REG_MTIME_L, "MTIME_L", 0x00000000); addReg(REG_MTIME_H, "MTIME_H", 0x00000000); } @Override public int readWord(BusMaster64 m, long addr) { int regaddr; int result; regaddr = (int) (addr & BitOp.getAddressMask(LEN_WORD_BITS)); switch (regaddr) { case REG_MSIP0: //case REG_MSIP1: //case REG_MSIP2: //case REG_MSIP3: //case REG_MSIP4: int id = (regaddr - REG_MSIP0) / 4; if (cores[id].getXIP_XSIP(RV64.PRIV_M)) { result = 1; } else { result = 0; } System.out.printf("rd MSIP[%d] val:%08x\n", id, result); break; default: result = super.readWord(m, regaddr); break; } return result; } @Override public void writeWord(BusMaster64 m, long addr, int data) { int regaddr; regaddr = (int) (addr & BitOp.getAddressMask(LEN_WORD_BITS)); switch (regaddr) { case REG_MSIP0: //case REG_MSIP1: //case REG_MSIP2: //case REG_MSIP3: //case REG_MSIP4: int id = (regaddr - REG_MSIP0) / 4; boolean b = (data & 1) != 0; cores[id].setXIP_XSIP(RV64.PRIV_M, b); System.out.printf("MSIP[%d] val:%08x\n", id, data); break; default: super.writeWord(m, regaddr, data); break; } } @Override public long read64(BusMaster64 m, long addr) { int regaddr = (int) (addr & BitOp.getAddressMask(LEN_WORD_BITS)); long data; switch (regaddr) { case REG_MTIMECMP0_L: case REG_MTIMECMP1_L: case REG_MTIMECMP2_L: case REG_MTIMECMP3_L: case REG_MTIMECMP4_L: case REG_MTIME_L: break; default: throw new IllegalArgumentException(String.format( "Cannot read 64bit from 0x%08x.", addr)); } data = (((long)readWord(m, addr + 0) & 0xffffffffL) << 0) | (((long)readWord(m, addr + 4) & 0xffffffffL) << 32); return data; } @Override public void write64(BusMaster64 m, long addr, long data) { int regaddr = (int) (addr & BitOp.getAddressMask(LEN_WORD_BITS)); switch (regaddr) { case REG_MTIMECMP0_L: case REG_MTIMECMP1_L: case REG_MTIMECMP2_L: case REG_MTIMECMP3_L: case REG_MTIMECMP4_L: case REG_MTIME_L: break; default: throw new IllegalArgumentException(String.format( "Cannot write 64bit to 0x%08x.", addr)); } writeWord(m, addr + 0, (int)(data >>> 0)); writeWord(m, addr + 4, (int)(data >>> 32)); } @Override public void run() { //do nothing } } }
package nom.bdezonia.zorbage.procedure.impl.parse; import static org.junit.Assert.assertEquals; import org.junit.Test; import nom.bdezonia.zorbage.algebras.G; import nom.bdezonia.zorbage.procedure.Procedure; import nom.bdezonia.zorbage.tuple.Tuple2; import nom.bdezonia.zorbage.type.data.float64.real.Float64Algebra; import nom.bdezonia.zorbage.type.data.float64.real.Float64Member; /** * * @author Barry DeZonia * */ public class TestRealNumberEquation { @Test public void test1() { EquationParser<Float64Algebra,Float64Member> parser = new EquationParser<Float64Algebra,Float64Member>(); Tuple2<String, Procedure<Float64Member>> result = parser.parse(G.DBL, "4.7315"); assertEquals(null, result.a()); Float64Member tmp = G.DBL.construct(); result.b().call(tmp); assertEquals(4.7315, tmp.v(), 0.00000000000001); } @Test public void test2() { EquationParser<Float64Algebra,Float64Member> parser = new EquationParser<Float64Algebra,Float64Member>(); Tuple2<String, Procedure<Float64Member>> result = parser.parse(G.DBL, "1.4 + 2.6"); assertEquals(null, result.a()); Float64Member tmp = G.DBL.construct(); result.b().call(tmp); assertEquals(4, tmp.v(), 0.00000000000001); } @Test public void test3() { EquationParser<Float64Algebra,Float64Member> parser = new EquationParser<Float64Algebra,Float64Member>(); Tuple2<String, Procedure<Float64Member>> result = parser.parse(G.DBL, "1.4-2.6"); assertEquals(null, result.a()); Float64Member tmp = G.DBL.construct(); result.b().call(tmp); assertEquals(-1.2, tmp.v(), 0.00000000000001); } @Test public void test4() { EquationParser<Float64Algebra,Float64Member> parser = new EquationParser<Float64Algebra,Float64Member>(); Tuple2<String, Procedure<Float64Member>> result = parser.parse(G.DBL, "sin(PI/4)"); assertEquals(null, result.a()); Float64Member tmp = G.DBL.construct(); result.b().call(tmp); assertEquals(Math.sqrt(2)/2, tmp.v(), 0.00000000000001); } @Test public void test5() { EquationParser<Float64Algebra,Float64Member> parser = new EquationParser<Float64Algebra,Float64Member>(); Tuple2<String, Procedure<Float64Member>> result = parser.parse(G.DBL, "$0+$1"); assertEquals(null, result.a()); Float64Member tmp = G.DBL.construct(); result.b().call(tmp,G.DBL.construct("7"),G.DBL.construct("9")); assertEquals(16, tmp.v(), 0.00000000000001); } @Test public void test6() { EquationParser<Float64Algebra,Float64Member> parser = new EquationParser<Float64Algebra,Float64Member>(); Tuple2<String, Procedure<Float64Member>> result = parser.parse(G.DBL, "1.2e2-1.1"); assertEquals(null, result.a()); Float64Member tmp = G.DBL.construct(); result.b().call(tmp); assertEquals(120-1.1, tmp.v(), 0.00000000000001); } @Test public void test7() { EquationParser<Float64Algebra,Float64Member> parser = new EquationParser<Float64Algebra,Float64Member>(); Tuple2<String, Procedure<Float64Member>> result = parser.parse(G.DBL, "1--4"); assertEquals(null, result.a()); Float64Member tmp = G.DBL.construct(); result.b().call(tmp); assertEquals(5, tmp.v(), 0.00000000000001); } @Test public void test8() { EquationParser<Float64Algebra,Float64Member> parser = new EquationParser<Float64Algebra,Float64Member>(); Tuple2<String, Procedure<Float64Member>> result = parser.parse(G.DBL, "1-+4"); assertEquals(null, result.a()); Float64Member tmp = G.DBL.construct(); result.b().call(tmp); assertEquals(-3, tmp.v(), 0.00000000000001); } @Test public void test9() { EquationParser<Float64Algebra,Float64Member> parser = new EquationParser<Float64Algebra,Float64Member>(); Tuple2<String, Procedure<Float64Member>> result = parser.parse(G.DBL, "5-+1.4e-03"); assertEquals(null, result.a()); Float64Member tmp = G.DBL.construct(); result.b().call(tmp); assertEquals(5-0.0014, tmp.v(), 0.00000000000001); } /* TODO BROKEN @Test public void test10() { EquationParser<SignedInt16Algebra,SignedInt16Member> parser = new EquationParser<SignedInt16Algebra,SignedInt16Member>(); Tuple2<String, Procedure<SignedInt16Member>> result = parser.parse(G.INT16, "-32768"); assertEquals(null, result.a()); SignedInt16Member tmp = G.INT16.construct(); result.b().call(tmp); assertEquals(-32768, tmp.v()); } */ // Verify that I can parse a bunch of things by using a benchmark some other parsers are tested with. @Test public void monsterTest() { String[] eqns = { // trivial expressions and expressions eliminated by // constant folding "1", "$0", "2/abs(3*4/5)", "sin((1+2/2*3)*4^5)+cos(6*PI)", // Variablen und Variablenzusammenfassung // direkte Rckgabe von Variablen Zusammenfassung von Variablen // Alle gleichungen hier knnen auf eine Variable oder einen Term // der Form a*x+b mit a,b konstant zurckgefhrt werden "$0+1", "$0*2", "2*$0+1", "(2*$0+1)*3", // Polynome / Optimierung von Potenzfunktionen testen // Polynomials with integer exponents "$0^2+1", "1+$0^2", "1.1*$0^2", "1.1*$0^2 + 2.2*$1^3", "1.1*$0^2 + 2.2*$1^3 + 3.3*$2^4", // Polynome mit floating point exponenten "1.1*$0^2.01", "1.1*$0^2.01 + 2.2*$1^3.01", "1.1*$0^2.01 + 2.2*$1^3.01 + 3.3*$2^4.01", //physikalisch relevante gleichungen (variablen sind willkrlich gesetzt) // gausskurve "1/($0*sqrt(2*PI))*E^(-0.5*(($1-$0)/$0)^2)", // hornerschema: "(((((((7*$0+6)*$0+5)*$0+4)*$0+3)*$0+2)*$0+1)*$0+0.1)", "7*$0^7+6*$0^6+5*$0^5+4*$0^4+3*$0^3+2*$0^2+1*$0^1+0.1", // distance calculation "sqrt($0^2+$1^2)", // Overhead of basic function calls "sin($0)", "sqrt($0)", "abs($0)", // Simple expressions without functions "$0+$1", "$0+$1-$2", "$0*$1*$2", "$0/$1/$2", "$0+$1*$2", "$0*$1+$2", "$0/(($0+$1)*($0-$1))/$1", "1-(($0*$1)+($0/$1))-3", "($0+$1)*3", "-($1^1.1)", "$0+$1*($0+$1)", "(1+$1)*(-3)", "$0+$1-E*PI/5^6", "$0^$1/E*PI-5+6", "$0*2+2*$1", "2*($0+$1)", "($0+$1)*2", "-$0+-$1", "-$0 "-$0*-$1", "-$0/-$1", "-$0*$1", "-$0/$1", "$0*-$1", "$0/-$1", "$0+1-2/3", "1+$0-2/3", "(1+$0)-2/3", "1+($0-2/3)", "($0/(((($1+(((E*(((((PI*((((3.45*((PI+$0)+PI))+$1)+$1)*$0))+0.68)+E)+$0)/$0))+$0)+$1))+$1)*$0)-PI))", "(5.5+$0)+(2*$0-2/3*$1)*($0/3+$1/4)+($2+7.7)", "(((($0)-($1))+(($2)-($3)))/((($4)-($5))+(($6)-($0))))*(((($1)-($2))+(($3)-($4)))/((($5)-($6))+(($0)-($1))))", "((((2*$0)-($1*3))+((4*$2)-($3*5)))/((($4/6)-(7/$5))+(($6/8)-($0^2))))*(((($1^3)-($2/4))+((5/$3)-(6/$4)))/((($5/7)-(8/$6))+(($0)-($1))))", // expressions with functions "$0+(cos($1-sin(2/$0*PI))-sin($0-cos(2*$1/PI)))-$1", "sin($0)+sin($1)", "abs(sin(sqrt($0^2+$1^2))*255)", "-abs($0+1)*-sin(2-$1)", "sqrt($0)*sin(8)", "(10+sqrt($0))*(sin(8)^2)", "($1+$0/$1) * ($0-$1/$0)", "(0.1*$0+1)*$0+1.1-sin($0)-log($0)/$0*3/4", "sin(2 * $0) + cos(PI / $1)", "1 - sin(2 * $0) + cos(PI / $1)", "sqrt(1 - sin(2 * $0) + cos(PI / $1) / 3)", "($0^2 / sin(2 * PI / $1)) -$0 / 2", "1-($0/$1*0.5)", "E^log(7*$0)", "10^log(3+$1)", "(cos(2.41)/$1)", "-(sin(PI+$0)+1)", "$0-(E^(log(7+$1)))" }; EquationParser<Float64Algebra,Float64Member> parser = new EquationParser<Float64Algebra,Float64Member>(); for (String eqn : eqns) { Tuple2<String, Procedure<Float64Member>> result = parser.parse(G.DBL, eqn); assertEquals(null, result.a()); } } }
package com.ecyrd.jspwiki.ui; import com.ecyrd.jspwiki.WikiContext; /** * Describes an editor. * * @author Chuck Smith * @since 2.4.12 */ public class Editor { private String m_editorName; private WikiContext m_wikiContext; private EditorManager m_editorManager; public Editor( WikiContext wikiContext, String editorName ) { m_wikiContext = wikiContext; m_editorName = editorName; m_editorManager = wikiContext.getEngine().getEditorManager(); } public String getName() { return m_editorName; } public String getURL() { String uri = m_wikiContext.getHttpRequest().getRequestURI(); String para = m_wikiContext.getHttpRequest().getQueryString(); // if para already contains editor parameter, replace instead of append it // FIXME: Should cut out parameter instead of simple setting strin to null, maybe // in futur releases it may change and theres the danger that trailing parameters get lost int idx = para.indexOf(EditorManager.PARA_EDITOR + "="); if (idx >= 0) { para = para.substring(0, idx-1); } return uri + "?" + para + "&amp;" + EditorManager.PARA_EDITOR + "=" + m_editorName; } /** * Convinience method which returns XHTML for an option element. * @return "selected='selected'", if this editor is selected. */ public String isSelected( ) { return isSelected( "selected='selected'", "" ); } public String isSelected( String ifSelected ) { return isSelected( ifSelected, "" ); } public String isSelected( String ifSelected, String ifNotSelected ) { if ( m_editorName.equals(m_editorManager.getEditorName(m_wikiContext) ) ) { return ifSelected; } return ifNotSelected; } public String toString() { return m_editorName; } }
package org.alienlabs.hatchetharry.integrationTest; import java.util.concurrent.TimeUnit; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.webapp.WebAppContext; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.firefox.internal.ProfilesIni; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.Select; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FullAppTraversalTests { private static final Logger LOGGER = LoggerFactory.getLogger(FullAppTraversalTests.class); private static final String PORT = "8088"; private static final String HOST = "localhost"; private static final Server server = new Server(); private static WebDriver chromeDriver1; private static WebDriver chromeDriver2; private static final String SHOW_AND_OPEN_MOBILE_MENUBAR = "jQuery('#cssmenu').hide(); jQuery('.categories').hide(); jQuery('.dropdownmenu').show(); jQuery('.dropdownmenu:first').click();"; private static final String JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS = "window.scrollBy(0,100); jQuery('.w_content_container').scrollTop(200);"; private static final String JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_RESPONSIVE_MENU = "function elementInViewport(el) {\n" + " var top = el.offsetTop;\n" + " var left = el.offsetLeft;\n" + " var width = el.offsetWidth;\n" + " var height = el.offsetHeight;\n" + "\n" + " while(el.offsetParent) {\n" + " el = el.offsetParent;\n" + " top += el.offsetTop;\n" + " left += el.offsetLeft;\n" + " }\n" + "\n" + " return (\n" + " top > (window.pageYOffset + 50) &&\n" + " left > (window.pageXOffset + 50) &&\n" + " (top + height + 50) < (window.pageYOffset + window.innerHeight) &&\n" + " (left + width + 50) < (window.pageXOffset + window.innerWidth)\n" + " );\n" + "}\n" + "\n" + "var elementToLookFor = document.getElementById('revealTopLibraryCardLinkResponsive');\n" + "\n" + "for (var i = 0; i < 10000; i = i + 1) {\n" + " if (elementInViewport(elementToLookFor)) {\n" + " break;\n" + " } else {\n" + " window.scrollBy(0,5);\n}\n}"; private static final String JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_CARD = "function elementInViewport(el) {\n" + " var top = el.offsetTop;\n" + " var left = el.offsetLeft;\n" + " var width = el.offsetWidth;\n" + " var height = el.offsetHeight;\n" + "\n" + " while(el.offsetParent) {\n" + " el = el.offsetParent;\n" + " top += el.offsetTop;\n" + " left += el.offsetLeft;\n" + " }\n" + "\n" + " return (\n" + " top > (window.pageYOffset + 50) &&\n" + " left > (window.pageXOffset + 50) &&\n" + " (top + height + 50) < (window.pageYOffset + window.innerHeight) &&\n" + " (left + width + 50) < (window.pageXOffset + window.innerWidth)\n" + " );\n" + "}\n" + "\n" + "var elementToLookFor = jQuery(\"img[id^='tapHandleImage']\");\n" + "\n" + "for (var i = 0; i < 10000; i = i + 1) {\n" + " if (elementInViewport(elementToLookFor)) {\n" + " break;\n" + " } else {\n" + " window.scrollBy(0,5);\n}\n}"; private static final String JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_PUT_TO_ZONE_SUMBIT_BUTTON_FOR_HAND = "function elementInViewport(el) {\n" + " var top = el.offsetTop;\n" + " var left = el.offsetLeft;\n" + " var width = el.offsetWidth;\n" + " var height = el.offsetHeight;\n" + "\n" + " while(el.offsetParent) {\n" + " el = el.offsetParent;\n" + " top += el.offsetTop;\n" + " left += el.offsetLeft;\n" + " }\n" + "\n" + " return (\n" + " top > (window.pageYOffset + 50) &&\n" + " left > (window.pageXOffset + 50) &&\n" + " (top + height + 50) < (window.pageYOffset + window.innerHeight) &&\n" + " (left + width + 50) < (window.pageXOffset + window.innerWidth)\n" + " );\n" + "}\n" + "\n" + "var elementToLookFor = jQuery(\"#moveToZoneSubmitHand\");\n" + "\n" + "for (var i = 0; i < 10000; i = i + 1) {\n" + " if (elementInViewport(elementToLookFor)) {\n" + " break;\n" + " } else {\n" + " window.scrollBy(0,5);\n}\n}"; @Before public void setUp() throws Exception { FullAppTraversalTests.LOGGER .info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> STARTING EMBEDDED JETTY SERVER"); final ServerConnector http = new ServerConnector(FullAppTraversalTests.server); http.setHost(FullAppTraversalTests.HOST); http.setPort(Integer.parseInt(FullAppTraversalTests.PORT)); http.setIdleTimeout(30000); FullAppTraversalTests.server.addConnector(http); final WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); webapp.setWar("src/main/webapp"); FullAppTraversalTests.server.setHandler(webapp); FullAppTraversalTests.server.start(); FullAppTraversalTests.LOGGER .info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SUCCESSFULLY STARTED EMBEDDED JETTY SERVER"); System.setProperty("webdriver.chrome.driver", "/home/nostromo/chromedriver"); FullAppTraversalTests.chromeDriver1 = new ChromeDriver(); FullAppTraversalTests.chromeDriver1.manage().timeouts() .implicitlyWait(30, TimeUnit.SECONDS); FullAppTraversalTests.chromeDriver2 = new ChromeDriver(); FullAppTraversalTests.chromeDriver2.manage().timeouts() .implicitlyWait(30, TimeUnit.SECONDS); Thread.sleep(5000); FullAppTraversalTests.chromeDriver1.get("http://" + FullAppTraversalTests.HOST + ":" + FullAppTraversalTests.PORT + "/"); FullAppTraversalTests.chromeDriver2.get("http://" + FullAppTraversalTests.HOST + ":" + FullAppTraversalTests.PORT + "/"); Thread.sleep(5000); } @After public void tearDown() throws Exception { if (null != FullAppTraversalTests.chromeDriver1) { FullAppTraversalTests.chromeDriver1.quit(); } if (null != FullAppTraversalTests.chromeDriver2) { FullAppTraversalTests.chromeDriver2.quit(); } FullAppTraversalTests.LOGGER .info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> STOPPING EMBEDDED JETTY SERVER"); FullAppTraversalTests.server.stop(); FullAppTraversalTests.server.join(); Thread.sleep(30000); } @Test public void testFullAppTraversal() throws InterruptedException { // Create a game in Chrome 1 ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); Thread.sleep(8000); FullAppTraversalTests.chromeDriver1.findElement(By.id("createGameLinkResponsive")).click(); Thread.sleep(8000); FullAppTraversalTests.chromeDriver1.findElement(By.id("name")).clear(); FullAppTraversalTests.chromeDriver1.findElement(By.id("name")).sendKeys("Zala"); new Select(FullAppTraversalTests.chromeDriver1.findElement(By.id("sideInput"))) .getOptions().get(1).click(); new Select(FullAppTraversalTests.chromeDriver1.findElement(By.id("decks"))).getOptions() .get(1).click(); final String gameId = FullAppTraversalTests.chromeDriver1.findElement(By.id("gameId")) .getText(); FullAppTraversalTests.chromeDriver1.findElement(By.id("createSubmit")).click(); Thread.sleep(8000); // Join a game in Firefox ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver2.findElement(By.id("joinGameLinkResponsive")).click(); Thread.sleep(8000); FullAppTraversalTests.chromeDriver2.findElement(By.id("name")).clear(); FullAppTraversalTests.chromeDriver2.findElement(By.id("name")).sendKeys("Marie"); new Select(FullAppTraversalTests.chromeDriver2.findElement(By.id("sideInput"))) .getOptions().get(2).click(); new Select(FullAppTraversalTests.chromeDriver2.findElement(By.id("decks"))).getOptions() .get(2).click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("gameIdInput")).clear(); FullAppTraversalTests.chromeDriver2.findElement(By.id("gameIdInput")).sendKeys(gameId); FullAppTraversalTests.chromeDriver2.findElement(By.id("joinSubmit")).click(); // Assert that no card is present on battlefield // The Balduvian Horde is hidden but still there // And it contains TWO elements of class magicCard Thread.sleep(8000); Assert.assertEquals(2, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .size()); Assert.assertEquals(2, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .size()); // Verify that the hands contains 7 cards Assert.assertEquals(7, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".movers-row")) .size()); Assert.assertEquals(7, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".movers-row")) .size()); // Find first hand card name of Chrome1 final String battlefieldCardName = FullAppTraversalTests.chromeDriver2 .findElements(By.cssSelector(".cross-link:nth-child(1) img")).get(0) .getAttribute("name"); // Play a card in firefox FullAppTraversalTests.chromeDriver2.findElement(By.id("playCardLink0")).click(); // Verify that the hand contains only 6 cards, now Thread.sleep(12000); Assert.assertEquals(6, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".movers-row")) .size()); // Verify that card is present on the battlefield // Two HTML elements with class "magicCard" are created for each card Assert.assertEquals(4, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .size()); Assert.assertEquals(4, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .size()); // Verify the name of the card on the battlefield Assert.assertEquals(battlefieldCardName, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); Assert.assertEquals(battlefieldCardName, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); // Verify that the card is untapped Assert.assertFalse(FullAppTraversalTests.chromeDriver2 .findElements(By.cssSelector("img[id^='card']")).get(0).getAttribute("style") .contains("transform")); Assert.assertFalse(FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector("img[id^='card']")).get(0).getAttribute("style") .contains("transform")); // Tap card ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_CARD); FullAppTraversalTests.chromeDriver2.findElement( By.cssSelector("img[id^='tapHandleImage']")).click(); Thread.sleep(8000); // Verify card is tapped Assert.assertTrue(FullAppTraversalTests.chromeDriver2 .findElements(By.cssSelector("img[id^='card']")).get(0).getAttribute("style") .contains("rotate(90deg)")); Assert.assertTrue(FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector("img[id^='card']")).get(0).getAttribute("style") .contains("rotate(90deg)")); // Assert that graveyard is not visible Assert.assertTrue(FullAppTraversalTests.chromeDriver2.findElements( By.id("graveyard-page-wrap")).isEmpty()); // Grow up zone images ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript("$('#putToGraveyard').attr('src', 'image/graveyard.jpg');"); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript("$('#putToHand').attr('src', 'image/hand.jpg');"); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript("$('#putToExile').attr('src', 'image/exile.jpg');"); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript("$('#putToGraveyard').attr('src', 'image/graveyard.jpg');"); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript("$('#putToHand').attr('src', 'image/hand.jpg');"); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript("$('#putToExile').attr('src', 'image/exile.jpg');"); // Put card to graveyard WebElement draggable = FullAppTraversalTests.chromeDriver1.findElement(By .cssSelector("img[id^='handleImage']")); WebElement to = FullAppTraversalTests.chromeDriver1.findElement(By.id("putToGraveyard")); new Actions(FullAppTraversalTests.chromeDriver1).dragAndDrop(draggable, to).build() .perform(); Thread.sleep(30000); // Assert graveyard is visible and contains one card Assert.assertFalse(FullAppTraversalTests.chromeDriver2.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".graveyard-cross-link")).size() == 1); // Verify name of the card in the graveyard Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver2 .findElements(By.cssSelector(".graveyard-cross-link:nth-child(1) img")).get(0) .getAttribute("name"))); // Play card from graveyard ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); Thread.sleep(8000); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_RESPONSIVE_MENU); FullAppTraversalTests.chromeDriver2.findElement( By.id("playCardFromGraveyardLinkResponsive")).click(); Thread.sleep(8000); // Verify the name of the card on the battlefield Assert.assertEquals(battlefieldCardName, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); Assert.assertEquals(battlefieldCardName, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); // Assert that the graveyard is visible and empty Assert.assertFalse(FullAppTraversalTests.chromeDriver2.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".graveyard-cross-link")).isEmpty()); // Put card to hand draggable = FullAppTraversalTests.chromeDriver2.findElement(By .cssSelector("img[id^='handleImage']")); to = FullAppTraversalTests.chromeDriver2.findElement(By.id("putToHand")); new Actions(FullAppTraversalTests.chromeDriver2).dragAndDrop(draggable, to).build() .perform(); Thread.sleep(8000); // Assert that the hand contains 7 cards again Assert.assertEquals(7, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".movers-row")) .size()); // Reveal top card of library ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); Thread.sleep(2000); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_RESPONSIVE_MENU); FullAppTraversalTests.chromeDriver2.findElement( By.id("revealTopLibraryCardLinkResponsive")).click(); Thread.sleep(8000); // Get top card name final String topCardName = FullAppTraversalTests.chromeDriver2.findElement( By.id("topLibraryCard")).getAttribute("name"); // Verify that the card name is the same in the second browser Assert.assertTrue(topCardName.equals(FullAppTraversalTests.chromeDriver1.findElement( By.id("topLibraryCard")).getAttribute("name"))); // Click on the button "Do nothing" FullAppTraversalTests.chromeDriver2.findElement(By.id("doNothing")).click(); FullAppTraversalTests.chromeDriver1.findElement(By.id("doNothing")).click(); Thread.sleep(8000); // Reveal again ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver2.findElement( By.id("revealTopLibraryCardLinkResponsive")).click(); Thread.sleep(8000); // Assert that the card is the same Assert.assertTrue(topCardName.equals(FullAppTraversalTests.chromeDriver2.findElement( By.id("topLibraryCard")).getAttribute("name"))); Assert.assertTrue(topCardName.equals(FullAppTraversalTests.chromeDriver1.findElement( By.id("topLibraryCard")).getAttribute("name"))); // Put to battlefield ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); FullAppTraversalTests.chromeDriver2.findElement(By.id("putToBattlefieldFromModalWindow")) .click(); FullAppTraversalTests.chromeDriver1.findElement(By.id("doNothing")).click(); // Verify that the card is present on the battlefield Thread.sleep(8000); Assert.assertEquals(4, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .size()); Assert.assertEquals(4, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .size()); // Assert that the card on the battlefield is the same Assert.assertEquals(topCardName, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); Assert.assertEquals(topCardName, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); // Reveal top card of library ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver2.findElement( By.id("revealTopLibraryCardLinkResponsive")).click(); Thread.sleep(8000); // Put to hand ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); FullAppTraversalTests.chromeDriver2.findElement(By.id("putToHandFromModalWindow")).click(); FullAppTraversalTests.chromeDriver1.findElement(By.id("doNothing")).click(); Thread.sleep(8000); // Assert that the hand contains 8 cards Assert.assertEquals(8, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".movers-row")) .size()); // Verify that there is still two cards on the battlefield Assert.assertEquals(4, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .size()); Assert.assertEquals(4, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .size()); // Reveal again ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver2.findElement( By.id("revealTopLibraryCardLinkResponsive")).click(); Thread.sleep(8000); // Get top card name final String graveyardCardName = FullAppTraversalTests.chromeDriver2.findElement( By.id("topLibraryCard")).getAttribute("name"); // Put to graveyard ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); FullAppTraversalTests.chromeDriver2.findElement(By.id("putToGraveyardFromModalWindow")) .click(); FullAppTraversalTests.chromeDriver1.findElement(By.id("doNothing")).click(); Thread.sleep(8000); // Assert graveyard is visible and contains one card Assert.assertFalse(FullAppTraversalTests.chromeDriver2.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".graveyard-cross-link")).size() == 1); // Verify name of the card in the graveyard Assert.assertTrue(graveyardCardName.equals(FullAppTraversalTests.chromeDriver2 .findElements(By.cssSelector(".graveyard-cross-link:nth-child(1) img")).get(0) .getAttribute("name"))); // Verify that there is still two cards on the battlefield Assert.assertEquals(4, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .size()); Assert.assertEquals(4, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .size()); // Verify the name of the card on the battlefield Assert.assertEquals(topCardName, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); Assert.assertEquals(topCardName, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); // Verify that the hands contains 8 cards Assert.assertEquals(8, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".movers-row")) .size()); Assert.assertEquals(7, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".movers-row")) .size()); // Put one card from hand to graveyard ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_PUT_TO_ZONE_SUMBIT_BUTTON_FOR_HAND); new Select( FullAppTraversalTests.chromeDriver2.findElement(By.id("putToZoneSelectForHand"))) .getOptions().get(1).click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("moveToZoneSubmitHand")).click(); Thread.sleep(8000); // Verify that there is one more card in the graveyard Assert.assertFalse(FullAppTraversalTests.chromeDriver2.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertEquals( 2, FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".graveyard-cross-link")).size()); // Put current card from hand to exile new Select( FullAppTraversalTests.chromeDriver2.findElement(By.id("putToZoneSelectForHand"))) .getOptions().get(2).click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("moveToZoneSubmitHand")).click(); Thread.sleep(8000); // Verify that there is one more card in the exile and that it is // visible Assert.assertFalse(FullAppTraversalTests.chromeDriver2.findElements( By.id("exile-page-wrap")).isEmpty()); Assert.assertEquals( 1, FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".exile-cross-link")).size()); // Put current card in exile to graveyard new Select(FullAppTraversalTests.chromeDriver2.findElement(By .id("putToZoneSelectForExile"))).getOptions().get(1).click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("moveToZoneSubmitExile")).click(); Thread.sleep(8000); // Verify that there is one more card in the graveyard Assert.assertFalse(FullAppTraversalTests.chromeDriver2.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertEquals( 3, FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".graveyard-cross-link")).size()); // Get name of the current card in the hand final String handCardName = FullAppTraversalTests.chromeDriver2 .findElements(By.cssSelector(".cross-link:nth-child(1) img")).get(0) .getAttribute("name"); // Put current card from hand to exile new Select( FullAppTraversalTests.chromeDriver2.findElement(By.id("putToZoneSelectForHand"))) .getOptions().get(2).click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("moveToZoneSubmitHand")).click(); Thread.sleep(8000); // Verify that there is one more card in the exile Assert.assertFalse(FullAppTraversalTests.chromeDriver2.findElements( By.id("exile-page-wrap")).isEmpty()); Assert.assertEquals( 1, FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".exile-cross-link")).size()); // Get name of the current card in the exile final String exileCardName = FullAppTraversalTests.chromeDriver2 .findElements(By.cssSelector(".exile-cross-link:nth-child(1) img")).get(0) .getAttribute("name"); // Verify that active card in exile is same than card from hand Assert.assertEquals(handCardName, exileCardName); // Put card from exile to battlefield new Select(FullAppTraversalTests.chromeDriver2.findElement(By .id("putToZoneSelectForExile"))).getOptions().get(0).click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("moveToZoneSubmitExile")).click(); Thread.sleep(8000); // Verify that there are three cards on the battlefield Assert.assertEquals(6, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .size()); Assert.assertEquals(6, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .size()); // Verify the name of the card on the battlefield Assert.assertEquals(exileCardName, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .get(4).getAttribute("name")); Assert.assertEquals(exileCardName, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .get(4).getAttribute("name")); } }
package com.tlamatini.modelo; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.sql.Date; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.hyphenation.TernaryTree.Iterator; public class Ticket implements Iterable<Producto> { int indice; ArrayList<Producto> productosVenta =null; void imprime() throws FileNotFoundException, DocumentException{ FileOutputStream archivo = new FileOutputStream("C:"); Document documento = new Document(); PdfWriter.getInstance(documento, archivo); documento.open(); documento.add(new Paragraph("Hola Mundo!")); documento.add(new Paragraph("Luis Enrique Acosta Meza")); documento.close(); } public String guardarVentaPDF(ArrayList<Producto> productosVenta,double total_descuento){ Document documento = new Document(PageSize.LETTER, 80, 80, 75, 75); PdfWriter writer = null; Calendar fecha = new GregorianCalendar(); int ao = fecha.get(Calendar.YEAR); int mes = fecha.get(Calendar.MONTH); int dia = fecha.get(Calendar.DAY_OF_MONTH); int hora = fecha.get(Calendar.HOUR_OF_DAY); int minuto = fecha.get(Calendar.MINUTE); int segundo = fecha.get(Calendar.SECOND); double costo; int cont=0; String fecha1="fecha-"+ao+"-"+(mes+1)+"-"+dia+"-hora-"+hora+"-"+minuto+"-"+segundo; String dato="../"+fecha1+".pdf"; System.out.println("Fecha Actual: "+fecha1); System.out.println(dato); try { writer = PdfWriter.getInstance(documento, new FileOutputStream(dato)); documento.addTitle("Tiket de compra"); documento.addAuthor("Maoli"); System.out.println("Imprime 2"); documento.open(); Paragraph parrafo = new Paragraph(); parrafo.setAlignment(Paragraph.ALIGN_CENTER); parrafo.setFont(FontFactory.getFont("Sans",20,Font.BOLD, BaseColor.BLUE)); parrafo.add("Gracias Por Su Compra\n"); Paragraph parrafo1 = new Paragraph(); parrafo1.setAlignment(Paragraph.ALIGN_JUSTIFIED); parrafo1.setFont(FontFactory.getFont("Sans",20,Font.BOLD, BaseColor.BLUE)); parrafo1.add("\nNOMBRE"+" "+"PRECIO"+" "+"CANTIDAD"+" "+"TOTAL"); System.out.println("Imprime 3"); Paragraph ventas = new Paragraph(); parrafo.setAlignment(Paragraph.ALIGN_RIGHT); ventas.setFont(FontFactory.getFont("Sans",20,Font.BOLD, BaseColor.BLACK)); float acumulado=0; System.out.println("Imprime 4"); for(indice = 0; indice < productosVenta.size(); indice++){ System.out.println("Imprime 5"); costo=productosVenta.get(indice).getCostoUnitario()*.10; costo=costo+productosVenta.get(indice).getCostoUnitario(); ventas.add(productosVenta.get(indice).getNombre()+": \t "+costo+": \t "+productosVenta.get(indice).getCantidad()+" : \t "+costo*productosVenta.get(indice).getCantidad()+"\n"); acumulado=(float) (acumulado+costo*productosVenta.get(indice).getCantidad()); //Iterator i = (Iterator) productosVenta.iterator(); System.out.println(productosVenta.get(indice).getNombre()+" "+productosVenta.get(indice).getCostoUnitario()+" cantidad "+productosVenta.get(indice).getCantidad()+"\n"); } ventas.add("Precio total a pagar: "+acumulado); Paragraph totalcondescuento = new Paragraph(); parrafo.setAlignment(Paragraph.ALIGN_RIGHT); totalcondescuento.add("Precio total a pagar con descuento: "+total_descuento); Paragraph fechapdf = new Paragraph(); parrafo.setAlignment(Paragraph.ALIGN_RIGHT); fechapdf.add(fecha1); ventas.setFont(FontFactory.getFont("Sans",20,Font.BOLD, BaseColor.BLACK)); documento.add(parrafo); documento.add(parrafo1); documento.add(ventas); documento.add(totalcondescuento); documento.add(fechapdf); //documento.add(fecha2); writer.close(); documento.close(); return dato; } catch (Exception ex) { ex.getMessage(); } return dato; } @Override public java.util.Iterator<Producto> iterator() { // TODO Auto-generated method stub return null; } }
package com.tpcstld.jetris; import java.util.ArrayList; import java.util.Random; import java.util.Timer; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.MotionEvent; import android.view.View; public class MainGame extends View { Paint paint = new Paint(); // Internal Options static int test = 0; static int numSquaresX = 16; // Total number of columns static int numSquaresY = 22; // total number of rows static double textScaleSize = 0.8; // Text scaling // External Options static double defaultGravity = ClassicModeActivity.defaultGravity; static int FPS = ClassicModeActivity.FPS; static int flickSensitivity = ClassicModeActivity.flickSensitivity; static int slackLength = ClassicModeActivity.slackLength; static double softDropMultiplier = ClassicModeActivity.softDropMultiplier; static Timer time = new Timer(true); static boolean slack = false; // Whether or not slack is currently active static boolean pause = false; // Whether or not the pause is currently // paused static boolean lose = false; // Whether or not the game is still in progress static boolean holdOnce = false; // Whether or not the block has already // been held once static boolean hardDrop = false; // Whether or not harddropping is active static boolean slackOnce = false; // Whether or not slack as already been // activated static boolean turnSuccess = false; // Whether or not a turn was successful static boolean softDrop = false; // Whether or not softdropping is active static boolean kick = false; // Whether or not the block was kicked to // location static boolean difficult = false; // Whether or not a clear was considered // to be "hard" static boolean lastDifficult = false; // Whether or not the last clear was // considered to be "hard" static int score = 0; static int mainFieldShiftX; // How much the screen is shifted to the right static int mainFieldShiftY; // How much the screen is shifted downwards static int squareSide; // The size of one square static int numberOfBlocksWidth = 10; // The number of columns of blocks in // the main field static int numberOfBlocksLength = 22; // The number of rows of blocks in the // main field static int numberOfHoldShapeWidth = 4; // The width of the auxiliary boxes static int numberOfHoldShapeLength = 2; // The length of the auxiliary boxes static int holdShapeXStarting; // Where the hold box starts (x) static int nextShapeYStarting; // Where the first next box starts (y) static int nextShapeY2Starting; // Where the second next box starts (y) static int nextShapeY3Starting; // Where the third next box starts (y) static int thisShape = -1; // The NEXT shape on the playing field. static int nextShape = -1; // The NEXT2 shape on the playing field. static int nextShape1 = -1; // The NEXT3 shaped on the playing field. static int holdShape = -1; // The shape currently being held. static int lastShape = -1; // The CURRENT shape on the playing field. // A list containing the shapes left in the current bag static ArrayList<Integer> shapeList = new ArrayList<Integer>(); static int shape = 0; // The current shape of the block static int combo = 0; // The current combo static int scoreInfoYStarting; // Where the score box starts (y) static Random r = new Random(); // The randomizer // Array detailing the type of block in each square static int[][] blocks = new int[numberOfBlocksWidth][numberOfBlocksLength]; // Array detailing the colour in each square static int[][] colors = new int[numberOfBlocksWidth][numberOfBlocksLength]; // Array displaying the block in hold static int[][] holdBlocks = new int[numberOfHoldShapeWidth][numberOfHoldShapeLength]; // Array displaying the next block static int[][] nextBlocks = new int[numberOfHoldShapeWidth][numberOfHoldShapeLength]; // Array displaying the next2 block static int[][] next2Blocks = new int[numberOfHoldShapeWidth][numberOfHoldShapeLength]; // Array displaying the next3 block static int[][] next3Blocks = new int[numberOfHoldShapeWidth][numberOfHoldShapeLength]; static int[] playLocationX = new int[4]; // X-coords of the blocks in play static int[] playLocationY = new int[4]; // Y-coords of the blocks in play static double gravity = defaultGravity; // The current gravity of the game static double totalGrav = 0; // The current gravity ticker static long clock = System.currentTimeMillis(); // Tracks the real time for // fps static boolean getScreenSize = false; // Initial getting screen size // variable // Blocks Data: // 0 = empty space // 1 = active space // 2 = locked space // 3 = ghost space public MainGame(Context context) { super(context); defaultGravity = ClassicModeActivity.defaultGravity; FPS = ClassicModeActivity.FPS; flickSensitivity = ClassicModeActivity.flickSensitivity; slackLength = ClassicModeActivity.slackLength; softDropMultiplier = ClassicModeActivity.softDropMultiplier; setOnTouchListener(new OnTouchListener() { float x; float y; float prevY; boolean turn; boolean hardDropped; float startingX; float startingY; @Override public boolean onTouch(View arg0, MotionEvent arg1) { if (!pause & !lose) { switch (arg1.getAction()) { case MotionEvent.ACTION_DOWN: x = arg1.getX(); y = arg1.getY(); startingX = x; startingY = y; prevY = y; turn = true; hardDropped = false; return true; case MotionEvent.ACTION_MOVE: x = arg1.getX(); y = arg1.getY(); float dy = y - prevY; if (dy > flickSensitivity & !hardDropped) { hardDrop = true; slack = false; gravity = 20.0; turn = false; hardDropped = true; } else if (dy < -flickSensitivity) { if (!holdOnce) { holdShape(); } turn = false; } else if (x - startingX > squareSide) { startingX = x; moveRight(); turn = false; } else if (x - startingX < -squareSide) { startingX = x; moveLeft(); turn = false; } else if (y - startingY > squareSide & !hardDropped) { gravity = defaultGravity * softDropMultiplier; softDrop = true; turn = false; } prevY = y; coloring(); return true; case MotionEvent.ACTION_UP: x = arg1.getX(); y = arg1.getY(); if (turn) { if (x < squareSide * numberOfBlocksWidth * 0.5) { shapeTurnCC(); } else { shapeTurn(); } } if (softDrop) { gravity = defaultGravity; softDrop = false; } coloring(); return true; } } return false; } }); newGame(); } @Override public void onDraw(Canvas canvas) { if (!getScreenSize) { int width = this.getMeasuredWidth(); int height = this.getMeasuredHeight(); System.out.println(width + " " + height); squareSide = (int) Math.min(width / numSquaresX, height / numSquaresY); holdShapeXStarting = squareSide * (numberOfBlocksWidth + 1); nextShapeYStarting = squareSide * 5; nextShapeY2Starting = squareSide * 8; nextShapeY3Starting = squareSide * 11; scoreInfoYStarting = squareSide * 3; mainFieldShiftX = squareSide; mainFieldShiftY = squareSide; getScreenSize = true; paint.setTextSize((float) (squareSide * textScaleSize)); } paint.setColor(Color.BLACK); canvas.drawText("Score: " + score, holdShapeXStarting + mainFieldShiftX - squareSide, scoreInfoYStarting + mainFieldShiftY, paint); // Gravity falling mechanic. // totalGrav is incremented by gravity every tick. // when totalGrav is higher than 1, the shape moves down 1 block. if (!lose & !pause) { if (thisShape >= 0) { long temp = System.currentTimeMillis(); long dtime = temp - clock; if (dtime > FPS) { totalGrav = totalGrav + gravity; clock = clock + FPS; } while (totalGrav >= 1) { shapeDown(); totalGrav = totalGrav - 1; } } } coloring(); ghostShape(); for (int xx = mainFieldShiftX; xx <= squareSide * numberOfBlocksWidth + mainFieldShiftX; xx += squareSide) canvas.drawLine(xx, mainFieldShiftY, xx, squareSide * (numberOfBlocksLength - 2) + mainFieldShiftY, paint); for (int xx = mainFieldShiftY; xx <= squareSide * (numberOfBlocksLength - 2) + mainFieldShiftY; xx += squareSide) canvas.drawLine(mainFieldShiftX, xx, squareSide * numberOfBlocksWidth + mainFieldShiftX, xx, paint); for (int x = 0; x < 8; x++) { // Setting the color of the blocks if (x == 0) paint.setColor(Color.CYAN); else if (x == 1) paint.setColor(Color.BLUE); else if (x == 2) paint.setColor(Color.DKGRAY); else if (x == 3) paint.setColor(Color.MAGENTA); else if (x == 4) paint.setColor(Color.GREEN); else if (x == 5) paint.setColor(Color.RED); else if (x == 6) paint.setColor(Color.YELLOW); else if (x == 7) paint.setColor(Color.GRAY); for (int xx = 0; xx < numberOfBlocksWidth; xx++) for (int yy = 2; yy < numberOfBlocksLength; yy++) if (blocks[xx][yy] != 0 & blocks[xx][yy] != 3 & colors[xx][yy] == x) { canvas.drawRect(xx * squareSide + mainFieldShiftX, (yy - 2) * squareSide + mainFieldShiftY, xx * squareSide + squareSide + mainFieldShiftX, (yy - 2) * squareSide + squareSide + mainFieldShiftY, paint); } for (int xx = 0; xx < numberOfBlocksWidth; xx++) for (int yy = 0; yy < numberOfBlocksLength; yy++) if (blocks[xx][yy] == 3 & lastShape == x) canvas.drawCircle((float) (xx * squareSide + squareSide * 0.5 + mainFieldShiftX), (float) ((yy - 2) * squareSide + squareSide * 0.5 + mainFieldShiftY), (float) (squareSide * 0.5), paint); for (int xx = 0; xx < numberOfHoldShapeWidth; xx++) for (int yy = 0; yy < numberOfHoldShapeLength; yy++) if (holdBlocks[xx][yy] == 1 & holdShape == x) canvas.drawRect(xx * squareSide + holdShapeXStarting + mainFieldShiftX, yy * squareSide + mainFieldShiftY, xx * squareSide + holdShapeXStarting + squareSide + mainFieldShiftX, yy * squareSide + squareSide + mainFieldShiftY, paint); for (int xx = 0; xx < numberOfHoldShapeWidth; xx++) for (int yy = 0; yy < numberOfHoldShapeLength; yy++) if (nextBlocks[xx][yy] == 1 & thisShape == x) canvas.drawRect(xx * squareSide + holdShapeXStarting + mainFieldShiftX, yy * squareSide + nextShapeYStarting + mainFieldShiftY, xx * squareSide + holdShapeXStarting + squareSide + mainFieldShiftX, yy * squareSide + nextShapeYStarting + squareSide + mainFieldShiftY, paint); for (int xx = 0; xx < numberOfHoldShapeWidth; xx++) for (int yy = 0; yy < numberOfHoldShapeLength; yy++) if (next2Blocks[xx][yy] == 1 & nextShape == x) canvas.drawRect(xx * squareSide + holdShapeXStarting + mainFieldShiftX, yy * squareSide + nextShapeY2Starting + mainFieldShiftY, xx * squareSide + holdShapeXStarting + squareSide + mainFieldShiftX, yy * squareSide + nextShapeY2Starting + squareSide + mainFieldShiftY, paint); for (int xx = 0; xx < numberOfHoldShapeWidth; xx++) for (int yy = 0; yy < numberOfHoldShapeLength; yy++) if (next3Blocks[xx][yy] == 1 & nextShape1 == x) canvas.drawRect(xx * squareSide + holdShapeXStarting + mainFieldShiftX, yy * squareSide + nextShapeY3Starting + mainFieldShiftY, xx * squareSide + holdShapeXStarting + squareSide + mainFieldShiftX, yy * squareSide + nextShapeY3Starting + squareSide + mainFieldShiftY, paint); } invalidate(); } public static void detectShape() { int counter = 0; for (int yy = numberOfBlocksLength - 1; yy >= 0; yy for (int xx = numberOfBlocksWidth - 1; xx >= 0; xx if (blocks[xx][yy] == 1) { playLocationX[counter] = xx; playLocationY[counter] = yy; counter++; } } } } // Generates new minos. // Follows the 7-bag system, which means that there will be ALL the blocks.. // ...found in each "bag" of 7 pieces. // thisShape = -1 means that it is a new game // Affects: // lastShape == The CURRENT shape on the playing field. // thisShape == The NEXT shape on the playing field. // nextShape == The NEXT2 shape on the playing field. // nextShape1 == The NEXT3 shape on the playing field. public static void pickShape() { if (thisShape == -1) { thisShape = shapeList.remove(r.nextInt(shapeList.size())); nextShape = shapeList.remove(r.nextInt(shapeList.size())); nextShape1 = shapeList.remove(r.nextInt(shapeList.size())); } if (thisShape == 0) { for (int xx = 3; xx <= 6; xx++) blocks[xx][0] = 1; shape = 1; } else if (thisShape == 1) { for (int xx = 3; xx <= 5; xx++) blocks[xx][1] = 1; blocks[3][0] = 1; shape = 5; } else if (thisShape == 2) { for (int xx = 3; xx <= 5; xx++) blocks[xx][1] = 1; blocks[5][0] = 1; shape = 9; } else if (thisShape == 3) { for (int xx = 3; xx <= 5; xx++) blocks[xx][1] = 1; blocks[4][0] = 1; shape = 13; } else if (thisShape == 4) { blocks[4][0] = 1; blocks[5][0] = 1; blocks[3][1] = 1; blocks[4][1] = 1; shape = 15; } else if (thisShape == 5) { blocks[3][0] = 1; blocks[4][0] = 1; blocks[4][1] = 1; blocks[5][1] = 1; shape = 17; } else if (thisShape == 6) { blocks[4][0] = 1; blocks[5][0] = 1; blocks[4][1] = 1; blocks[5][1] = 1; shape = 19; } lastShape = thisShape; thisShape = nextShape; nextShape = nextShape1; nextShape1 = shapeList.remove(r.nextInt(shapeList.size())); if (shapeList.size() <= 0) { for (int xx = 0; xx < 7; xx++) { shapeList.add(xx); } } displayBoxShape(nextBlocks, thisShape); displayBoxShape(next2Blocks, nextShape); displayBoxShape(next3Blocks, nextShape1); detectShape(); holdOnce = false; } public static void holdShape() { if (holdShape == -1) { holdShape = lastShape; for (int xx = 0; xx < numberOfBlocksWidth; xx++) for (int yy = 0; yy < numberOfBlocksLength; yy++) if (blocks[xx][yy] == 1) blocks[xx][yy] = 0; pickShape(); } else { int lastShape1 = holdShape; holdShape = lastShape; lastShape = lastShape1; for (int xx = 0; xx < numberOfBlocksWidth; xx++) for (int yy = 0; yy < numberOfBlocksLength; yy++) if (blocks[xx][yy] == 1) blocks[xx][yy] = 0; if (lastShape == 0) { for (int xx = 3; xx <= 6; xx++) blocks[xx][0] = 1; shape = 1; } else if (lastShape == 1) { for (int xx = 3; xx <= 5; xx++) blocks[xx][0] = 1; blocks[5][1] = 1; shape = 3; } else if (lastShape == 2) { for (int xx = 3; xx <= 5; xx++) blocks[xx][0] = 1; blocks[3][1] = 1; shape = 7; } else if (lastShape == 3) { for (int xx = 3; xx <= 5; xx++) blocks[xx][0] = 1; blocks[4][1] = 1; shape = 11; } else if (lastShape == 4) { blocks[4][0] = 1; blocks[5][0] = 1; blocks[3][1] = 1; blocks[4][1] = 1; shape = 15; } else if (lastShape == 5) { blocks[3][0] = 1; blocks[4][0] = 1; blocks[4][1] = 1; blocks[5][1] = 1; shape = 17; } else if (lastShape == 6) { blocks[3][0] = 1; blocks[4][0] = 1; blocks[3][1] = 1; blocks[4][1] = 1; shape = 19; } } holdOnce = true; displayBoxShape(holdBlocks, holdShape); } public static void shapeDown() { if (!lose & !pause) { boolean move = true; detectShape(); coloring(); // Detection of whether the block can still fall down. if (true) { for (int xx = 0; xx < playLocationY.length; xx++) if (playLocationY[xx] + 1 >= numberOfBlocksLength) move = false; if (move == true) for (int xx = 0; xx < playLocationY.length; xx++) if (blocks[playLocationX[xx]][playLocationY[xx] + 1] == 2) move = false; } // Detection Ends // Slack Procedure if (!move && !hardDrop && !slackOnce) { slackOnce = true; slack = true; time.schedule(new Slack(), slackLength); } // Slack Procedure Ends. if (!move && !slack) { int currentDrop = 0; // The number of lines cleared // T-spin Recognition boolean moveUp = true; boolean moveLeft = true; boolean moveRight = true; boolean tSpin = false; for (int xx = 0; xx < playLocationY.length; xx++) { try { if (blocks[playLocationX[xx] - 1][playLocationY[xx]] == 2) { moveLeft = false; } } catch (Exception e) { moveLeft = false; } try { if (blocks[playLocationX[xx] + 1][playLocationY[xx]] == 2) { moveRight = false; } } catch (Exception e) { moveRight = false; } try { if (blocks[playLocationX[xx]][playLocationY[xx] - 1] == 2) { moveUp = false; } } catch (Exception e) { moveUp = false; } } if (!moveLeft & !moveRight & !moveUp) { tSpin = true; } // T-spin recognition end. for (int xx = 0; xx < playLocationY.length; xx++) blocks[playLocationX[xx]][playLocationY[xx]] = 2; for (int yy = numberOfBlocksLength - 1; yy > 0; yy boolean line = true; do { for (int xx = 0; xx < numberOfBlocksWidth; xx++) { if (blocks[xx][yy] == 0) { line = false; break; } } if (line) { for (int xx = 0; xx < numberOfBlocksWidth; xx++) { blocks[xx][yy] = 0; } for (int xy = yy; xy > 0; xy for (int xx = 0; xx < numberOfBlocksWidth; xx++) { blocks[xx][xy] = blocks[xx][xy - 1]; colors[xx][xy] = colors[xx][xy - 1]; } } for (int xx = 0; xx < numberOfBlocksWidth; xx++) { blocks[xx][0] = 0; } currentDrop++; } } while (line); } hardDrop = false; totalGrav = 0.0; gravity = defaultGravity; // Scoring System int addScore = 0; if (currentDrop == 1 & tSpin & !kick) { addScore = 800; difficult = true; } else if (currentDrop == 1 & tSpin & kick) { addScore = 200; difficult = true; } else if (currentDrop == 2 & tSpin) { addScore = 1200; difficult = true; } else if (currentDrop == 3 & tSpin) { addScore = 1600; difficult = true; } else if (currentDrop == 0 & tSpin & kick) { addScore = 100; } else if (currentDrop == 0 & tSpin) { addScore = 400; } else if (currentDrop == 1) { addScore = 100; } else if (currentDrop == 2) { addScore = 300; } else if (currentDrop == 3) { addScore = 500; } else if (currentDrop == 4) { addScore = 800; difficult = true; } if (lastDifficult & difficult) { addScore = (int) (addScore * 1.5); } addScore = addScore + 50 * combo; if (currentDrop != 0) { combo = combo + 1; } else { combo = 0; } score = score + addScore; // Scoring System end. pickShape(); } else if (move) { // If slack is still activated if (slack) { time.cancel(); time = new Timer(); } slackOnce = false; for (int xx = 0; xx < playLocationX.length; xx++) { blocks[playLocationX[xx]][playLocationY[xx]] = 0; blocks[playLocationX[xx]][playLocationY[xx] + 1] = 1; } } if (move && !slack) { if (hardDrop) { score = score + 2; } else if (softDrop) { score = score + 1; } } lose = false; for (int xx = 0; xx < numberOfBlocksWidth; xx++) { if (blocks[xx][2] == 2) { lose = true; // TODO set lose message break; } } } } public static void ghostShape() { boolean move = true; detectShape(); int[] tempPlayLocationX = new int[4]; int[] tempPlayLocationY = new int[4]; for (int xx = 0; xx < numberOfBlocksWidth; xx++) for (int yy = 0; yy < numberOfBlocksLength; yy++) if (blocks[xx][yy] == 3) blocks[xx][yy] = 0; for (int xx = 0; xx < playLocationY.length; xx++) { tempPlayLocationX[xx] = playLocationX[xx]; tempPlayLocationY[xx] = playLocationY[xx]; } do { for (int xx = 0; xx < playLocationY.length; xx++) if (tempPlayLocationY[xx] + 1 >= numberOfBlocksLength) move = false; if (move) for (int xx = 0; xx < playLocationY.length; xx++) if (blocks[tempPlayLocationX[xx]][tempPlayLocationY[xx] + 1] == 2) move = false; if (!move) { for (int xx = 0; xx < playLocationY.length; xx++) if (blocks[tempPlayLocationX[xx]][tempPlayLocationY[xx]] != 1 & blocks[tempPlayLocationX[xx]][tempPlayLocationY[xx]] != 2) blocks[tempPlayLocationX[xx]][tempPlayLocationY[xx]] = 3; } else for (int xx = 0; xx < playLocationY.length; xx++) tempPlayLocationY[xx] = tempPlayLocationY[xx] + 1; } while (move); } public static void moveLeft() { boolean move = true; detectShape(); for (int xx = 0; xx < playLocationY.length; xx++) if (playLocationX[xx] - 1 < 0) move = false; if (move) for (int xx = 0; xx < playLocationY.length; xx++) if (blocks[playLocationX[xx] - 1][playLocationY[xx]] == 2) move = false; if (move) { for (int xx = 0; xx < playLocationY.length; xx++) blocks[playLocationX[xx]][playLocationY[xx]] = 0; for (int xx = 0; xx < playLocationY.length; xx++) blocks[playLocationX[xx] - 1][playLocationY[xx]] = 1; } } public static void moveRight() { boolean move = true; detectShape(); for (int xx = 0; xx < playLocationY.length; xx++) if (playLocationX[xx] + 1 >= numberOfBlocksWidth) move = false; if (move) for (int xx = 0; xx < playLocationY.length; xx++) if (blocks[playLocationX[xx] + 1][playLocationY[xx]] == 2) move = false; if (move) { for (int xx = 0; xx < playLocationY.length; xx++) blocks[playLocationX[xx]][playLocationY[xx]] = 0; for (int xx = 0; xx < playLocationY.length; xx++) blocks[playLocationX[xx] + 1][playLocationY[xx]] = 1; } } public static void shapeTurn() { turnSuccess = false; detectShape(); if (shape == 1) { turnShape(-2, -1, 0, 1, 2, 1, 0, -1); if (turnSuccess) shape = 2; } else if (shape == 2) { turnShape(-2, -1, 0, 1, -2, -1, 0, 1); if (turnSuccess) shape = 1; } else if (shape == 3) { turnShape(-2, -1, 0, 1, 0, 1, 0, -1); if (turnSuccess) shape = 4; } else if (shape == 4) { turnShape(-1, 0, 0, 1, -1, -2, 0, 1); if (turnSuccess) shape = 5; } else if (shape == 5) { turnShape(-1, 0, 1, 2, 1, 0, -1, 0); if (turnSuccess) shape = 6; } else if (shape == 6) { turnShape(-1, 0, 0, 1, -1, 0, 2, 1); if (turnSuccess) shape = 3; } else if (shape == 7) { turnShape(0, -1, 0, 1, -2, 1, 0, -1); if (turnSuccess) shape = 8; } else if (shape == 8) { turnShape(-1, 0, 1, 2, -1, 0, 1, 0); if (turnSuccess) shape = 9; } else if (shape == 9) { turnShape(-1, 0, 1, 0, 1, 0, -1, 2); if (turnSuccess) shape = 10; } else if (shape == 10) { turnShape(-2, -1, 0, 1, 0, -1, 0, 1); if (turnSuccess) shape = 7; } else if (shape == 11) { turnShape(0, -1, 0, 0, 0, -1, 0, 0); if (turnSuccess) shape = 12; } else if (shape == 12) { turnShape(1, 0, 0, 0, -1, 0, 0, 0); if (turnSuccess) shape = 13; } else if (shape == 13) { turnShape(0, 0, 1, 0, 0, 0, 1, 0); if (turnSuccess) shape = 14; } else if (shape == 14) { turnShape(0, 0, 0, -1, 0, 0, 0, 1); if (turnSuccess) shape = 11; } else if (shape == 15) { turnShape(0, 0, -2, 0, 0, -1, -1, 0); if (turnSuccess) shape = 16; } else if (shape == 16) { turnShape(0, 0, 0, 2, 0, 0, 1, 1); if (turnSuccess) shape = 15; } else if (shape == 17) { turnShape(-1, -1, 0, 0, -2, 0, 0, 0); if (turnSuccess) shape = 18; } else if (shape == 18) { turnShape(1, 0, 0, 1, 0, 0, 0, 2); if (turnSuccess) shape = 17; } // Reset slack if turn is successful if (turnSuccess) { slackOnce = false; time.cancel(); time = new Timer(); } } public static void shapeTurnCC() { turnSuccess = false; detectShape(); if (shape == 1) { turnShape(-2, -1, 0, 1, 2, 1, 0, -1); if (turnSuccess) shape = 2; } else if (shape == 2) { turnShape(-2, -1, 0, 1, -2, -1, 0, 1); if (turnSuccess) shape = 1; } else if (shape == 3) { turnShape(0, -1, 0, 1, -2, -1, 0, 1); if (turnSuccess) shape = 6; } else if (shape == 4) { turnShape(1, 2, 0, -1, -1, 0, 0, 1); if (turnSuccess) shape = 3; } else if (shape == 5) { turnShape(-1, 0, 1, 0, -1, 0, 1, 2); if (turnSuccess) shape = 4; } else if (shape == 6) { turnShape(1, 0, -2, -1, -1, 0, 1, 0); if (turnSuccess) shape = 5; } else if (shape == 7) { turnShape(2, -1, 0, 1, 0, -1, 0, 1); if (turnSuccess) shape = 10; } else if (shape == 8) { turnShape(1, 0, -1, 0, -1, 0, 1, 2); if (turnSuccess) shape = 7; } else if (shape == 9) { turnShape(-1, 0, 1, -2, -1, 0, 1, 0); if (turnSuccess) shape = 8; } else if (shape == 10) { turnShape(0, 1, 0, -1, -2, -1, 0, 1); if (turnSuccess) shape = 9; } else if (shape == 11) { turnShape(0, 0, 0, 1, 0, 0, 0, -1); if (turnSuccess) shape = 14; } else if (shape == 12) { turnShape(0, 0, 0, 1, 0, 0, 0, 1); if (turnSuccess) shape = 11; } else if (shape == 13) { turnShape(-1, 0, 0, 0, 1, 0, 0, 0); if (turnSuccess) shape = 12; } else if (shape == 14) { turnShape(-1, 0, 0, 0, -1, 0, 0, 0); if (turnSuccess) shape = 13; } else if (shape == 15) { turnShape(0, 0, -2, 0, 0, -1, -1, 0); if (turnSuccess) shape = 16; } else if (shape == 16) { turnShape(0, 0, 0, 2, 0, 0, 1, 1); if (turnSuccess) shape = 15; } else if (shape == 17) { turnShape(-1, -1, 0, 0, -2, 0, 0, 0); if (turnSuccess) shape = 18; } else if (shape == 18) { turnShape(1, 0, 0, 1, 0, 0, 0, 2); if (turnSuccess) shape = 17; } // Reset slack if turn is successful if (turnSuccess) { slackOnce = false; time.cancel(); time = new Timer(); } } public static void turnShape(int x1, int x2, int x3, int x4, int y1, int y2, int y3, int y4) { kick = false; int[] x = new int[4]; int[] y = new int[4]; x[0] = x1; x[1] = x2; x[2] = x3; x[3] = x4; y[0] = y1; y[1] = y2; y[2] = y3; y[3] = y4; for (int yy = 0; yy <= 2; yy++) { if (yy == 1) yy = -1; else if (yy != 0) yy = yy - 1; for (int xy = 0; xy <= 3; xy++) { if (xy == 1) xy = -1; else if (xy != 0) xy = xy - 1; boolean ok = true; for (int xx = 0; xx < playLocationX.length; xx++) { if (playLocationX[xx] + x[xx] + xy > numberOfBlocksWidth - 1 | playLocationX[xx] + x[xx] + xy < 0) { ok = false; } } for (int xx = 0; xx < playLocationY.length; xx++) { if (playLocationY[xx] + y[xx] - yy >= 22 | playLocationY[xx] + y[xx] - yy < 0) { ok = false; } } try { if (ok) { if (blocks[playLocationX[0] + x[0] + xy][playLocationY[0] + y[0] - yy] != 2 & blocks[playLocationX[1] + x[1] + xy][playLocationY[1] + y[1] - yy] != 2 & blocks[playLocationX[2] + x[2] + xy][playLocationY[2] + y[2] - yy] != 2 & blocks[playLocationX[3] + x[3] + xy][playLocationY[3] + y[3] - yy] != 2) { for (int xx = 0; xx < playLocationY.length; xx++) blocks[playLocationX[xx]][playLocationY[xx]] = 0; for (int xx = 0; xx < playLocationY.length; xx++) blocks[playLocationX[xx] + x[xx] + xy][playLocationY[xx] + y[xx] - yy] = 1; turnSuccess = true; } } } catch (Exception e) { e.printStackTrace(); } if (xy == -1) xy = 1; else if (xy != 0) xy = xy + 1; if (turnSuccess) { if (xy != 0) { kick = true; } break; } } if (yy == -1) yy = 1; else if (yy != 0) yy = yy + 1; if (turnSuccess) { if (yy != 0) { kick = true; } break; } } } public static void coloring() { detectShape(); for (int xx = 0; xx < MainGame.playLocationX.length; xx++) MainGame.colors[MainGame.playLocationX[xx]][MainGame.playLocationY[xx]] = MainGame.lastShape; } public static void displayBoxShape(int[][] x, int y) { for (int xx = 0; xx < numberOfHoldShapeWidth; xx++) for (int yy = 0; yy < numberOfHoldShapeLength; yy++) x[xx][yy] = 0; if (y == 0) { for (int xx = 0; xx <= 3; xx++) x[xx][0] = 1; } else if (y == 1) { for (int xx = 0; xx <= 2; xx++) x[xx][1] = 1; x[0][0] = 1; } else if (y == 2) { for (int xx = 0; xx <= 2; xx++) x[xx][1] = 1; x[2][0] = 1; } else if (y == 3) { for (int xx = 0; xx <= 2; xx++) x[xx][1] = 1; x[1][0] = 1; } else if (y == 4) { x[1][0] = 1; x[2][0] = 1; x[0][1] = 1; x[1][1] = 1; } else if (y == 5) { x[0][0] = 1; x[1][0] = 1; x[1][1] = 1; x[2][1] = 1; } else if (y == 6) { x[0][0] = 1; x[1][0] = 1; x[0][1] = 1; x[1][1] = 1; } } public static void newGame() { for (int xx = 0; xx < numberOfBlocksWidth; xx++) { for (int yy = 0; yy < numberOfBlocksLength; yy++) { blocks[xx][yy] = 0; colors[xx][yy] = 0; if (xx < numberOfHoldShapeWidth & yy < numberOfHoldShapeLength) { holdBlocks[xx][yy] = 0; nextBlocks[xx][yy] = 0; next2Blocks[xx][yy] = 0; next3Blocks[xx][yy] = 0; } } } pause = false; blocks = new int[numberOfBlocksWidth][numberOfBlocksLength]; colors = new int[numberOfBlocksWidth][numberOfBlocksLength]; holdBlocks = new int[numberOfHoldShapeWidth][numberOfHoldShapeLength]; nextBlocks = new int[numberOfHoldShapeWidth][numberOfHoldShapeLength]; next2Blocks = new int[numberOfHoldShapeWidth][numberOfHoldShapeLength]; next3Blocks = new int[numberOfHoldShapeWidth][numberOfHoldShapeLength]; playLocationX = new int[4]; playLocationY = new int[4]; thisShape = -1; nextShape = -1; nextShape1 = -1; holdShape = -1; shape = -1; lastShape = -1; for (int xx = 0; xx < 7; xx++) { shapeList.add(xx); } score = 0; lose = false; getScreenSize = false; time.cancel(); time = new Timer(); pickShape(); } }
package org.biojava.bio.structure.io.mmcif; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import org.biojava.bio.structure.AminoAcid; import org.biojava.bio.structure.AminoAcidImpl; import org.biojava.bio.structure.Atom; import org.biojava.bio.structure.AtomImpl; import org.biojava.bio.structure.Chain; import org.biojava.bio.structure.ChainImpl; import org.biojava.bio.structure.DBRef; import org.biojava.bio.structure.Group; import org.biojava.bio.structure.HetatomImpl; import org.biojava.bio.structure.NucleotideImpl; import org.biojava.bio.structure.PDBHeader; import org.biojava.bio.structure.ResidueNumber; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.StructureImpl; import org.biojava.bio.structure.StructureTools; import org.biojava.bio.structure.UnknownPdbAminoAcidException; import org.biojava.bio.structure.io.FileParsingParameters; import org.biojava.bio.structure.io.PDBParseException; import org.biojava.bio.structure.io.SeqRes2AtomAligner; import org.biojava.bio.structure.io.mmcif.model.AtomSite; import org.biojava.bio.structure.io.mmcif.model.AuditAuthor; import org.biojava.bio.structure.io.mmcif.model.ChemComp; import org.biojava.bio.structure.io.mmcif.model.DatabasePDBremark; import org.biojava.bio.structure.io.mmcif.model.DatabasePDBrev; import org.biojava.bio.structure.io.mmcif.model.Entity; import org.biojava.bio.structure.io.mmcif.model.EntityPolySeq; import org.biojava.bio.structure.io.mmcif.model.Exptl; import org.biojava.bio.structure.io.mmcif.model.PdbxEntityNonPoly; import org.biojava.bio.structure.io.mmcif.model.PdbxNonPolyScheme; import org.biojava.bio.structure.io.mmcif.model.PdbxPolySeqScheme; import org.biojava.bio.structure.io.mmcif.model.Refine; import org.biojava.bio.structure.io.mmcif.model.Struct; import org.biojava.bio.structure.io.mmcif.model.StructAsym; import org.biojava.bio.structure.io.mmcif.model.StructKeywords; import org.biojava.bio.structure.io.mmcif.model.StructRef; import org.biojava.bio.structure.io.mmcif.model.StructRefSeq; /** A MMcifConsumer implementation that build a in-memory representation of the * content of a mmcif file as a BioJava Structure object. * @author Andreas Prlic * @since 1.7 */ public class SimpleMMcifConsumer implements MMcifConsumer { boolean DEBUG = false; Structure structure; Chain current_chain; Group current_group; int atomCount; List<Chain> current_model; List<Entity> entities; List<StructRef> strucRefs; List<Chain> seqResChains; List<Chain> entityChains; // needed to link entities, chains and compounds... List<StructAsym> structAsyms; // needed to link entities, chains and compounds... Map<String,String> asymStrandId; String current_nmr_model ; FileParsingParameters params; public static Logger logger = Logger.getLogger("org.biojava.bio.structure"); public SimpleMMcifConsumer(){ params = new FileParsingParameters(); documentStart(); } public void newEntity(Entity entity) { if (DEBUG) System.out.println(entity); entities.add(entity); } public void newStructAsym(StructAsym sasym){ structAsyms.add(sasym); } private Entity getEntity(String entity_id){ for (Entity e: entities){ if (e.getId().equals(entity_id)){ return e; } } return null; } public void newStructKeywords(StructKeywords kw){ PDBHeader header = structure.getPDBHeader(); if ( header == null) header = new PDBHeader(); header.setDescription(kw.getPdbx_keywords()); header.setClassification(kw.getPdbx_keywords()); Map<String, Object> h = structure.getHeader(); h.put("classification", kw.getPdbx_keywords()); } public void setStruct(Struct struct) { //System.out.println(struct); PDBHeader header = structure.getPDBHeader(); if ( header == null) header = new PDBHeader(); header.setTitle(struct.getTitle()); header.setIdCode(struct.getEntry_id()); //header.setDescription(struct.getPdbx_descriptor()); //header.setClassification(struct.getPdbx_descriptor()); //header.setDescription(struct.getPdbx_descriptor()); //System.out.println(struct.getPdbx_model_details()); Map<String, Object> h = structure.getHeader(); h.put("title", struct.getTitle()); //h.put("classification", struct.getPdbx_descriptor()); structure.setPDBHeader(header); structure.setPDBCode(struct.getEntry_id()); } /** initiate new group, either Hetatom, Nucleotide, or AminoAcid */ private Group getNewGroup(String recordName,Character aminoCode1, long seq_id,String groupCode3) { if ( params.isLoadChemCompInfo() ){ Group g = ChemCompGroupFactory.getGroupFromChemCompDictionary(groupCode3); if ( g != null) { if ( g instanceof AminoAcidImpl) { AminoAcidImpl aa = (AminoAcidImpl) g; aa.setId(seq_id); } else if ( g instanceof NucleotideImpl) { NucleotideImpl nuc = (NucleotideImpl) g; nuc.setId(seq_id); } else if ( g instanceof HetatomImpl) { HetatomImpl het = (HetatomImpl)g; het.setId(seq_id); } return g; } } Group group; if ( recordName.equals("ATOM") ) { if (aminoCode1 == null) { // it is a nucleotide NucleotideImpl nu = new NucleotideImpl(); group = nu; nu.setId(seq_id); } else if (aminoCode1 == StructureTools.UNKNOWN_GROUP_LABEL){ HetatomImpl h = new HetatomImpl(); h.setId(seq_id); group = h; } else { AminoAcidImpl aa = new AminoAcidImpl() ; aa.setAminoType(aminoCode1); aa.setId(seq_id); group = aa ; } } else { HetatomImpl h = new HetatomImpl(); h.setId(seq_id); group = h; } //System.out.println("new group type: "+ group.getType() ); return group ; } /** test if the chain is already known (is in current_model * ArrayList) and if yes, returns the chain * if no -> returns null */ private Chain isKnownChain(String chainID, List<Chain> chains){ for (int i = 0; i< chains.size();i++){ Chain testchain = chains.get(i); //System.out.println("comparing chainID >"+chainID+"< against testchain " + i+" >" +testchain.getName()+"<"); if (chainID.equals(testchain.getChainID())) { //System.out.println("chain "+ chainID+" already known ..."); return testchain; } } return null; } /** during mmcif parsing the full atom name string gets truncated, fix this... * * @param name * @return */ private String fixFullAtomName(String name){ if (name.equals("N")){ return " N "; } if (name.equals("CA")){ return " CA "; } if (name.equals("C")){ return " C "; } if (name.equals("O")){ return " O "; } if (name.equals("CB")){ return " CB "; } if (name.equals("CG")) return " CG "; if (name.length() == 2) return " " + name + " "; if (name.length() == 1) return " " + name + " "; if (name.length() == 3) return " " + name ; return name; } public void newAtomSite(AtomSite atom) { // Warning: getLabel_asym_id is not the "chain id" in the PDB file // it is the internally used chain id. // later on we will fix this... // later one needs to map the asym id to the pdb_strand_id //TODO: add support for MAX_ATOMS boolean startOfNewChain = false; //String chain_id = atom.getAuth_asym_id(); String chain_id = atom.getLabel_asym_id(); String fullname = fixFullAtomName(atom.getLabel_atom_id()); String recordName = atom.getGroup_PDB(); String residueNumberS = atom.getAuth_seq_id(); Integer residueNrInt = Integer.parseInt(residueNumberS); // the 3-letter name of the group: String groupCode3 = atom.getLabel_comp_id(); Character aminoCode1 = null; if ( recordName.equals("ATOM") ) aminoCode1 = StructureTools.get1LetterCode(groupCode3); else { aminoCode1 = StructureTools.get1LetterCode(groupCode3); if ( aminoCode1.equals(StructureTools.UNKNOWN_GROUP_LABEL)) aminoCode1 = null; } String insCodeS = atom.getPdbx_PDB_ins_code(); Character insCode = null; if (! insCodeS.equals("?")) { insCode = insCodeS.charAt(0); } // we store the internal seq id in the Atom._id field // this is not a PDB file field but we need this to internally assign the insertion codes later // from the pdbx_poly_seq entries.. long seq_id = -1; try { seq_id = Long.parseLong(atom.getLabel_seq_id()); } catch (NumberFormatException e){ } String nmrModel = atom.getPdbx_PDB_model_num(); if ( current_nmr_model == null) { current_nmr_model = nmrModel; } if (! current_nmr_model.equals(nmrModel)){ current_nmr_model = nmrModel; // add previous data if ( current_chain != null ) { current_chain.addGroup(current_group); } // we came to the beginning of a new NMR model structure.setNmr(true); structure.addModel(current_model); current_model = new ArrayList<Chain>(); current_chain = null; current_group = null; } if (current_chain == null) { current_chain = new ChainImpl(); current_chain.setChainID(chain_id); current_model.add(current_chain); startOfNewChain = true; } //System.out.println("BEFORE: " + chain_id + " " + current_chain.getName()); if ( ! chain_id.equals(current_chain.getChainID()) ) { startOfNewChain = true; // end up old chain... current_chain.addGroup(current_group); // see if old chain is known ... Chain testchain ; testchain = isKnownChain(current_chain.getChainID(),current_model); //System.out.println("trying to re-using known chain " + current_chain.getName() + " " + chain_id); if ( testchain != null && testchain.getChainID().equals(chain_id)){ //System.out.println("re-using known chain " + current_chain.getName() + " " + chain_id); } else { testchain = isKnownChain(chain_id,current_model); } if ( testchain == null) { //System.out.println("unknown chain. creating new chain."); current_chain = new ChainImpl(); current_chain.setChainID(chain_id); } else { current_chain = testchain; } if ( ! current_model.contains(current_chain)) current_model.add(current_chain); } ResidueNumber residueNumber = new ResidueNumber(chain_id,residueNrInt, insCode); if (current_group == null) { current_group = getNewGroup(recordName,aminoCode1,seq_id, groupCode3); //current_group.setPDBCode(residueNumber); current_group.setResidueNumber(residueNumber); try { current_group.setPDBName(groupCode3); } catch (PDBParseException e){ System.err.println(e.getMessage()); } } if ( startOfNewChain){ current_group = getNewGroup(recordName,aminoCode1,seq_id, groupCode3); // current_group.setPDBCode(residueNumber); current_group.setResidueNumber(residueNumber); try { current_group.setPDBName(groupCode3); } catch (PDBParseException e){ e.printStackTrace(); } } Group altGroup = null; String altLocS = atom.getLabel_alt_id(); Character altLoc = ' '; if ( altLocS.length()>0) { altLoc = altLocS.charAt(0); if ( altLoc.equals('.') ) altLoc = ' '; } // check if residue number is the same ... // insertion code is part of residue number if ( ! residueNumber.equals(current_group.getResidueNumber())) { //System.out.println("end of residue: "+current_group.getPDBCode()+" "+residueNrInt); current_chain.addGroup(current_group); current_group = getNewGroup(recordName,aminoCode1,seq_id,groupCode3); //current_group.setPDBCode(pdbCode); try { current_group.setPDBName(groupCode3); } catch (PDBParseException e){ e.printStackTrace(); } current_group.setResidueNumber(residueNumber); // System.out.println("Made new group: " + groupCode3 + " " + resNum + " " + iCode); } else { // same residueNumber, but altLocs... // test altLoc if ( ! altLoc.equals(' ') && ( ! altLoc.equals('.'))) { altGroup = getCorrectAltLocGroup( altLoc,recordName,aminoCode1,groupCode3, seq_id); //System.out.println("found altLoc! " + altLoc + " " + current_group + " " + altGroup); } } if ( params.isHeaderOnly()) return; atomCount++; //System.out.println("fixing atom name for >" + atom.getLabel_atom_id() + "< >" + fullname + "<"); if ( params.isParseCAOnly() ){ // yes , user wants to get CA only // only parse CA atoms... if (! fullname.equals(" CA ")){ //System.out.println("ignoring " + line); atomCount return; } } //see if chain_id is one of the previous chains ... Atom a = convertAtom(atom); //see if chain_id is one of the previous chains ... if ( altGroup != null) { altGroup.addAtom(a); altGroup = null; } else { current_group.addAtom(a); } //System.out.println(current_group); } /** convert a MMCif AtomSite object to a BioJava Atom object * * @param atom the mmmcif AtomSite record * @return an Atom */ private Atom convertAtom(AtomSite atom){ Atom a = new AtomImpl(); a.setPDBserial(Integer.parseInt(atom.getId())); a.setName(atom.getLabel_atom_id()); a.setFullName(fixFullAtomName(atom.getLabel_atom_id())); double x = Double.parseDouble (atom.getCartn_x()); double y = Double.parseDouble (atom.getCartn_y()); double z = Double.parseDouble (atom.getCartn_z()); a.setX(x); a.setY(y); a.setZ(z); double occupancy = Double.parseDouble(atom.getOccupancy()); a.setOccupancy(occupancy); double temp = Double.parseDouble(atom.getB_iso_or_equiv()); a.setTempFactor(temp); String alt = atom.getLabel_alt_id(); if (( alt != null ) && ( alt.length() > 0) && (! alt.equals("."))){ a.setAltLoc(new Character(alt.charAt(0))); } else { a.setAltLoc(new Character(' ')); } return a; } private Group getCorrectAltLocGroup( Character altLoc, String recordName, Character aminoCode1, String groupCode3, long seq_id) { // see if we know this altLoc already; List<Atom> atoms = current_group.getAtoms(); if ( atoms.size() > 0) { Atom a1 = atoms.get(0); // we are just adding atoms to the current group // probably there is a second group following later... if (a1.getAltLoc().equals(altLoc)) { return current_group; } } List<Group> altLocs = current_group.getAltLocs(); for ( Group altLocG : altLocs ){ atoms = altLocG.getAtoms(); if ( atoms.size() > 0) { for ( Atom a1 : atoms) { if (a1.getAltLoc().equals( altLoc)) { return altLocG; } } } } // no matching altLoc group found. // build it up. if ( groupCode3.equals(current_group.getPDBName())) { if ( current_group.getAtoms().size() == 0) return current_group; //System.out.println("cloning current group"); Group altLocG = (Group) current_group.clone(); current_group.addAltLoc(altLocG); return altLocG; } Group altLocG = getNewGroup(recordName,aminoCode1,seq_id,groupCode3); try { altLocG.setPDBName(groupCode3); } catch (PDBParseException e) { e.printStackTrace(); } altLocG.setResidueNumber(current_group.getResidueNumber()); current_group.addAltLoc(altLocG); return altLocG; } /** Start the parsing * */ public void documentStart() { structure = new StructureImpl(); current_chain = null; current_group = null; current_nmr_model = null; atomCount = 0; current_model = new ArrayList<Chain>(); entities = new ArrayList<Entity>(); strucRefs = new ArrayList<StructRef>(); seqResChains = new ArrayList<Chain>(); entityChains = new ArrayList<Chain>(); structAsyms = new ArrayList<StructAsym>(); asymStrandId = new HashMap<String, String>(); } public void documentEnd() { // a problem occurred earlier so current_chain = null ... // most likely the buffered reader did not provide data ... if ( current_chain != null ) { current_chain.addGroup(current_group); if (isKnownChain(current_chain.getChainID(),current_model) == null) { current_model.add(current_chain); } } else { if ( DEBUG){ System.err.println("current chain is null at end of document."); } } structure.addModel(current_model); // Goal is to reproduce the PDB files exactly: // What has to be done is to use the auth_mon_id for the assignment. For this // map entities to Chains and Compound objects... for (StructAsym asym : structAsyms) { if ( DEBUG ) System.out.println("entity " + asym.getEntity_id() + " matches asym id:" + asym.getId() ); Chain s = getEntityChain(asym.getEntity_id()); Chain seqres = (Chain)s.clone(); seqres.setChainID(asym.getId()); seqResChains.add(seqres); if ( DEBUG ) System.out.println(" seqres: " + asym.getId() + " " + seqres + "<") ; } if ( params.isAlignSeqRes() ){ SeqRes2AtomAligner aligner = new SeqRes2AtomAligner(); aligner.align(structure,seqResChains); } //TODO: add support for these: //structure.setConnections(connects); //structure.setCompounds(compounds); //linkChains2Compound(structure); // mismatching Author assigned chain IDS and PDB internal chain ids: // fix the chain IDS in the current model: Set<String> asymIds = asymStrandId.keySet(); for (int i =0; i< structure.nrModels() ; i++){ List<Chain>model = structure.getModel(i); List<Chain> pdbChains = new ArrayList<Chain>(); for (Chain chain : model) { for (String asym : asymIds) { if ( chain.getChainID().equals(asym)){ if (DEBUG) System.out.println("renaming " + asym + " to : " + asymStrandId.get(asym)); chain.setChainID(asymStrandId.get(asym)); Chain known = isKnownChain(chain.getChainID(), pdbChains); if ( known == null ){ pdbChains.add(chain); } else { // and now we join the 2 chains together again, because in cif files the data can be split up... for ( Group g : chain.getAtomGroups()){ known.addGroup(g); } } break; } } } structure.setModel(i,pdbChains); } } /** This method will return the parsed protein structure, once the parsing has been finished * * @return a BioJava protein structure object */ public Structure getStructure() { return structure; } public void newDatabasePDBrev(DatabasePDBrev dbrev) { //System.out.println("got a database revision:" + dbrev); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); PDBHeader header = structure.getPDBHeader(); Map<String, Object> h = structure.getHeader(); if ( header == null) { header = new PDBHeader(); } if (dbrev.getNum().equals("1")){ try { String date = dbrev.getDate_original(); //System.out.println(date); Date dep = dateFormat.parse(date); //System.out.println(dep); header.setDepDate(dep); h.put("depDate", date); Date mod = dateFormat.parse(dbrev.getDate()); header.setModDate(mod); h.put("revDate",dbrev.getDate()); } catch (ParseException e){ e.printStackTrace(); } } else { try { Date mod = dateFormat.parse(dbrev.getDate()); header.setModDate(mod); h.put("revDate",dbrev.getDate()); } catch (ParseException e){ e.printStackTrace(); } } structure.setPDBHeader(header); } @SuppressWarnings("deprecation") public void newDatabasePDBremark(DatabasePDBremark remark) { //System.out.println(remark); String id = remark.getId(); if (id.equals("2")){ //this remark field contains the resolution information: String line = remark.getText(); int i = line.indexOf("ANGSTROM"); if ( i > 5) { // line contains ANGSTROM info... String resolution = line.substring(i-5,i).trim(); // convert string to float float res = 99 ; try { res = Float.parseFloat(resolution); } catch (NumberFormatException e) { System.err.println(e.getMessage()); System.err.println("could not parse resolution from line and ignoring it " + line); return ; } // support for old style header Map<String,Object> header = structure.getHeader(); header.put("resolution",new Float(res)); structure.setHeader(header); PDBHeader pdbHeader = structure.getPDBHeader(); pdbHeader.setResolution(res); } } } public void newRefine(Refine r){ // copy the resolution to header PDBHeader pdbHeader = structure.getPDBHeader(); try { pdbHeader.setResolution(Float.parseFloat(r.getLs_d_res_high())); } catch (NumberFormatException e){ logger.warning("could not parse resolution from " + r.getLs_d_res_high() + " " + e.getMessage()); } Map<String,Object> header = structure.getHeader(); header.put("resolution",pdbHeader.getResolution()); } public void newAuditAuthor(AuditAuthor aa){ String name = aa.getName(); StringBuffer famName = new StringBuffer(); StringBuffer initials = new StringBuffer(); boolean afterComma = false; for ( char c: name.toCharArray()) { if ( c == ' ') continue; if ( c == ','){ afterComma = true; continue; } if ( afterComma) initials.append(c); else famName.append(c); } StringBuffer newaa = new StringBuffer(); newaa.append(initials); newaa.append(famName); PDBHeader header = structure.getPDBHeader(); String auth = header.getAuthors(); if (auth == null) { header.setAuthors(newaa.toString()); }else { auth += "," + newaa.toString(); header.setAuthors(auth); } } @SuppressWarnings("deprecation") public void newExptl(Exptl exptl) { PDBHeader pdbHeader = structure.getPDBHeader(); String method = exptl.getMethod(); String old = pdbHeader.getTechnique(); if ( (old != null) && (! old.equals(""))){ method = old+"; " + method; } pdbHeader.setTechnique(method); Map<String,Object> header = structure.getHeader(); header.put("technique",method); } public void newStructRef(StructRef sref) { if (DEBUG) System.out.println(sref); strucRefs.add(sref); } private StructRef getStructRef(String ref_id){ for (StructRef structRef : strucRefs) { if (structRef.getId().equals(ref_id)){ return structRef; } } return null; } /** create a DBRef record from the StrucRefSeq record: * <pre> PDB record DBREF Field Name mmCIF Data Item Section n.a. PDB_ID_Code _struct_ref_seq.pdbx_PDB_id_code Strand_ID _struct_ref_seq.pdbx_strand_id Begin_Residue_Number _struct_ref_seq.pdbx_auth_seq_align_beg Begin_Ins_Code _struct_ref_seq.pdbx_seq_align_beg_ins_code End_Residue_Number _struct_ref_seq.pdbx_auth_seq_align_end End_Ins_Code _struct_ref_seq.pdbx_seq_align_end_ins_code Database _struct_ref.db_name Database_Accession_No _struct_ref_seq.pdbx_db_accession Database_ID_Code _struct_ref.db_code Database_Begin_Residue_Number _struct_ref_seq.db_align_beg Databaes_Begin_Ins_Code _struct_ref_seq.pdbx_db_align_beg_ins_code Database_End_Residue_Number _struct_ref_seq.db_align_end Databaes_End_Ins_Code _struct_ref_seq.pdbx_db_align_end_ins_code </pre> * * */ public void newStructRefSeq(StructRefSeq sref) { //if (DEBUG) // System.out.println(sref); DBRef r = new DBRef(); //if (DEBUG) // System.out.println( " " + sref.getPdbx_PDB_id_code() + " " + sref.getPdbx_db_accession()); r.setIdCode(sref.getPdbx_PDB_id_code()); r.setDbAccession(sref.getPdbx_db_accession()); r.setDbIdCode(sref.getPdbx_db_accession()); //TODO: make DBRef chain IDs a string for chainIDs that are longer than one char... r.setChainId(new Character(sref.getPdbx_strand_id().charAt(0))); StructRef structRef = getStructRef(sref.getRef_id()); if (structRef == null){ logger.warning("could not find StructRef " + sref.getRef_id() + " for StructRefSeq " + sref); } else { r.setDatabase(structRef.getDb_name()); r.setDbIdCode(structRef.getDb_code()); } int seqbegin = Integer.parseInt(sref.getPdbx_auth_seq_align_beg()); int seqend = Integer.parseInt(sref.getPdbx_auth_seq_align_end()); Character begin_ins_code = new Character(sref.getPdbx_seq_align_beg_ins_code().charAt(0)); Character end_ins_code = new Character(sref.getPdbx_seq_align_end_ins_code().charAt(0)); if (begin_ins_code == '?') begin_ins_code = ' '; if (end_ins_code == '?') end_ins_code = ' '; r.setSeqBegin(seqbegin); r.setInsertBegin(begin_ins_code); r.setSeqEnd(seqend); r.setInsertEnd(end_ins_code); int dbseqbegin = Integer.parseInt(sref.getDb_align_beg()); int dbseqend = Integer.parseInt(sref.getDb_align_end()); Character db_begin_in_code = new Character(sref.getPdbx_db_align_beg_ins_code().charAt(0)); Character db_end_in_code = new Character(sref.getPdbx_db_align_end_ins_code().charAt(0)); if (db_begin_in_code == '?') db_begin_in_code = ' '; if (db_end_in_code == '?') db_end_in_code = ' '; r.setDbSeqBegin(dbseqbegin); r.setIdbnsBegin(db_begin_in_code); r.setDbSeqEnd(dbseqend); r.setIdbnsEnd(db_end_in_code); List<DBRef> dbrefs = structure.getDBRefs(); if ( dbrefs == null) dbrefs = new ArrayList<DBRef>(); dbrefs.add(r); if ( DEBUG) System.out.println(r.toPDB()); structure.setDBRefs(dbrefs); } private Chain getChainFromList(List<Chain> chains, String name){ for (Chain chain : chains) { if ( chain.getChainID().equals(name)){ return chain; } } // does not exist yet, so create... Chain chain = new ChainImpl(); chain.setChainID(name); chains.add(chain); return chain; } private Chain getEntityChain(String entity_id){ return getChainFromList(entityChains,entity_id); } //private Chain getSeqResChain(String chainID){ // return getChainFromList(seqResChains, chainID); /** The EntityPolySeq object provide the amino acid sequence objects for the Entities. * Later on the entities are mapped to the BioJava Chain and Compound objects. * @param epolseq the EntityPolySeq record for one amino acid */ public void newEntityPolySeq(EntityPolySeq epolseq) { if (DEBUG) System.out.println("NEW entity poly seq " + epolseq); Entity e = getEntity(epolseq.getEntity_id()); if (e == null){ System.err.println("could not find entity "+ epolseq.getEntity_id()+". Can not match sequence to it."); return; } Chain entityChain = getEntityChain(epolseq.getEntity_id()); // create group from epolseq; // by default this are the SEQRES records... AminoAcid g = new AminoAcidImpl(); g.setRecordType(AminoAcid.SEQRESRECORD); try { g.setPDBName(epolseq.getMon_id()); Character code1 = StructureTools.convert_3code_1code(epolseq.getMon_id()); g.setAminoType(code1); g.setResidueNumber(ResidueNumber.fromString(epolseq.getNum())); // ARGH at this stage we don;t know about insertion codes // this has to be obtained from _pdbx_poly_seq_scheme entityChain.addGroup(g); } catch (PDBParseException ex) { if ( StructureTools.isNucleotide(epolseq.getMon_id())) { // the group is actually a nucleotide group... NucleotideImpl n = new NucleotideImpl(); n.setResidueNumber(ResidueNumber.fromString(epolseq.getNum())); entityChain.addGroup(n); } else { logger.warning(ex.getMessage() + " creating a hetatom called XXX "); HetatomImpl h = new HetatomImpl(); try { h.setPDBName(epolseq.getMon_id()); //h.setAminoType('X'); h.setResidueNumber(ResidueNumber.fromString(epolseq.getNum())); entityChain.addGroup(h); } catch (PDBParseException exc) { System.err.println("this is a helpless case and I am dropping group " + epolseq.getMon_id()); } //ex.printStackTrace(); } } catch (UnknownPdbAminoAcidException ex){ //logger.warning("no sure what to do with:" + epolseq.getMon_id()+ " " + ex.getMessage()); HetatomImpl h = new HetatomImpl(); try { h.setPDBName(epolseq.getMon_id()); //h.setAminoType('X'); h.setResidueNumber(ResidueNumber.fromString(epolseq.getNum())); entityChain.addGroup(h); } catch (PDBParseException exc) { System.err.println("this is a helpless case and I am dropping group " + epolseq.getMon_id() + " " + ex.getMessage()); } //System.err.println(ex.getMessage()); } } /* returns the chains from all models that have the provided chainId * */ private List<Chain> getChainsFromAllModels(String chainId){ List<Chain> chains = new ArrayList<Chain>(); for (int i=0 ; i < structure.nrModels();i++){ List<Chain> model = structure.getModel(i); for (Chain c: model){ if (c.getChainID().equals(chainId)) { chains.add(c); } } } return chains; } /** finds the residue in the internal representation and fixes the residue number and insertion code * * @param ppss */ private void replaceGroupSeqPos(PdbxPolySeqScheme ppss){ if (ppss.getAuth_seq_num().equals("?")) return; // at this stage we are still using the internal asym ids... List<Chain> matchinChains = getChainsFromAllModels(ppss.getAsym_id()); long sid = Long.parseLong(ppss.getSeq_id()); for (Chain c: matchinChains){ Group target = null; for (Group g: c.getAtomGroups()){ if ( g instanceof AminoAcidImpl){ AminoAcidImpl aa = (AminoAcidImpl)g; if (aa.getId() == sid ) { // found it: target = g; break; } } else if ( g instanceof NucleotideImpl) { NucleotideImpl n = (NucleotideImpl)g; if ( n.getId() == sid) { target = g; break; } } } if (target == null){ logger.info("could not find group at seq. position " + ppss.getSeq_id() + " in internal chain. " + ppss); continue; } if (! target.getPDBName().equals(ppss.getMon_id())){ logger.info("could not match PdbxPolySeqScheme to chain:" + ppss); continue; } // fix the residue number to the one used in the PDB files... Integer pdbResNum = Integer.parseInt(ppss.getAuth_seq_num()); // check the insertion code... String insCodeS = ppss.getPdb_ins_code(); Character insCode = null; if ( ( insCodeS != null) && (! insCodeS.equals(".")) && insCodeS.length()>0){ //pdbResNum += insCode insCode = insCodeS.charAt(0); } ResidueNumber residueNumber = new ResidueNumber(null, pdbResNum,insCode); target.setResidueNumber(residueNumber); } } public void newPdbxPolySeqScheme(PdbxPolySeqScheme ppss) { //if ( headerOnly) // return; // replace the group asym ids with the real PDB ids! replaceGroupSeqPos(ppss); // merge the EntityPolySeq info and the AtomSite chains into one... //already known ignore: if (asymStrandId.containsKey(ppss.getAsym_id())) return; // this is one of the interal mmcif rules it seems... if ( ppss.getPdb_strand_id() == null) { asymStrandId.put(ppss.getAsym_id(), ppss.getAuth_mon_id()); return; } //System.out.println(ppss.getAsym_id() + " = " + ppss.getPdb_strand_id()); asymStrandId.put(ppss.getAsym_id(), ppss.getPdb_strand_id()); } public void newPdbxNonPolyScheme(PdbxNonPolyScheme ppss) { //if (headerOnly) // return; // merge the EntityPolySeq info and the AtomSite chains into one... //already known ignore: if (asymStrandId.containsKey(ppss.getAsym_id())) return; // this is one of the interal mmcif rules it seems... if ( ppss.getPdb_strand_id() == null) { asymStrandId.put(ppss.getAsym_id(), ppss.getAsym_id()); return; } asymStrandId.put(ppss.getAsym_id(), ppss.getPdb_strand_id()); } public void newPdbxEntityNonPoly(PdbxEntityNonPoly pen){ // TODO: do something with them... } public void newChemComp(ChemComp c) { // TODO: do something with them... } public void newGenericData(String category, List<String> loopFields, List<String> lineData) { if (DEBUG) { System.err.println("unhandled category so far: " + category); } } public FileParsingParameters getFileParsingParameters() { return params; } public void setFileParsingParameters(FileParsingParameters params) { this.params = params; } }
package info.curtbinder.reefangel.service; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import android.util.Log; public class Host { private static final String TAG = Host.class.getSimpleName(); private String host; private int port; private String command; private int timeoutConnect; private int timeoutRead; private String raUserid; private final String RAPARAMS = "http://forum.reefangel.com/status/params.aspx?id="; private final String RALABELS = "http://forum.reefangel.com/status/labels.aspx?id="; // for memory reading/writing private int location; private int value; private boolean write; // for labels only private boolean labels; Host ( int timeoutConnect, int timeoutRead ) { setDefaults( "", 80, RequestCommands.None ); this.timeoutConnect = timeoutConnect; this.timeoutRead = timeoutRead; } /* Host ( String userid ) { setDefaults( "", 80, RequestCommands.ReefAngel ); raUserid = userid; } Host ( String host, int port, String command ) { setDefaults( host, port, command ); } Host ( String host, String port, String command ) { setDefaults( host, Integer.parseInt( port ), command ); } */ private void setDefaults ( String host, int port, String command ) { this.host = host; this.port = port; this.command = command; //timeoutConnect = 15000; // milliseconds //timeoutRead = 10000; // milliseconds location = 0; value = 0; write = false; raUserid = ""; labels = false; } public void setHost ( String host ) { this.host = host; } public void setPort ( String port ) { this.port = Integer.parseInt( port ); } public void setCommand ( String command ) { this.command = command; } public String getCommand ( ) { return this.command; } public void setUserId ( String userid ) { raUserid = userid; setCommand( RequestCommands.ReefAngel ); } public void setGetLabelsOnly ( boolean getLabels ) { // TODO consider putting a check for a valid raUserid this.labels = true; setCommand( RequestCommands.ReefAngel ); } public boolean isRequestForLabels ( ) { return this.labels; } public int getConnectTimeout ( ) { return timeoutConnect; } public void setConnectTimeout ( int timeout ) { timeoutConnect = timeout; } public int getReadTimeout ( ) { return timeoutRead; } public void setReadTimout ( int timeout ) { timeoutRead = timeout; } public void setReadLocation ( int location ) { this.location = location; this.value = 0; this.write = false; } public void setWriteLocation ( int location, int value ) { this.location = location; this.value = value; this.write = true; } public boolean isWrite ( ) { return this.write; } public void setOverrideLocation ( int port, int value ) { this.location = port; this.value = value; } public void setCalibrateType ( int type ) { this.location = type; } public String toString ( ) { // TODO improve error message with a null host string String s = ""; if ( (command.startsWith( RequestCommands.Relay )) || (command.equals( RequestCommands.Status )) || (command.equals( RequestCommands.Version )) || (command.equals( RequestCommands.FeedingMode )) || (command.equals( RequestCommands.ExitMode )) || (command.equals( RequestCommands.WaterMode )) || (command.equals( RequestCommands.AtoClear )) || (command.equals( RequestCommands.OverheatClear )) || (command.startsWith( RequestCommands.DateTime )) || (command.equals( RequestCommands.LightsOn )) || (command.equals( RequestCommands.LightsOff )) || (command.equals( RequestCommands.Reboot )) ) { s = new String( String.format( "http://%s:%d%s", host, port, command ) ); } else if ( (command.equals( RequestCommands.MemoryInt )) || (command.equals( RequestCommands.MemoryByte )) ) { if ( write ) { s = new String( String.format( "http://%s:%d%s%d,%d", host, port, command, location, value ) ); } else { s = new String( String.format( "http://%s:%d%s%d", host, port, command, location ) ); } } else if ( command.equals( RequestCommands.Calibrate ) ) { s = new String ( String.format( "http://%s:%d%s%d", host, port, command, location) ); } else if ( command.equals( RequestCommands.PwmOverride ) ) { s = new String ( String.format( "http://%s:%d%s%d,%d", host, port, command, location, value) ); } else if ( command.equals( RequestCommands.ReefAngel ) ) { String encodedId; try { encodedId = URLEncoder.encode( raUserid, "UTF-8" ); } catch ( UnsupportedEncodingException e ) { Log.e( TAG, "Failed URL encoder" ); encodedId = ""; } if ( labels ) { s = RALABELS + encodedId; } else { s = RAPARAMS + encodedId; } } return s; } }
package uk.org.taverna.platform.run.impl; import java.io.File; import java.io.IOException; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.osgi.service.event.Event; import org.osgi.service.event.EventAdmin; import org.purl.wf4ever.robundle.Bundle; import uk.org.taverna.databundle.DataBundles; import uk.org.taverna.platform.execution.api.ExecutionEnvironment; import uk.org.taverna.platform.execution.api.ExecutionEnvironmentService; import uk.org.taverna.platform.execution.api.InvalidExecutionIdException; import uk.org.taverna.platform.execution.api.InvalidWorkflowException; import uk.org.taverna.platform.report.ReportListener; import uk.org.taverna.platform.report.State; import uk.org.taverna.platform.report.WorkflowReport; import uk.org.taverna.platform.run.api.InvalidRunIdException; import uk.org.taverna.platform.run.api.RunProfile; import uk.org.taverna.platform.run.api.RunProfileException; import uk.org.taverna.platform.run.api.RunService; import uk.org.taverna.platform.run.api.RunStateException; import uk.org.taverna.scufl2.api.container.WorkflowBundle; import uk.org.taverna.scufl2.api.core.Workflow; import uk.org.taverna.scufl2.api.io.ReaderException; import uk.org.taverna.scufl2.api.io.WorkflowBundleIO; import uk.org.taverna.scufl2.api.profiles.Profile; /** * Implementation of the <code>RunService</code>. * * @author David Withers */ public class RunServiceImpl implements RunService { private static SimpleDateFormat ISO_8601 = new SimpleDateFormat("yyyy-MM-dd_HHmmss"); private final Map<String, Run> runMap; private ExecutionEnvironmentService executionEnvironmentService; private EventAdmin eventAdmin; public RunServiceImpl() { runMap = new TreeMap<>(); } @Override public Set<ExecutionEnvironment> getExecutionEnvironments() { return executionEnvironmentService.getExecutionEnvironments(); } @Override public Set<ExecutionEnvironment> getExecutionEnvironments(WorkflowBundle workflowBundle) { return getExecutionEnvironments(workflowBundle.getMainProfile()); } @Override public Set<ExecutionEnvironment> getExecutionEnvironments(Profile profile) { return executionEnvironmentService.getExecutionEnvironments(profile); } @Override public List<String> getRuns() { return new ArrayList<>(runMap.keySet()); } @Override public String createRun(RunProfile runProfile) throws InvalidWorkflowException, RunProfileException { Run run = new Run(runProfile); run.getWorkflowReport().addReportListener(new RunReportListener(run.getID())); runMap.put(run.getID(), run); postEvent(RUN_CREATED, run.getID()); return run.getID(); } @Override public String open(File runFile) throws IOException { Bundle bundle = DataBundles.openBundle(runFile.toPath()); try { String fileName = runFile.getName(); int dot = fileName.indexOf('.'); if (dot > 0) { fileName = fileName.substring(0, dot); } Run run = new Run(fileName, bundle); runMap.put(run.getID(), run); postEvent(RUN_OPENED, run.getID()); return runFile.getName(); } catch (ReaderException | ParseException e) { throw new IOException("Error opening file " + runFile, e); } } @Override public void close(String runID) throws InvalidRunIdException, InvalidExecutionIdException { runMap.remove(runID); postEvent(RUN_CLOSED, runID); } @Override public void save(String runID, File runFile) throws InvalidRunIdException, IOException { Run run = getRun(runID); Bundle dataBundle = run.getDataBundle(); try { DataBundles.closeAndSaveBundle(dataBundle, runFile.toPath()); } catch (InvalidPathException e) { throw new IOException(e); } } @Override public void delete(String runID) throws InvalidRunIdException, InvalidExecutionIdException { getRun(runID).delete(); runMap.remove(runID); postEvent(RUN_DELETED, runID); } @Override public void start(String runID) throws InvalidRunIdException, RunStateException, InvalidExecutionIdException { getRun(runID).start(); postEvent(RUN_STARTED, runID); } @Override public void pause(String runID) throws InvalidRunIdException, RunStateException, InvalidExecutionIdException { getRun(runID).pause(); postEvent(RUN_PAUSED, runID); } @Override public void resume(String runID) throws InvalidRunIdException, RunStateException, InvalidExecutionIdException { getRun(runID).resume(); postEvent(RUN_RESUMED, runID); } @Override public void cancel(String runID) throws InvalidRunIdException, RunStateException, InvalidExecutionIdException { getRun(runID).cancel(); postEvent(RUN_STOPPED, runID); } @Override public State getState(String runID) throws InvalidRunIdException { return getRun(runID).getState(); } @Override public Bundle getDataBundle(String runID) throws InvalidRunIdException { return getRun(runID).getDataBundle(); } @Override public WorkflowReport getWorkflowReport(String runID) throws InvalidRunIdException { return getRun(runID).getWorkflowReport(); } @Override public Workflow getWorkflow(String runID) throws InvalidRunIdException { return getRun(runID).getWorkflow(); } @Override public Profile getProfile(String runID) throws InvalidRunIdException { return getRun(runID).getProfile(); } @Override public String getRunName(String runID) throws InvalidRunIdException { WorkflowReport workflowReport = getWorkflowReport(runID); return workflowReport.getSubject().getName() + "_" + ISO_8601.format(workflowReport.getCreatedDate()); } private Run getRun(String runID) throws InvalidRunIdException { Run run = runMap.get(runID); if (run == null) { throw new InvalidRunIdException("Run ID " + runID + " is not valid"); } return run; } private void postEvent(String topic, String runId) { HashMap<String, String> properties = new HashMap<>(); properties.put("RUN_ID", runId); Event event = new Event(topic, properties); eventAdmin.postEvent(event); } public void setExecutionEnvironmentService(ExecutionEnvironmentService executionEnvironmentService) { this.executionEnvironmentService = executionEnvironmentService; } public void setEventAdmin(EventAdmin eventAdmin) { this.eventAdmin = eventAdmin; } public void setWorkflowBundleIO(WorkflowBundleIO workflowBundleIO) { DataBundles.setWfBundleIO(workflowBundleIO); } private class RunReportListener implements ReportListener { private final String runId; public RunReportListener(String runId) { this.runId = runId; } @Override public void outputAdded(Path path, String portName, int[] index) { } @Override public void stateChanged(State oldState, State newState) { switch (newState) { case COMPLETED: case FAILED: postEvent(RUN_STOPPED, runId); break; } } } }
package org.cornutum.tcases.openapi.testwriter; import org.cornutum.tcases.io.IndentedWriter; import org.cornutum.tcases.openapi.resolver.RequestCase; import org.cornutum.tcases.openapi.test.ResponsesDef; import org.cornutum.tcases.util.ToString; import static org.apache.commons.io.FilenameUtils.getBaseName; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.OutputStream; import java.net.URI; import java.util.List; import java.util.Optional; /** * Writes the source code for a test that executes API requests. */ public abstract class TestWriter<S extends TestSource, T extends TestTarget> { /** * Creates a new TestWriter instance. */ protected TestWriter( TestCaseWriter testCaseWriter) { testCaseWriter_ = testCaseWriter; } /** * Creates a test that executes the request test cases defined by the given {@link TestSource source} * and writes the result to the given {@link TestTarget target}. */ public void writeTest( S source, T target) { String testName = getTestName( source, target); File targetFile = getTargetFile( target, testName); File targetDir = Optional.ofNullable( targetFile) .flatMap( file -> Optional.ofNullable( file.getParentFile())) .map( File::getAbsoluteFile) .orElse( null); if( targetDir != null && !(targetDir.exists() || targetDir.mkdirs())) { throw new TestWriterException( String.format( "Can't create targetDir=%s", targetDir)); } OutputStream fileStream = null; IndentedWriter targetWriter = null; try { fileStream = targetFile == null ? null : new FileOutputStream( targetFile); OutputStream targetStream = Optional.ofNullable( fileStream) .orElse( Optional.ofNullable( target.getOutput()) .orElse( System.out)); targetWriter = new IndentedWriter( targetStream); targetWriter.setIndent( 4); writeProlog( target, testName, targetWriter); writeTestCases( target, testName, source.getRequestCases(), targetWriter); writeEpilog( target, testName, targetWriter); } catch( Exception e) { throw new TestWriterException( String.format( "Can't write test=%s", testName), e); } finally { if( targetWriter != null) { targetWriter.flush(); } closeQuietly( fileStream, null); } Optional.ofNullable( source.getResponses()) .ifPresent( responses -> writeResponsesDef( responses, targetFile, target.getResourceDir())); } /** * Returns the test file written for the given source and target. Returns null if the test is written to a stream. */ public File getTestFile( S source, T target) { return getTargetFile( target, getTestName( source, target)); } /** * Returns the test name derived from the given source and target. */ public String getTestName( S source, T target) { return getTestName( Optional.ofNullable( getTestBaseName( source, target)) .orElseThrow( () -> new TestWriterException( String.format( "No test name defined by source=%s, target=%s", source, target)))); } /** * Returns the test name derived from the given base name. */ protected abstract String getTestName( String baseName); /** * Returns the base test name defined by the given source and target. */ protected String getTestBaseName( S source, T target) { return Optional.ofNullable( target.getName()) .orElse( Optional.ofNullable( target.getFile()) .map( file -> getBaseName( file.getName())) .orElse( source.getApi())); } /** * Returns the target file defined by the given target. */ protected File getTargetFile( T target, String testName) { File targetFile = target.getFile(); File targetDir = target.getDir(); return targetFile == null && targetDir == null? null : targetDir == null? targetFile : targetFile == null? new File( targetDir, testName.replaceAll( "[/<>|:& \\\\]+", "-")) : targetFile.isAbsolute()? targetFile : new File( targetDir, targetFile.getPath()); } /** * Writes the target test prolog to the given stream. */ protected void writeProlog( T target, String testName, IndentedWriter targetWriter) { writeOpening( target, testName, targetWriter); writeDependencies( target, testName, targetWriter); getTestCaseWriter().writeDependencies( testName, targetWriter); writeDeclarations( target, testName, targetWriter); getTestCaseWriter().writeDeclarations( testName, targetWriter); } /** * Writes the target test opening to the given stream. */ protected abstract void writeOpening( T target, String testName, IndentedWriter targetWriter); /** * Writes the target test dependencies to the given stream. */ protected abstract void writeDependencies( T target, String testName, IndentedWriter targetWriter); /** * Writes the target test declarations to the given stream. */ protected abstract void writeDeclarations( T target, String testName, IndentedWriter targetWriter); /** * Writes the target test cases to the given stream. */ protected void writeTestCases( T target, String testName, List<RequestCase> requestCases, IndentedWriter targetWriter) { requestCases.stream().forEach( requestCase -> writeTestCase( target, testName, requestCase, targetWriter)); } /** * Writes a target test case to the given stream. */ protected void writeTestCase( T target, String testName, RequestCase requestCase, IndentedWriter targetWriter) { getTestCaseWriter().writeTestCase( testName, getTestServer( requestCase), requestCase, targetWriter); } /** * Writes the target test epilog to the given stream. */ protected void writeEpilog( T target, String testName, IndentedWriter targetWriter) { getTestCaseWriter().writeClosing( testName, targetWriter); writeClosing( target, testName, targetWriter); } /** * Writes the target test closing to the given stream. */ protected abstract void writeClosing( T target, String testName, IndentedWriter targetWriter); /** * Writes the target test responses definition to a resource file associated with the test target file. */ protected void writeResponsesDef( ResponsesDef responses, File targetFile, File resourceDir) { File targetDir = Optional.ofNullable( targetFile) .map( target -> target.getParentFile()) .orElse( null); File targetResourceDir = Optional.ofNullable( resourceDir) .map( dir -> dir.isAbsolute() || targetDir == null? dir : new File( targetDir, dir.getPath())) .orElse( targetDir); if( targetResourceDir != null) { Optional.of( targetResourceDir) .filter( dir -> dir.exists() || dir.mkdirs()) .orElseThrow( () -> new TestWriterException( String.format( "Can't create resourceDir=%s", targetResourceDir))); File resourceFile = new File( targetResourceDir, String.format( "%s-Responses.json", getBaseName( targetFile.getName()))); try( FileWriter writer = new FileWriter( resourceFile)) { ResponsesDef.write( responses, writer); } catch( Exception e) { throw new TestWriterException( String.format( "Can't write responses definition to resourceFile=%s", resourceFile), e); } } } /** * Returns the {@link TestCaseWriter} for this test. */ protected TestCaseWriter getTestCaseWriter() { return testCaseWriter_; } /** * Returns a URI for the API server used by the given test case. If non-null, this supersedes * the server URI defined by this {@link RequestCase request case}. */ protected URI getTestServer( RequestCase requestCase) { // By default, none defined. return null; } @Override public String toString() { return ToString.getBuilder( this) .toString(); } private final TestCaseWriter testCaseWriter_; }
package com.uber.tchannel.schemes; public class DefaultRawRequestHandler implements RawRequestHandler { @Override public RawResponse handle(RawRequest request) { return new RawResponse( request.getId(), request.getTransportHeaders(), request.getArg1(), request.getArg2(), request.getArg3() ); } }
package com.marklogic.javaclient; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.xml.sax.SAXException; import com.marklogic.client.DatabaseClient; import com.marklogic.client.DatabaseClientFactory; import com.marklogic.client.DatabaseClientFactory.Authentication; import com.marklogic.client.query.QueryManager; import com.marklogic.client.query.StringQueryDefinition; import com.marklogic.client.io.DOMHandle; import com.marklogic.client.io.DocumentMetadataHandle; import static org.custommonkey.xmlunit.XMLAssert.assertXpathEvaluatesTo; import org.custommonkey.xmlunit.exceptions.XpathException; import org.junit.*; public class TestConstraintCombination extends BasicJavaClientREST { private static String dbName = "ConstraintCombinationDB"; private static String [] fNames = {"ConstraintCombinationDB-1"}; private static String restServerName = "REST-Java-Client-API-Server"; private static int restPort = 8011; @BeforeClass public static void setUp() throws Exception { System.out.println("In setup"); setupJavaRESTServer(dbName, fNames[0], restServerName,8011); addRangeElementAttributeIndex(dbName, "dateTime", "http://example.com", "entry", "", "date"); addRangeElementIndex(dbName, "int", "http://example.com", "scoville"); addRangeElementIndex(dbName, "decimal", "http://example.com", "rating"); addField(dbName, "bbqtext"); includeElementField(dbName, "bbqtext", "http://example.com", "title"); includeElementField(dbName, "bbqtext", "http://example.com", "abstract"); enableCollectionLexicon(dbName); enableTrailingWildcardSearches(dbName); } @After public void testCleanUp() throws Exception { clearDB(restPort); System.out.println("Running clear script"); } @SuppressWarnings("deprecation") @Test public void testConstraintCombination() throws IOException, ParserConfigurationException, SAXException, XpathException { System.out.println("Running testConstraintCombination"); String filename1 = "bbq1.xml"; String filename2 = "bbq2.xml"; String filename3 = "bbq3.xml"; String filename4 = "bbq4.xml"; String filename5 = "bbq5.xml"; String queryOptionName = "constraintCombinationOpt.xml"; DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-admin", "x", Authentication.DIGEST); // create and initialize a handle on the metadata DocumentMetadataHandle metadataHandle1 = new DocumentMetadataHandle(); DocumentMetadataHandle metadataHandle2 = new DocumentMetadataHandle(); DocumentMetadataHandle metadataHandle3 = new DocumentMetadataHandle(); DocumentMetadataHandle metadataHandle4 = new DocumentMetadataHandle(); DocumentMetadataHandle metadataHandle5 = new DocumentMetadataHandle(); // set the metadata metadataHandle1.getCollections().addAll("http://bbq.com/contributor/AuntSally"); metadataHandle2.getCollections().addAll("http://bbq.com/contributor/BigTex"); metadataHandle3.getCollections().addAll("http://bbq.com/contributor/Dubois"); metadataHandle4.getCollections().addAll("http://bbq.com/contributor/BigTex"); metadataHandle5.getCollections().addAll("http://bbq.com/contributor/Dorothy"); // write docs writeDocumentUsingInputStreamHandle(client, filename1, "/combination-constraint/", metadataHandle1, "XML"); writeDocumentUsingInputStreamHandle(client, filename2, "/combination-constraint/", metadataHandle2, "XML"); writeDocumentUsingInputStreamHandle(client, filename3, "/combination-constraint/", metadataHandle3, "XML"); writeDocumentUsingInputStreamHandle(client, filename4, "/combination-constraint/", metadataHandle4, "XML"); writeDocumentUsingInputStreamHandle(client, filename5, "/combination-constraint/", metadataHandle5, "XML"); setQueryOption(client, queryOptionName); QueryManager queryMgr = client.newQueryManager(); // create query def StringQueryDefinition querydef = queryMgr.newStringDefinition(queryOptionName); querydef.setCriteria("intitle:BBQ AND flavor:smok* AND heat:moderate AND contributor:AuntSally AND (summary:Southern AND summary:classic)"); // create handle DOMHandle resultsHandle = new DOMHandle(); queryMgr.search(querydef, resultsHandle); // get the result Document resultDoc = resultsHandle.get();
package com.asksunny.schema; import java.util.Comparator; public class FieldDrillDownComparator implements Comparator<Field> { public FieldDrillDownComparator() { } @Override public int compare(Field o1, Field o2) { return Integer.valueOf(o1.getDrillDown()).compareTo( Integer.valueOf(o2.getDrillDown())); } }
package com.alvazan.ssql.cmdline; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alvazan.orm.api.base.NoSqlEntityManager; import com.alvazan.orm.api.z3api.NoSqlTypedSession; import com.alvazan.orm.api.z5api.IndexPoint; import com.alvazan.orm.api.z8spi.KeyValue; import com.alvazan.orm.api.z8spi.action.IndexColumn; import com.alvazan.orm.api.z8spi.iter.Cursor; import com.alvazan.orm.api.z8spi.meta.DboColumnMeta; import com.alvazan.orm.api.z8spi.meta.DboTableMeta; import com.alvazan.orm.api.z8spi.meta.TypedColumn; import com.alvazan.orm.api.z8spi.meta.TypedRow; public class CmdIndex { private static final int BATCH_SIZE = 200; private static final int TIME_TO_REPORT = 10000; public void reindex(String cmd, NoSqlEntityManager mgr) { String oldCommand = cmd.substring(8); String command = oldCommand.trim(); ColFamilyData data = parseData(mgr, command); NoSqlTypedSession s = mgr.getTypedSession(); String cf = data.getColFamily(); String field = data.getColumn(); String by = data.getPartitionBy(); String id = data.getPartitionId(); Cursor<IndexPoint> indexView = s.indexView(cf, field, by, id); Cursor<IndexPoint> indexView2 = s.indexView(cf, field, by, id); DboTableMeta meta = data.getTableMeta(); DboColumnMeta colMeta = data.getColumnMeta(); System.out.println("indexed value type="+colMeta.getStorageType()); System.out.println("row key type="+meta.getIdColumnMeta().getStorageType()); System.out.println("It is safe to kill this process at any time since it only removes duplicates"); System.out.println("Beginning re-index"); int totalChanges = 0; int totalRows = 0; int rowCountProcessed = 0; while(true) { Map<Object, KeyValue<TypedRow>> keyToRow = findNextSetOfData(s, cf, indexView); rowCountProcessed += keyToRow.size(); if(keyToRow.size() == 0) { break; //finished } Counter c = processAllColumns(s, data, keyToRow, indexView2); totalRows += c.getRowCounter(); totalChanges += c.getChangedCounter(); if(rowCountProcessed % 1000 == 0) { System.out.println("#Rows processed="+rowCountProcessed+" totalRows to process="+totalRows+" totalChanges so far="+totalChanges); } } System.out.println("#Rows processed="+rowCountProcessed+" totalRows to process="+totalRows+" totalChanges="+totalChanges); } private Counter processAllColumns(NoSqlTypedSession s, ColFamilyData data, Map<Object, KeyValue<TypedRow>> keyToRow, Cursor<IndexPoint> indexView2) { String colName = data.getColumn(); int rowCounter = 0; int changedCounter = 0; while(indexView2.next()) { IndexPoint pt = indexView2.getCurrent(); KeyValue<TypedRow> row = keyToRow.get(pt.getKey()); if(row == null) { //We are iterating over two views in batch mode soooo //one batch may not have any of the keys of the other batch. This is very normal } else if(row.getException() != null) { System.out.println("Entity with rowkey="+pt.getKeyAsString()+" does not exist, WILL remove from index"); s.removeIndexPoint(pt, data.getPartitionBy(), data.getPartitionBy()); changedCounter++; } else { TypedRow val = row.getValue(); TypedColumn column = val.getColumn(colName); if (column == null) { //It means column was deleted by user. Doing nothing as of now continue; } Object value = column.getValue(); if(!valuesEqual(pt.getIndexedValue(), value)) { System.out.println("Entity with rowkey="+pt.getKeyAsString()+" has extra incorrect index point with value="+pt.getIndexedValueAsString()+" correct value should be="+column.getValueAsString()); s.removeIndexPoint(pt, data.getPartitionBy(), data.getPartitionId()); IndexColumn col = new IndexColumn(); col.setColumnName(colName); col.setPrimaryKey(pt.getRawKey()); byte[] indValue = column.getValueRaw(); col.setIndexedValue(indValue); IndexPoint newPoint = new IndexPoint(pt.getRowKeyMeta(), col , data.getColumnMeta()); s.addIndexPoint(newPoint, data.getPartitionBy(), data.getPartitionId()); changedCounter++; } } rowCounter++; if(changedCounter > 50) { s.flush(); //System.out.println("Successfully flushed all previous changes. row="+rowCounter); } if(rowCounter % 1000 == 0) { System.out.println("reindexing. row count so far="+rowCounter+" num index points changed="+changedCounter); } } s.flush(); return new Counter(rowCounter, changedCounter); } private boolean valuesEqual(Object indexedValue, Object value) { if(indexedValue == null) { if(value == null) return true; return false; } else if(indexedValue.equals(value)) return true; return false; } private static class Counter { private int rowCounter; private int changedCounter; public Counter(int rowCounter, int changedCounter) { super(); this.rowCounter = rowCounter; this.changedCounter = changedCounter; } public int getRowCounter() { return rowCounter; } public int getChangedCounter() { return changedCounter; } } private Map<Object, KeyValue<TypedRow>> findNextSetOfData( NoSqlTypedSession s, String cf, Cursor<IndexPoint> indexView) { int batchCounter = 0; List<Object> keys = new ArrayList<Object>(); while(indexView.next() && batchCounter < BATCH_SIZE) { IndexPoint current = indexView.getCurrent(); keys.add(current.getKey()); batchCounter++; } Map<Object, KeyValue<TypedRow>> keyToRow = new HashMap<Object, KeyValue<TypedRow>>(); Cursor<KeyValue<TypedRow>> cursor = s.createFindCursor(cf, keys, BATCH_SIZE); while(cursor.next()) { KeyValue<TypedRow> current = cursor.getCurrent(); keyToRow.put(current.getKey(), current); } return keyToRow; } public void processIndex(String cmd, NoSqlEntityManager mgr) { String oldCommand = cmd.substring(10); String command = oldCommand.trim(); ColFamilyData data = parseData(mgr, command); NoSqlTypedSession s = mgr.getTypedSession(); String cf = data.getColFamily(); String field = data.getColumn(); String by = data.getPartitionBy(); String id = data.getPartitionId(); Cursor<IndexPoint> indexView = s.indexView(cf, field, by, id); DboTableMeta meta = data.getTableMeta(); DboColumnMeta colMeta = data.getColumnMeta(); System.out.println("indexed value type="+colMeta.getStorageType()); System.out.println("row key type="+meta.getIdColumnMeta().getStorageType()); System.out.println("<indexed value>.<row key>"); int count = 0; while(indexView.next()) { IndexPoint current = indexView.getCurrent(); String indVal = current.getIndexedValueAsString(); if(indVal == null) indVal = ""; String key = current.getKeyAsString(); System.out.println(count+" "+indVal+"."+key); count++; } System.out.println(count+" Columns Total"); } public ColFamilyData parseData(NoSqlEntityManager mgr, String command) { int index = command.indexOf("/"); if(index != 0) { throw new InvalidCommand("Index must start with '/' and does not"); } String withoutSlash = command.substring(1); index = withoutSlash.indexOf("/"); if(index < 0) { throw new InvalidCommand("Index requires two '/'"); } String cf = withoutSlash.substring(0, index); String lastPart = withoutSlash.substring(index+1); return goMore(mgr, cf, lastPart); } private ColFamilyData goMore(NoSqlEntityManager mgr, String cf, String lastPart) { ColFamilyData data = new ColFamilyData(); int index = lastPart.indexOf("/"); String field = null; String partitionBy = null; String partitionId = null; if(index < 0) { field = lastPart; } else { field = lastPart.substring(0, index); String partitionPart = lastPart.substring(index); index = partitionPart.indexOf("/"); if(index < 0) throw new InvalidCommand("Must have two or four '/' characters"); partitionBy = partitionPart.substring(0, index); partitionId = partitionPart.substring(index); } DboTableMeta meta = mgr.find(DboTableMeta.class, cf); if(meta == null) { throw new InvalidCommand("Column family meta not found="+cf); } DboColumnMeta colMeta = meta.getColumnMeta(field); if(colMeta == null) { colMeta = meta.getIdColumnMeta(); if(!(colMeta != null && colMeta.getColumnName().equals(field))) throw new InvalidCommand("Column="+field+" not found on table="+cf); } data.setColFamily(cf); data.setColumn(field); data.setPartitionBy(partitionBy); data.setPartitionId(partitionId); data.setTableMeta(meta); data.setColumnMeta(colMeta); return data; } }
// BUI - a user interface library for the JME 3D engine // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.jmex.bui.layout; import java.util.HashMap; import com.jmex.bui.BComponent; import com.jmex.bui.BContainer; import com.jmex.bui.util.Dimension; /** * Group layout managers lay out widgets in horizontal or vertical groups. */ public abstract class GroupLayout extends BLayoutManager { /** * The group layout managers supports two constraints: fixedness and weight. A fixed component * will not be stretched along the major axis of the group. Those components that are stretched * will have the extra space divided among them according to their weight (specifically * receiving the ratio of their weight to the total weight of all of the free components in the * container). * * <p/> If a constraints object is constructed with fixedness set to true and with a weight, * the weight will be ignored. */ public static class Constraints { /** Whether or not this component is fixed. */ public boolean fixed = false; /** The weight of this component relative to the other components in the container. */ public int weight = 1; /** Constructs a new constraints object with the specified fixedness and weight. */ public Constraints (boolean fixed) { this.fixed = fixed; } /** Constructs a new constraints object with the specified fixedness and weight. */ public Constraints (int weight) { this.weight = weight; } } /** A class used to make our policy constants type-safe. */ public static class Policy { int code; public Policy (int code) { this.code = code; } } /** A class used to make our policy constants type-safe. */ public static class Justification { int code; public Justification (int code) { this.code = code; } } /** The default gap used by a group layout. */ public static final int DEFAULT_GAP = 5; /** * A constraints object that indicates that the component should be fixed and have the default * weight of one. This is so commonly used that we create and make this object available here. */ public final static Constraints FIXED = new Constraints(true); /** Do not adjust the widgets on this axis. */ public final static Policy NONE = new Policy(0); /** Stretch all the widgets to their maximum possible size on this axis. */ public final static Policy STRETCH = new Policy(1); /** Stretch all the widgets to be equal to the size of the largest widget on this axis. */ public final static Policy EQUALIZE = new Policy(2); /** * Only valid for off-axis policy, this leaves widgets alone unless they are larger in the * off-axis direction than their container, in which case it constrains them to fit on the * off-axis. */ public final static Policy CONSTRAIN = new Policy(3); /** A justification constant. */ public final static Justification CENTER = new Justification(0); /** A justification constant. */ public final static Justification LEFT = new Justification(1); /** A justification constant. */ public final static Justification RIGHT = new Justification(2); /** A justification constant. */ public final static Justification TOP = new Justification(3); /** A justification constant. */ public final static Justification BOTTOM = new Justification(4); public GroupLayout setPolicy (Policy policy) { _policy = policy; return this; } public Policy getPolicy () { return _policy; } public GroupLayout setOffAxisPolicy (Policy offpolicy) { _offpolicy = offpolicy; return this; } public Policy getOffAxisPolicy () { return _offpolicy; } public GroupLayout setGap (int gap) { _gap = gap; return this; } public int getGap () { return _gap; } public GroupLayout setJustification (Justification justification) { _justification = justification; return this; } public Justification getJustification () { return _justification; } public GroupLayout setOffAxisJustification (Justification justification) { _offjust = justification; return this; } public Justification getOffAxisJustification () { return _offjust; } // documentation inherited from interface public void addLayoutComponent (BComponent comp, Object constraints) { if (constraints != null) { if (constraints instanceof Constraints) { if (_constraints == null) { _constraints = new HashMap<BComponent, Object>(); } _constraints.put(comp, constraints); } else { throw new RuntimeException( "GroupLayout constraints object must be of type GroupLayout.Constraints"); } } } // documentation inherited from interface public void removeLayoutComponent (BComponent comp) { if (_constraints != null) { _constraints.remove(comp); } } protected boolean isFixed (BComponent child) { if (_constraints == null) { return false; } Constraints c = (Constraints)_constraints.get(child); if (c != null) { return c.fixed; } return false; } protected int getWeight (BComponent child) { if (_constraints == null) { return 1; } Constraints c = (Constraints)_constraints.get(child); if (c != null) { return c.weight; } return 1; } /** * Computes dimensions of the children widgets that are useful for the group layout managers. */ protected DimenInfo computeDimens (BContainer parent, boolean horiz, int whint, int hhint) { int count = parent.getComponentCount(); DimenInfo info = new DimenInfo(); info.dimens = new Dimension[count]; // first compute the dimensions of our fixed children (to which we pass the width and // height hints straight through because they can theoretically take up the whole size) for (int ii = 0; ii < count; ii++) { BComponent child = parent.getComponent(ii); if (!child.isVisible()) { continue; } // we need to count all of our visible children first info.count++; if (!isFixed(child)) { continue; } Dimension csize = computeChildDimens(info, ii, child, whint, hhint); info.fixwid += csize.width; info.fixhei += csize.height; info.numfix++; info.dimens[ii] = csize; } // if we have no fixed components, stop here if (info.numfix == info.count) { return info; } // if we're stretching, divide up the remaining space (minus gaps) and let the free // children know what they're getting when we first ask them for their preferred size if (_policy == STRETCH) { if (horiz) { if (whint > 0) { int owhint = whint; whint -= (info.fixwid + _gap * (info.count-1)); whint /= (info.count - info.numfix); } } else { if (hhint > 0) { hhint -= (info.fixhei + _gap * (info.count-1)); hhint /= (info.count - info.numfix); } } } for (int ii = 0; ii < count; ii++) { BComponent child = parent.getComponent(ii); if (!child.isVisible() || isFixed(child)) { continue; } Dimension csize = computeChildDimens(info, ii, child, whint, hhint); info.totweight += getWeight(child); if (csize.width > info.maxfreewid) { info.maxfreewid = csize.width; } if (csize.height > info.maxfreehei) { info.maxfreehei = csize.height; } info.dimens[ii] = csize; } return info; } /** * A helper function for {@link #computeDimens}. */ protected Dimension computeChildDimens ( DimenInfo info, int ii, BComponent child, int whint, int hhint) { Dimension csize = child.getPreferredSize(whint, hhint); info.totwid += csize.width; info.tothei += csize.height; if (csize.width > info.maxwid) { info.maxwid = csize.width; } if (csize.height > info.maxhei) { info.maxhei = csize.height; } return csize; } /** * Convenience method for creating a horizontal group layout manager. */ public static GroupLayout makeHoriz ( Policy policy, Justification justification, Policy offpolicy) { HGroupLayout lay = new HGroupLayout(); lay.setPolicy(policy); lay.setJustification(justification); lay.setOffAxisPolicy(offpolicy); return lay; } /** * Convenience method for creating a vertical group layout manager. */ public static GroupLayout makeVert ( Policy policy, Justification justification, Policy offpolicy) { VGroupLayout lay = new VGroupLayout(); lay.setPolicy(policy); lay.setJustification(justification); lay.setOffAxisPolicy(offpolicy); return lay; } /** * Convenience method for creating a horizontal group layout manager. */ public static GroupLayout makeHoriz (Justification justification) { HGroupLayout lay = new HGroupLayout(); lay.setJustification(justification); return lay; } /** * Convenience method for creating a vertical group layout manager. */ public static GroupLayout makeVert (Justification justification) { VGroupLayout lay = new VGroupLayout(); lay.setJustification(justification); return lay; } /** * Convenience method for creating a horizontal group layout manager * that stretches in both directions. */ public static GroupLayout makeHStretch () { HGroupLayout lay = new HGroupLayout(); lay.setPolicy(STRETCH); lay.setOffAxisPolicy(STRETCH); return lay; } /** * Convenience method for creating a vertical group layout manager * that stretches in both directions. */ public static GroupLayout makeVStretch () { VGroupLayout lay = new VGroupLayout(); lay.setPolicy(STRETCH); lay.setOffAxisPolicy(STRETCH); return lay; } /** * Makes a container configured with a horizontal group layout manager. */ public static BContainer makeHBox (Justification justification) { HGroupLayout lay = new HGroupLayout(); lay.setJustification(justification); return new BContainer(lay); } /** * Makes a horizontal box of components that uses the supplied (on-axis) justification. */ public static BContainer makeHBox (Justification justification, BComponent ... comps) { BContainer cont = makeHBox(justification); for (BComponent comp : comps) { cont.add(comp); } return cont; } /** * Creates a container configured with a vertical group layout manager. */ public static BContainer makeVBox (Justification justification) { VGroupLayout lay = new VGroupLayout(); lay.setJustification(justification); return new BContainer(lay); } /** * Makes a vertical box of components that uses the supplied (on-axis) justification. */ public static BContainer makeVBox (Justification justification, BComponent ... comps) { BContainer cont = makeVBox(justification); for (BComponent comp : comps) { cont.add(comp); } return cont; } protected Policy _policy = NONE; protected Policy _offpolicy = CONSTRAIN; protected int _gap = DEFAULT_GAP; protected Justification _justification = CENTER; protected Justification _offjust = CENTER; protected HashMap<BComponent, Object> _constraints; }
package com.scylladb.tools; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.cassandra.io.sstable.format.SSTableReader.openForBatch; import static org.apache.cassandra.utils.UUIDGen.getUUID; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.ClusteringPrefix; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.DeletionTime; import org.apache.cassandra.db.LivenessInfo; import org.apache.cassandra.db.RangeTombstone.Bound; import org.apache.cassandra.db.Slice; import org.apache.cassandra.db.context.CounterContext; import org.apache.cassandra.db.marshal.AbstractCompositeType; import org.apache.cassandra.db.marshal.AbstractType; import org.apache.cassandra.db.marshal.CollectionType; import org.apache.cassandra.db.rows.Cell; import org.apache.cassandra.db.rows.ColumnData; import org.apache.cassandra.db.rows.ComplexColumnData; import org.apache.cassandra.db.rows.RangeTombstoneBoundMarker; import org.apache.cassandra.db.rows.RangeTombstoneMarker; import org.apache.cassandra.db.rows.Row; import org.apache.cassandra.db.rows.Row.Deletion; import org.apache.cassandra.db.rows.Unfiltered; import org.apache.cassandra.db.rows.UnfilteredRowIterator; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.io.sstable.Component; import org.apache.cassandra.io.sstable.Descriptor; import org.apache.cassandra.io.sstable.ISSTableScanner; import org.apache.cassandra.io.sstable.SSTable; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.utils.Pair; import org.apache.cassandra.utils.UUIDGen; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Multimap; import com.google.common.collect.MultimapBuilder; /** * Basic sstable -> CQL statements translator. * * Goes through a table, in token range order if possible, and tries to generate * CQL delete/update statements to match the perceived sstable atom cells read. * * This works fairly ok for most normal types, as well as frozen collections. * However, it breaks down completely for non-frozen lists. * * In cassandra, a list is stored as actually a "map" of time UUID -> value. * Since maps in turn are just prefixed thrift column names (the key is part of * column name), UUID sorting makes sure the list remains in order. However, * actually determining what is index 0, 1, 2 etc cannot be done until the whole * list is materialized (reading backwards etc yadayada). Since we a.) Read * forwards b.) Might not be reading all relevant sstables we have no idea what * is actually in the CQL list. Thus we cannot generate any of the valid * expressions to manipulate the list in question. * * As a "workaround", the code will instead generate map expressions, using the * actual time UUID keys for all list ops. This is of course bogus, and indeed * will result in wild errors from for example Origin getting any such * statements. * * Compact storage column families are not handled yet. * */ public class SSTableToCQL { /** * SSTable row worker. * * @author calle * */ private static class RowBuilder { /** Interface for partial generating CQL statements */ private static interface ColumnOp { boolean canDoInsert(); String apply(ColumnDefinition c, List<Object> params); } private static class DeleteSetEntry implements ColumnOp { private final Object key; public DeleteSetEntry(Object key) { this.key = key; } @Override public String apply(ColumnDefinition c, List<Object> params) { params.add(Collections.singleton(key)); return " = " + c.name.toCQLString() + " - ?"; } @Override public boolean canDoInsert() { return false; } } // CQL operations private static enum Op { NONE, UPDATE, DELETE, INSERT } private static class SetColumn implements ColumnOp { private final Object value; public SetColumn(Object value) { this.value = value; } @Override public String apply(ColumnDefinition c, List<Object> params) { params.add(value); return " = ?"; } @Override public boolean canDoInsert() { return true; } } private static final SetColumn SET_NULL = new SetColumn(null) { @Override public boolean canDoInsert() { return false; } }; private static class SetMapEntry implements ColumnOp { private final Object key; private final Object value; public SetMapEntry(Object key, Object value) { this.key = key; this.value = value; } @Override public String apply(ColumnDefinition c, List<Object> params) { params.add(key); params.add(value); return "[?] = ?"; } @Override public boolean canDoInsert() { return false; } } private static class SetListEntry implements ColumnOp { private final Object key; private final Object value; public SetListEntry(Object key, Object value) { this.key = key; this.value = value; } @Override public String apply(ColumnDefinition c, List<Object> params) { params.add(key); params.add(value); return "[SCYLLA_TIMEUUID_LIST_INDEX(?)] = ?"; } @Override public boolean canDoInsert() { return false; } } private static class SetSetEntry implements ColumnOp { private final Object key; public SetSetEntry(Object key) { this.key = key; } @Override public String apply(ColumnDefinition c, List<Object> params) { params.add(Collections.singleton(key)); return " = " + c.name.toCQLString() + " + ?"; } @Override public boolean canDoInsert() { return false; } } private static class SetCounterEntry implements ColumnOp { private final AbstractType<?> type; private final ByteBuffer value; SetCounterEntry(AbstractType<?> type, ByteBuffer value) { this.type = type; this.value = value; } @Override public boolean canDoInsert() { return false; } @Override public String apply(ColumnDefinition c, List<Object> params) { CounterContext.ContextState state = CounterContext.ContextState.wrap(value); StringBuilder buf = new StringBuilder(); while (state.hasRemaining()) { if (buf.length() != 0) { buf.append(", "); } int type = 'r'; if (state.isGlobal()) { type = 'g'; } if (state.isLocal()) { type = 'l'; } buf.append('(').append(type).append(',').append(getUUID(state.getCounterId().bytes())).append(',') .append(state.getClock()).append(',').append(state.getCount()).append(')'); state.moveToNext(); } return " = SCYLLA_COUNTER_SHARD_LIST([" + buf.toString() + "])"; } } private static final long invalidTimestamp = LivenessInfo.NO_TIMESTAMP; private static final int invalidTTL = LivenessInfo.NO_TTL; private final Client client; Op op; Object callback; CFMetaData cfMetaData; DecoratedKey key; Row row; boolean rowDelete; long timestamp; int ttl; Multimap<ColumnDefinition, ColumnOp> values = MultimapBuilder.treeKeys().arrayListValues(1).build(); Multimap<ColumnDefinition, Pair<Comp, Object>> where = MultimapBuilder.treeKeys().arrayListValues(2).build(); enum Comp { Equal("="), GreaterEqual(">="), Greater(">"), LessEqual("<="), Less("<"), ; private String s; private Comp(String s) { this.s = s; } public String toString() { return s; } } // sorted atoms? public RowBuilder(Client client) { this.client = client; } /** * Figure out the "WHERE" clauses (except for PK) for a column name * * @param composite * Thrift/cassandra name composite * @param timestamp * @param ttl */ private void setWhere(Slice.Bound start, Slice.Bound end) { assert where.isEmpty(); ClusteringPrefix spfx = start.clustering(); ClusteringPrefix epfx = end.clustering(); List<ColumnDefinition> clusteringColumns = cfMetaData.clusteringColumns(); for (int i = 0; i < clusteringColumns.size(); i++) { ColumnDefinition column = clusteringColumns.get(i); Object sval = i < spfx.size() ? column.cellValueType().compose(spfx.get(i)) : null; Object eval = spfx != epfx ? (i < epfx.size() ? column.cellValueType().compose(epfx.get(i)) : null) : sval; if (sval == null && eval == null) { // nothing. } else if (sval != null && (sval == eval || sval.equals(eval))) { assert start.isInclusive(); where.put(column, Pair.create(Comp.Equal, sval)); } else { if (column.isPrimaryKeyColumn()) { // cannot generate <> for pk columns throw new IllegalStateException("Cannot generate <> comparison for primary key colum " + column); } if (sval != null) { where.put(column, Pair.create( start.isInclusive() ? Comp.GreaterEqual : Comp.Greater, sval)); } if (eval != null) { where.put(column, Pair.create( end.isInclusive() ? Comp.LessEqual : Comp.Less, eval)); } } } } // Begin a new partition (cassandra "Row") private void begin(Object callback, DecoratedKey key, CFMetaData cfMetaData) { this.callback = callback; this.key = key; this.cfMetaData = cfMetaData; clear(); } private void beginRow(Row row) { where.clear(); this.row = row; } private void endRow() { this.row = null; this.rowDelete = false; } private void clear() { op = Op.NONE; values.clear(); where.clear(); timestamp = invalidTimestamp; ttl = invalidTTL; } // Delete the whole cql row void deleteCqlRow(Bound start, Bound end, long timestamp) { if (!values.isEmpty()) { finish(); } setOp(Op.DELETE, timestamp, invalidTTL); setWhere(start, end); finish(); } // Delete the whole partition private void deletePartition(DecoratedKey key, DeletionTime topLevelDeletion) { setOp(Op.DELETE, topLevelDeletion.markedForDeleteAt(), invalidTTL); finish(); }; // Genenerate the CQL query for this CQL row private void finish() { // Nothing? if (op == Op.NONE) { clear(); return; } checkRowClustering(); List<Object> params = new ArrayList<>(); StringBuilder buf = new StringBuilder(); buf.append(op.toString()); if (op == Op.UPDATE) { writeColumnFamily(buf); // Timestamps can be sent using statement options. // TTL cannot. But just to be extra funny, at least // origin does not seem to respect the timestamp // in statement, so we'll add them to the CQL string as well. writeUsingTimestamp(buf, params); writeUsingTTL(buf, params); buf.append(" SET "); } if (op == Op.INSERT) { buf.append(" INTO"); writeColumnFamily(buf); } int i = 0; for (Map.Entry<ColumnDefinition, ColumnOp> e : values.entries()) { ColumnDefinition c = e.getKey(); ColumnOp o = e.getValue(); String s = o != null ? o.apply(c, params) : null; if (op != Op.INSERT) { if (i++ > 0) { buf.append(", "); } ensureWhitespace(buf); buf.append(c.name.toCQLString()); if (s != null) { buf.append(s); } } } if (op == Op.DELETE) { buf.append(" FROM"); writeColumnFamily(buf); writeUsingTimestamp(buf, params); } if (op != Op.INSERT) { buf.append(" WHERE "); } // Add "WHERE pk1 = , pk2 = " List<ColumnDefinition> pk = cfMetaData.partitionKeyColumns(); AbstractType<?> type = cfMetaData.getKeyValidator(); ByteBuffer bufs[]; if (type instanceof AbstractCompositeType) { bufs = ((AbstractCompositeType) type).split(key.getKey()); } else { bufs = new ByteBuffer[] { key.getKey() }; } int k = 0; for (ColumnDefinition c : pk) { where.put(c, Pair.create(Comp.Equal, c.type.compose(bufs[k++]))); } for (Pair<Comp, Object> p : where.values()) { params.add(p.right); } i = 0; if (op == Op.INSERT) { buf.append('('); for (ColumnDefinition c : values.keySet()) { if (i++ > 0) { buf.append(','); } buf.append(c.name.toCQLString()); } for (ColumnDefinition c : where.keySet()) { if (i++ > 0) { buf.append(','); } buf.append(c.name.toCQLString()); } buf.append(") values ("); for (i = 0; i < values.size() + where.size(); ++i) { if (i > 0) { buf.append(','); } buf.append('?'); } buf.append(')'); writeUsingTimestamp(buf, params); writeUsingTTL(buf, params); } else { for (Map.Entry<ColumnDefinition, Pair<Comp, Object>> e : where.entries()) { if (i++ > 0) { buf.append(" AND "); } buf.append(e.getKey().name.toCQLString()); buf.append(' '); buf.append(e.getValue().left.toString()); buf.append(" ?"); } } buf.append(';'); makeStatement(key, timestamp, buf.toString(), params); clear(); } private void writeUsingTTL(StringBuilder buf, List<Object> params) { if (ttl != invalidTTL) { ensureWhitespace(buf); int adjustedTTL = ttl; if (timestamp == invalidTimestamp) { buf.append("USING "); } else { buf.append("AND "); long exp = SECONDS.convert(timestamp, MICROSECONDS) + ttl; long now = SECONDS.convert(System.currentTimeMillis(), MILLISECONDS); if (exp < now) { adjustedTTL = 1; // 0 -> no ttl. 1 should disappear fast enoug } else { adjustedTTL = (int)Math.min(ttl, exp - now); } } buf.append(" TTL ?"); params.add(adjustedTTL); } } private void ensureWhitespace(StringBuilder buf) { if (buf.length() > 0 && !Character.isWhitespace(buf.charAt(buf.length() - 1))) { buf.append(' '); } } private void writeUsingTimestamp(StringBuilder buf, List<Object> params) { if (timestamp != invalidTimestamp) { ensureWhitespace(buf); buf.append("USING TIMESTAMP ?"); params.add(timestamp); } } // Dispatch the CQL private void makeStatement(DecoratedKey key, long timestamp, String what, List<Object> objects) { client.processStatment(callback, key, timestamp, what, objects); } private void process(Row row) { beginRow(row); try { LivenessInfo liveInfo = row.primaryKeyLivenessInfo(); Deletion d = row.deletion(); updateTimestamp(liveInfo.timestamp()); updateTTL(liveInfo.ttl()); for (ColumnData cd : row) { if (cd.column().isSimple()) { process((Cell) cd, liveInfo, null); } else { ComplexColumnData complexData = (ComplexColumnData) cd; for (Cell cell : complexData) { process(cell, liveInfo, null); } } } if (!d.isLive() && d.deletes(liveInfo)) { rowDelete = true; } if (rowDelete) { setOp(Op.DELETE, d.time().markedForDeleteAt(), invalidTTL); } if (row.size() == 0 && !rowDelete && !row.isStatic()) { op = Op.INSERT; } finish(); } finally { endRow(); } } private void checkRowClustering() { if (row == null) { return; } if (!row.isStatic()) { Slice.Bound b = Slice.Bound.inclusiveStartOf(row.clustering().clustering()); Slice.Bound e = Slice.Bound.inclusiveEndOf(row.clustering().clustering()); setWhere(b, e); if (rowDelete && !tombstoneMarkers.isEmpty()) { RangeTombstoneMarker last = tombstoneMarkers.getLast(); Bound start = last.openBound(false); // If we're doing a cql row delete while processing a ranged // tombstone // chain, we're probably dealing with (old, horrble) // sstables with // overlapping tombstones. Since then this row delete was // also a link // in that tombstone chain, add a marker to the current list // being processed. if (start != null && this.cfMetaData.comparator.compare(start, b) < 0) { tombstoneMarkers.add(new RangeTombstoneBoundMarker(e, row.deletion().time())); } } } } // process an actual cell (data or tombstone) private void process(Cell cell, LivenessInfo liveInfo, DeletionTime d) { ColumnDefinition c = cell.column(); if (logger.isTraceEnabled()) { logger.trace("Processing {}", c.name); } AbstractType<?> type = c.type; ColumnOp cop = null; boolean live = !cell.isTombstone() && (d == null || d.isLive()); try { if (cell.path() != null && cell.path().size() > 0) { CollectionType<?> ctype = (CollectionType<?>) type; Object key = ctype.nameComparator().compose(cell.path().get(0)); Object val = live ? cell.column().cellValueType().compose(cell.value()) : null; switch (ctype.kind) { case MAP: cop = new SetMapEntry(key, val); break; case LIST: cop = new SetListEntry(key, val); break; case SET: cop = cell.isTombstone() ? new DeleteSetEntry(key) : new SetSetEntry(key); break; } } else if (live && type.isCounter()) { cop = new SetCounterEntry(type, cell.value()); } else if (live) { cop = new SetColumn(type.compose(cell.value())); } else { cop = SET_NULL; } } catch (Exception e) { logger.error("Could not compose value for " + c.name, e); throw e; } updateColumn(c, cop, cell.timestamp(), cell.ttl()); } // Process an SSTable row (partial partition) private void process(Object callback, UnfilteredRowIterator rows) { CFMetaData cfMetaData = rows.metadata(); DeletionTime deletionTime = rows.partitionLevelDeletion(); DecoratedKey key = rows.partitionKey(); begin(callback, key, cfMetaData); if (!deletionTime.isLive()) { deletePartition(key, deletionTime); return; } Row sr = rows.staticRow(); if (sr != null) { process(sr); } while (rows.hasNext()) { Unfiltered f = rows.next(); switch (f.kind()) { case RANGE_TOMBSTONE_MARKER: process((RangeTombstoneMarker) f); break; case ROW: process((Row)f); break; default: break; } } } private Deque<RangeTombstoneMarker> tombstoneMarkers = new ArrayDeque<>(); private void process(RangeTombstoneMarker tombstone) { Bound end = tombstone.closeBound(false); if (end != null && tombstoneMarkers.isEmpty()) { throw new IllegalStateException("Unexpected tombstone: " + tombstone); } if (end != null && !tombstoneMarkers.isEmpty()) { Bound last = tombstoneMarkers.getLast().closeBound(false); // This can happen if we're adding a tombstone marker but had a // row delete in between. In that case (overlapping tombstones), // we should (I hope) assume that he was really the high // watermark for the chain, and should also be followed by a new // tombstone range. if (last != null && this.cfMetaData.comparator.compare(end, last) < 0) { return; } Bound start = tombstoneMarkers.getFirst().openBound(false); assert start != null; deleteCqlRow(start, end, tombstoneMarkers.getFirst().openDeletionTime(false).markedForDeleteAt()); tombstoneMarkers.clear(); return; } Bound start = tombstone.openBound(false); if (start != null && !tombstoneMarkers.isEmpty()) { RangeTombstoneMarker last = tombstoneMarkers.getLast(); Bound stop = last.closeBound(false); if (stop == null) { throw new IllegalStateException("Unexpected tombstone: " + tombstone); } if (this.cfMetaData.comparator.compare(start, stop) != 0) { deleteCqlRow(tombstoneMarkers.getFirst().openBound(false), stop, tombstoneMarkers.getFirst().openDeletionTime(false).markedForDeleteAt()); tombstoneMarkers.clear(); } } if (start != null) { tombstoneMarkers.add(tombstone); } } // update the CQL operation. If we change, we need // to send the old query. private void setOp(Op op, long timestamp, int ttl) { if (this.op != op) { finish(); assert this.op == Op.NONE; } updateTimestamp(timestamp); updateTTL(ttl); this.op = op; } private boolean canDoInsert() { if (this.op == Op.UPDATE) { return false; } if (this.row != null && this.row.primaryKeyLivenessInfo().timestamp() != timestamp) { return false; } return true; } // add a column value to update. If we already have one for this column, // flush. (Should never happen though, as long as CQL row detection is // valid) private void updateColumn(ColumnDefinition c, ColumnOp object, long timestamp, int ttl) { if (object != null && object.canDoInsert() && canDoInsert()) { setOp(Op.INSERT, timestamp, ttl); } else { setOp(Op.UPDATE, timestamp, ttl); } values.put(c, object); } // Since each CQL query can only have a single // timestamp, we must send old query once we // set a new timestamp private void updateTimestamp(long timestamp) { if (this.timestamp != invalidTimestamp && this.timestamp != timestamp) { finish(); } this.timestamp = timestamp; } private void updateTTL(int ttl) { if (this.ttl != invalidTTL && this.ttl != ttl) { finish(); } this.ttl = ttl; } protected void writeColumnFamily(StringBuilder buf) { buf.append(' '); buf.append(cfMetaData.ksName); buf.append('.'); buf.append(cfMetaData.cfName); buf.append(' '); } } private static final Logger logger = LoggerFactory.getLogger(SSTableToCQL.class); private final Client client; private final String keyspace; public SSTableToCQL(String keyspace, Client client) { this.client = client; this.keyspace = keyspace; } private CFMetaData getCFMetaData(String keyspace, String cfName) { return client.getCFMetaData(keyspace, cfName); } protected Collection<SSTableReader> openSSTables(File directoryOrSStable) { logger.info("Opening sstables and calculating sections to stream"); final List<SSTableReader> sstables = new ArrayList<>(); if (!directoryOrSStable.isDirectory()) { addFile(sstables, directoryOrSStable.getParentFile(), directoryOrSStable.getName()); } else { directoryOrSStable.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (new File(dir, name).isDirectory()) { return false; } addFile(sstables, dir, name); return false; } }); } return sstables; } private void addFile(final List<SSTableReader> sstables, File dir, String name) { Pair<Descriptor, Component> p = SSTable.tryComponentFromFilename(dir, name); Descriptor desc = p == null ? null : p.left; if (p == null || !p.right.equals(Component.DATA)) { return; } if (!new File(desc.filenameFor(Component.PRIMARY_INDEX)).exists()) { logger.info("Skipping file {} because index is missing", name); return; } CFMetaData metadata = getCFMetaData(keyspace, desc.cfname); if (metadata == null) { logger.info("Skipping file {}: column family {}.{} doesn't exist", name, keyspace, desc.cfname); return; } Set<Component> components = new HashSet<>(); components.add(Component.DATA); components.add(Component.PRIMARY_INDEX); if (new File(desc.filenameFor(Component.SUMMARY)).exists()) { components.add(Component.SUMMARY); } if (new File(desc.filenameFor(Component.COMPRESSION_INFO)).exists()) { components.add(Component.COMPRESSION_INFO); } if (new File(desc.filenameFor(Component.STATS)).exists()) { components.add(Component.STATS); } try { // To conserve memory, open SSTableReaders without bloom // filters and discard // the index summary after calculating the file sections to // stream and the estimated // number of keys for each endpoint. See CASSANDRA-5555 for // details. SSTableReader sstable = openForBatch(desc, components, metadata); sstables.add(sstable); } catch (IOException e) { logger.warn("Skipping file {}, error opening it: {}", name, e.getMessage()); } } protected void process(RowBuilder builder, InetAddress address, ISSTableScanner scanner) { // collecting keys to export while (scanner.hasNext()) { UnfilteredRowIterator ri = scanner.next(); builder.process(address, ri); } } public void stream(File directoryOrSStable) throws IOException, ConfigurationException { RowBuilder builder = new RowBuilder(client); logger.info("Opening sstables and calculating sections to stream"); // Hack. Must do because Range mangling code in cassandra is // broken, and does not preserve input range objects internal // "partitioner" field. DatabaseDescriptor.setPartitionerUnsafe(client.getPartitioner()); Map<InetAddress, Collection<Range<Token>>> ranges = client.getEndpointRanges(); Collection<SSTableReader> sstables = openSSTables(directoryOrSStable); try { for (SSTableReader reader : sstables) { logger.info("Processing {}", reader.getFilename()); if (ranges == null || ranges.isEmpty()) { ISSTableScanner scanner = reader.getScanner(); try { process(builder, null, scanner); } finally { scanner.close(); } } else { for (Map.Entry<InetAddress, Collection<Range<Token>>> e : ranges.entrySet()) { ISSTableScanner scanner = reader.getScanner(e.getValue(), null); try { process(builder, e.getKey(), scanner); } finally { scanner.close(); } } } } } finally { client.finish(); } } }
package jade.domain; //#MIDP_EXCLUDE_FILE //#APIDOC_EXCLUDE_FILE import jade.core.Agent; import jade.core.CaseInsensitiveString; import jade.content.onto.OntologyException; import jade.content.lang.Codec.CodecException; import jade.content.onto.basic.Action; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import jade.proto.SimpleAchieveREResponder; import jade.domain.FIPAException; import jade.domain.FIPAAgentManagement.FailureException; import jade.domain.FIPAAgentManagement.RefuseException; import jade.domain.FIPAAgentManagement.UnsupportedValue; import jade.domain.FIPAAgentManagement.NotUnderstoodException; import jade.security.AuthException; import jade.domain.FIPAAgentManagement.ExceptionVocabulary; /** Base class for AMS and DF behaviours managing requests from agents. This class handles the FIPA-request protocol and in particular prepares the response taking into account all possible exceptions. The preparation of the result notification is delegated to subclasses as its form (RESULT or DONE) and sending time (i.e. whether it can be sent immediately or must be delayed at a later time) depends on the specific action. @author Giovanni Caire - Tilab */ public abstract class RequestManagementBehaviour extends SimpleAchieveREResponder { private ACLMessage notification; protected RequestManagementBehaviour(Agent a, MessageTemplate mt){ super(a,mt); } protected abstract ACLMessage performAction(Action slAction, ACLMessage request) throws AuthException, FIPAException; /** * @return null when the AGREE message can be skipper, the AGREE message * otherwise. */ protected ACLMessage prepareResponse(ACLMessage request) throws NotUnderstoodException, RefuseException { ACLMessage response = null; try{ // Check the language is SL0, SL1, SL2 or SL. isAnSLRequest(request); // Extract the content Action slAction = (Action) myAgent.getContentManager().extractContent(request); // Perform the action notification = performAction(slAction, request); // Action OK } catch (OntologyException oe) { // Error decoding request --> NOT_UNDERSTOOD response = request.createReply(); response.setPerformative(ACLMessage.NOT_UNDERSTOOD); response.setContent("("+ExceptionVocabulary.UNRECOGNISEDVALUE+" content)"); } catch (CodecException ce) { // Error decoding request --> NOT_UNDERSTOOD response = request.createReply(); response.setPerformative(ACLMessage.NOT_UNDERSTOOD); response.setContent("("+ExceptionVocabulary.UNRECOGNISEDVALUE+" content)"); } catch (RefuseException re) { // RefuseException thrown during action execution --> REFUSE response = request.createReply(); response.setPerformative(ACLMessage.REFUSE); response.setContent(prepareErrorContent(request.getContent(), re.getMessage())); } catch (FailureException fe) { // FailureException thrown during action execution --> FAILURE notification = request.createReply(); notification.setPerformative(ACLMessage.FAILURE); notification.setContent(prepareErrorContent(request.getContent(), fe.getMessage())); } catch(FIPAException fe){ // Malformed request --> NOT_UNDERSTOOD response = request.createReply(); response.setPerformative(ACLMessage.NOT_UNDERSTOOD); response.setContent("("+fe.getMessage()+")"); } catch(Throwable t){ t.printStackTrace(); // Generic error --> FAILURE notification = request.createReply(); notification.setPerformative(ACLMessage.FAILURE); notification.setContent(prepareErrorContent(request.getContent(), ExceptionVocabulary.INTERNALERROR+" \""+t.getMessage()+"\"")); } return response; } /** Just return the (already prepared) notification message (if any). */ protected ACLMessage prepareResultNotification(ACLMessage request, ACLMessage response) throws FailureException{ return notification; } //to reset the action public void reset(){ super.reset(); notification = null; } private void isAnSLRequest(ACLMessage msg) throws FIPAException { String language = msg.getLanguage(); if ( (!CaseInsensitiveString.equalsIgnoreCase(FIPANames.ContentLanguage.FIPA_SL0, language)) && (!CaseInsensitiveString.equalsIgnoreCase(FIPANames.ContentLanguage.FIPA_SL1, language)) && (!CaseInsensitiveString.equalsIgnoreCase(FIPANames.ContentLanguage.FIPA_SL2, language)) && (!CaseInsensitiveString.equalsIgnoreCase(FIPANames.ContentLanguage.FIPA_SL, language))) { throw new UnsupportedValue("language"); } } private String prepareErrorContent(String content, String e) { String tmp = content.trim(); tmp = tmp.substring(1, tmp.length()-1); return "("+tmp+" "+e+")"; } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util; import java.net.URL; import com.samskivert.util.ResultListener; import com.samskivert.util.RunAnywhere; import com.samskivert.util.StringUtil; import static com.threerings.NenyaLog.log; /** * Encapsulates a bunch of hackery needed to invoke an external web browser * from within a Java application. */ public class BrowserUtil { /** * Opens the user's web browser with the specified URL. * * @param url the URL to display in an external browser. * @param listener a listener to be notified if we failed to launch the * browser. <em>Note:</em> it will not be notified of success. */ public static void browseURL (URL url, ResultListener listener) { browseURL(url, listener, "firefox"); } /** * Opens the user's web browser with the specified URL. * * @param url the URL to display in an external browser. * @param listener a listener to be notified if we failed to launch the * browser. <em>Note:</em> it will not be notified of success. * @param genagent the path to the browser to execute on non-Windows, * non-MacOS. */ public static void browseURL ( URL url, ResultListener listener, String genagent) { String[] cmd; if (RunAnywhere.isWindows()) { // TODO: test this on Vinders 98 // cmd = new String[] { "rundll32", "url.dll,FileProtocolHandler", // url.toString() }; String osName = System.getProperty("os.name"); if (osName.indexOf("9") != -1 || osName.indexOf("Me") != -1) { cmd = new String[] { "command.com", "/c", "start", "\"" + url.toString() + "\"" }; } else { cmd = new String[] { "cmd.exe", "/c", "start", "\"\"", "\"" + url.toString() + "\"" }; } } else if (RunAnywhere.isMacOS()) { cmd = new String[] { "open", url.toString() }; } else { // Linux, Solaris, etc cmd = new String[] { genagent, url.toString() }; } // obscure any password information String logcmd = StringUtil.join(cmd, " "); logcmd = logcmd.replaceAll("password=[^&]*", "password=XXX"); log.info("Browsing URL [cmd=" + logcmd + "]."); try { Process process = Runtime.getRuntime().exec(cmd); BrowserTracker tracker = new BrowserTracker(process, url, listener); tracker.start(); } catch (Exception e) { log.warning("Failed to launch browser [url=" + url + ", error=" + e + "]."); listener.requestFailed(e); } } protected static class BrowserTracker extends Thread { public BrowserTracker (Process process, URL url, ResultListener rl) { super("BrowserLaunchWaiter"); setDaemon(true); _process = process; _url = url; _listener = rl; } public void run () { try { _process.waitFor(); int rv = _process.exitValue(); if (rv == 0) { return; } String errmsg = "Launched browser failed [rv=" + rv + "]."; log.warning(errmsg); if (!RunAnywhere.isWindows()) { _listener.requestFailed(new Exception(errmsg)); return; } // if we're on windows, make a last ditch effort String[] cmd = new String[] { "C:\\Program Files\\Internet Explorer\\" + "IEXPLORE.EXE", "\"" + _url.toString() + "\""}; Process process = Runtime.getRuntime().exec(cmd); process.waitFor(); rv = process.exitValue(); if (rv != 0) { errmsg = "Failed to launch iexplore.exe [rv=" + rv + "]."; log.warning(errmsg); _listener.requestFailed(new Exception(errmsg)); } } catch (Exception e) { _listener.requestFailed(e); } } protected Process _process; protected URL _url; protected ResultListener _listener; }; }
package org.xins.common.xml; import java.awt.Color; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import org.xins.common.io.IOReader; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.Utils; import org.xins.common.text.ParseException; public class Viewer extends JTextPane { /** * Flag to indicate whether the received XML should be indented or left as is. */ private boolean indentXML; /** * Constructs a new <code>Viewer</code>. */ public Viewer() { indentXML = true; } public void parse(String text) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("text", text); setText(""); // Write the headers if (text.substring(0, 2).equals("<?")) { appendText(text.substring(0, text.indexOf(">")+1) + "\n", null); } try { parse(new StringReader(text)); } catch (ParseException pe) { setText(text); } catch (IOException ioe) { setText(text); } } public void parse(InputStream in) throws IllegalArgumentException, IOException { // Check preconditions MandatoryArgumentChecker.check("in", in); String text = IOReader.readFully(in); parse(text); } private void parse(Reader in) throws IllegalArgumentException, IOException, ParseException { // Check preconditions MandatoryArgumentChecker.check("in", in); // Wrap the Reader in a SAX InputSource object InputSource source = new InputSource(in); // Initialize our SAX event handler Handler handler = new Handler(); try { // Let SAX parse the XML, using our handler SAXParserProvider.get().parse(source, handler); } catch (SAXException exception) { // TODO: Log: Parsing failed String exMessage = exception.getMessage(); // Construct complete message String message = "Failed to parse XML"; // Throw exception with message, and register cause exception throw new ParseException(message, exception, exMessage); } } /** * Indicate whether to indent the XML or leave it as received. * * @param indentXML * <code>true<code> if the XML should be indented, <code>false</code> otherwise. */ public void setIndentation(boolean indentXML) { this.indentXML = indentXML; } /** * Append text at the end of the document. * * @param text * the text to append, cannot be <code>null</code>. * * @param style * the style in which the text should appear, can be <code>null</code> */ public void appendText(String text, Style style) { try { getDocument().insertString(getDocument().getLength(), text, style); } catch (BadLocationException ble) { } } /** * SAX event handler that will parse XML. * * @version $Revision$ $Date$ * @author <a href="mailto:anthony.goubard@orange-ftgroup.com">Anthony Goubard</a> * @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a> */ private class Handler extends DefaultHandler { /** * The styles used for the syntax highlighting. */ private Style elementStyle; private Style attrNameStyle; private Style attrValueStyle; private Style contentStyle; /** * The level for the element pointer within the XML document. Initially * this field is <code>-1</code>, which indicates the current element * pointer is outside the document. The value <code>0</code> is for the * root element (<code>result</code>), etc. */ private int _level; /** * Flag indicating whether the current element sub-elements (<code>true</code>) * or not (<code>false</code>). */ private boolean _hasSubElement; /** * Constructs a new <code>Handler</code> instance. */ private Handler() { _level = -1; _hasSubElement = false; // Define the style needed elementStyle = addStyle("Element", null); StyleConstants.setForeground(elementStyle, Color.BLUE.darker()); attrNameStyle = addStyle("AttrName", null); StyleConstants.setForeground(attrNameStyle, Color.GREEN.darker()); attrValueStyle = addStyle("AttrValue", null); StyleConstants.setForeground(attrValueStyle, Color.RED.darker()); contentStyle = addStyle("Content", null); StyleConstants.setForeground(contentStyle, Color.BLACK); } public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws IllegalArgumentException, SAXException { // Make sure namespaceURI is either null or non-empty namespaceURI = "".equals(namespaceURI) ? null : namespaceURI; // Increase the element depth level _level++; _hasSubElement = false; indent(); appendText("<", null); appendText(qName, elementStyle); // Find the namespace prefix String prefixNS = null; if (qName != null && qName.indexOf(':') != -1) { prefixNS = "xmlns:" + qName.substring(0, qName.indexOf(':')); } else { prefixNS = "xmlns"; } if (namespaceURI != null) { appendText(" " + prefixNS, attrNameStyle); appendText("=\"", null); appendText(namespaceURI, attrValueStyle); appendText("\"", null); } // Add all attributes for (int i = 0; i < atts.getLength(); i++) { String attrValue = atts.getValue(i); String attrQName = atts.getQName(i); appendText(" " + attrQName, attrNameStyle); appendText("=\"", null); appendText(attrValue, attrValueStyle); appendText("\"", null); } appendText(">", null); } public void endElement(String namespaceURI, String localName, String qName) throws IllegalArgumentException { if (_hasSubElement) { indent(); } appendText("</", null); appendText(qName, elementStyle); appendText(">", null); _level _hasSubElement = true; } /** * Receive notification of character data. * * @param ch * the <code>char</code> array that contains the characters from the * XML document, cannot be <code>null</code>. * * @param start * the start index within <code>ch</code>. * * @param length * the number of characters to take from <code>ch</code>. * * @throws IndexOutOfBoundsException * if characters outside the allowed range are specified. * * @throws SAXException * if the parsing failed. */ public void characters(char[] ch, int start, int length) throws IndexOutOfBoundsException, SAXException { appendText(new String(ch, start, length), contentStyle); } public InputSource resolveEntity(String publicId, String systemId) { return new InputSource(new ByteArrayInputStream(new byte[0])); } /** * Indent if needed. */ private void indent() { if (indentXML) { String indentation = "\n"; for (int i = 0; i < _level; i++) { indentation += "\t"; } appendText(indentation, null); } } } }
package org.spine3.server.storage; import com.google.common.base.Optional; import com.google.protobuf.Any; import com.google.protobuf.FieldMask; import com.google.protobuf.Message; import org.spine3.protobuf.AnyPacker; import org.spine3.server.entity.EntityRecord; import org.spine3.server.entity.FieldMasks; import org.spine3.server.entity.LifecycleFlags; import org.spine3.server.entity.storage.EntityQuery; import org.spine3.server.entity.storage.EntityRecordWithColumns; import org.spine3.server.stand.AggregateStateId; import org.spine3.type.TypeUrl; import java.util.Map; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static org.spine3.base.Identifiers.idToString; import static org.spine3.util.Exceptions.newIllegalStateException; /** * A storage keeping messages with identity. * * @param <I> the type of entity IDs * @author Alexander Yevsyukov */ public abstract class RecordStorage<I> extends AbstractStorage<I, EntityRecord> implements StorageWithLifecycleFlags<I, EntityRecord>, BulkStorageOperationsMixin<I, EntityRecord> { protected RecordStorage(boolean multitenant) { super(multitenant); } /** * {@inheritDoc} */ @Override public Optional<EntityRecord> read(I id) { checkNotClosed(); checkNotNull(id); final Optional<EntityRecord> record = readRecord(id); return record; } /** * Reads a single item from the storage and applies a {@link FieldMask} to it. * * @param id ID of the item to read. * @param fieldMask fields to read. * @return the item with the given ID and with the {@code FieldMask} applied. * @see #read(Object) */ public Optional<EntityRecord> read(I id, FieldMask fieldMask) { final Optional<EntityRecord> rawResult = read(id); if (!rawResult.isPresent()) { return Optional.absent(); } final EntityRecord.Builder builder = EntityRecord.newBuilder(rawResult.get()); final Any state = builder.getState(); final TypeUrl type = TypeUrl.parse(state.getTypeUrl()); final Message stateAsMessage = AnyPacker.unpack(state); final Message maskedState = FieldMasks.applyMask(fieldMask, stateAsMessage, type); final Any packedState = AnyPacker.pack(maskedState); builder.setState(packedState); return Optional.of(builder.build()); } public void write(I id, EntityRecordWithColumns record) { checkNotNull(id); checkArgument(record.getRecord().hasState(), "Record does not have state field."); checkNotClosed(); writeRecord(id, record); } /** * {@inheritDoc} */ @Override public void write(I id, EntityRecord record) { final EntityRecordWithColumns recordWithStorageFields = EntityRecordWithColumns.of(record); write(id, recordWithStorageFields); } public void write(Map<I, EntityRecordWithColumns> records) { checkNotNull(records); checkNotClosed(); writeRecords(records); } @Override public Optional<LifecycleFlags> readLifecycleFlags(I id) { final Optional<EntityRecord> optional = read(id); if (optional.isPresent()) { return Optional.of(optional.get() .getLifecycleFlags()); } return Optional.absent(); } @Override public void writeLifecycleFlags(I id, LifecycleFlags flags) { final Optional<EntityRecord> optional = read(id); if (optional.isPresent()) { final EntityRecord record = optional.get(); final EntityRecord updated = record.toBuilder() .setLifecycleFlags(flags) .build(); write(id, updated); } else { // The AggregateStateId is a special case, which is not handled by the Identifier class. final String idStr = id instanceof AggregateStateId ? id.toString() : idToString(id); throw newIllegalStateException("Unable to load record for entity with ID: %s", idStr); } } /** * Deletes the record with the passed ID. * * @param id the record to delete * @return {@code true} if the operation succeeded, {@code false} otherwise */ public abstract boolean delete(I id); /** * {@inheritDoc} */ @Override public Iterable<EntityRecord> readMultiple(Iterable<I> ids) { checkNotClosed(); checkNotNull(ids); return readMultipleRecords(ids); } /** * Reads multiple items from the storage and apply {@link FieldMask} to each of the results. * * @param ids the IDs of the items to read * @param fieldMask the mask to apply * @return the items with the given IDs and with the given {@code FieldMask} applied */ public Iterable<EntityRecord> readMultiple(Iterable<I> ids, FieldMask fieldMask) { checkNotClosed(); checkNotNull(ids); return readMultipleRecords(ids, fieldMask); } /** * {@inheritDoc} */ @Override public Map<I, EntityRecord> readAll() { checkNotClosed(); return readAllRecords(); } /** * Reads all items from the storage and apply {@link FieldMask} to each of the results. * * @param fieldMask the {@code FieldMask} to apply * @return all items from this repository with the given {@code FieldMask} applied */ public Map<I, EntityRecord> readAll(FieldMask fieldMask) { checkNotClosed(); return readAllRecords(fieldMask); } public Map<I, EntityRecord> readAll(EntityQuery query, FieldMask fieldMask) { checkNotClosed(); checkNotNull(query); checkNotNull(fieldMask); return readAllRecords(query, fieldMask); } // Internal storage methods /** * Reads a record from the storage by the passed ID. * * @param id the ID of the record to load * @return a record instance or {@code null} if there is no record with this ID */ protected abstract Optional<EntityRecord> readRecord(I id); /** @see BulkStorageOperationsMixin#readMultiple(java.lang.Iterable) */ protected abstract Iterable<EntityRecord> readMultipleRecords(Iterable<I> ids); /** @see BulkStorageOperationsMixin#readMultiple(java.lang.Iterable) */ protected abstract Iterable<EntityRecord> readMultipleRecords(Iterable<I> ids, FieldMask fieldMask); /** @see BulkStorageOperationsMixin#readAll() */ protected abstract Map<I, EntityRecord> readAllRecords(); /** @see BulkStorageOperationsMixin#readAll() */ protected abstract Map<I, EntityRecord> readAllRecords(FieldMask fieldMask); protected abstract Map<I, EntityRecord> readAllRecords(EntityQuery query, FieldMask fieldMask); /** * Writes a record and the associated * {@link org.spine3.server.entity.storage.Column Column values} into the storage. * * <p>Rewrites it if a record with this ID already exists in the storage. * * @param id an ID of the record * @param record a record to store */ protected abstract void writeRecord(I id, EntityRecordWithColumns record); /** * Writes a bulk of records into the storage. * * <p>Rewrites it if a record with this ID already exists in the storage. * * @param records an ID to record map with the entries to store */ protected abstract void writeRecords(Map<I, EntityRecordWithColumns> records); }
package edu.uiuc.dprg.morphous; import edu.uiuc.dprg.morphous.MorphousTaskMessageSender.MorphousTask; import edu.uiuc.dprg.morphous.MorphousTaskMessageSender.MorphousTaskCallback; import edu.uiuc.dprg.morphous.MorphousTaskMessageSender.MorphousTaskResponse; import edu.uiuc.dprg.morphous.MorphousTaskMessageSender.MorphousTaskType; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.db.*; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.exceptions.WriteTimeoutException; import org.apache.cassandra.gms.FailureDetector; import org.apache.cassandra.net.MessageOut; import org.apache.cassandra.net.MessagingService; import org.apache.cassandra.service.MigrationManager; import org.apache.cassandra.service.WriteResponseHandler; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.WrappedRunnable; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.util.Collections; import java.util.Map; import java.util.concurrent.*; public class Morphous { public static final int numConcurrentMorphusMutationHandlerThreads = 32; private static Morphous instance = new Morphous(); private static final Logger logger = LoggerFactory.getLogger(Morphous.class); private int numConcurrentRowMutationSenderThreads = 8; private ExecutorService executor; public MorphousConfiguration configuration; private Morphous() { } public static Morphous instance() { return instance; } private long startTimestamp; /** * @param keyspace * @param columnFamily * @param config * @return */ public FutureTask<Object> createAsyncMorphousTask(final String keyspace, final String columnFamily, final MorphousConfiguration config) { startTimestamp = System.currentTimeMillis(); // Record start time logger.info("MorphusTimestamp: MorphusStartAt {}", startTimestamp); logger.debug("Creating a morphous task with keyspace={}, columnFamily={}, configuration={}", keyspace, columnFamily, config); return new FutureTask<Object>(new WrappedRunnable() { @Override protected void runMayThrow() throws Exception { logger.info("Starting morphous command for keyspace {}, column family {}, configuration {}", keyspace, columnFamily, config); try { createTempColumnFamily(keyspace, columnFamily, config.columnName); // Wait until the create table command propagates Thread.sleep(8000); MorphousTask morphousTask = new MorphousTask(); if (config.shouldCompact) { morphousTask.taskType = MorphousTaskType.COMPACT; morphousTask.callback = getCompactMorphousTaskCallback(); } else { morphousTask.taskType = MorphousTaskType.INSERT; morphousTask.callback = getInsertMorphousTaskCallback(); } morphousTask.keyspace = keyspace; morphousTask.columnFamily = columnFamily; morphousTask.newPartitionKey = config.columnName; morphousTask.taskStartedAtInMicro = System.currentTimeMillis() * 1000; morphousTask.numConcurrentRowMutationSenderThreads = config.numMorphusMutationSenderThreads; MorphousTaskMessageSender.instance().sendMorphousTaskToAllEndpoints(morphousTask); } catch(Exception e) { logger.error("Execption occurred {}", e); throw new RuntimeException(e); } } }, null); } public MorphousTaskCallback getCompactMorphousTaskCallback() { return new MorphousTaskCallback() { @Override public void callback(MorphousTask task, Map<InetAddress, MorphousTaskResponse> responses) { logger.info("MorphusTimestamp: CompactMorphusTask {}", System.currentTimeMillis()); logger.info("CompactMorphousTask is over in {}ms (since reconfiguration was started)", System.currentTimeMillis() - startTimestamp); logger.info("CompactMorphousTask is over. Start InsertMorphousTask for keyspace {}, column family {}", task.keyspace, task.columnFamily); try { MorphousTask morphousTask = new MorphousTask(); morphousTask.taskType = MorphousTaskType.INSERT; morphousTask.keyspace = task.keyspace; morphousTask.columnFamily = task.columnFamily; morphousTask.newPartitionKey = task.newPartitionKey; morphousTask.callback = getInsertMorphousTaskCallback(); morphousTask.taskStartedAtInMicro = task.taskStartedAtInMicro; MorphousTaskMessageSender.instance().sendMorphousTaskToAllEndpoints(morphousTask); } catch(Exception e) { logger.error("Execption occurred {}", e); throw new RuntimeException(e); } } }; } public void setWriteLockOnColumnFamily(String ksName, String columnFamily, boolean locked) { logger.info("Locking/Unlocking Keysapce {}, ColumnFamily {}. isLocked = {}", ksName, columnFamily, locked); RowMutation rm = new RowMutation(Keyspace.SYSTEM_KS, SystemKeyspace.getSchemaKSKey(ksName)); ColumnFamily cf = rm.addOrGet(CFMetaData.MorphousStatusCf); long timestamp = FBUtilities.timestampMicros() + 1; cf.addColumn(Column.create("", timestamp, columnFamily, "")); // Since column family name is part of composite key cf.addColumn(Column.create(locked, timestamp, columnFamily, "swapping")); // No need to include keyspace because it's partition key itself Util.invokePrivateMethodWithReflection(MigrationManager.instance, "announce", rm); } /** * Get callback for the InsertMorphousTask. It should generate the next stage MorphousTask. * @return */ public MorphousTaskCallback getInsertMorphousTaskCallback() { return new MorphousTaskCallback() { @Override public void callback(MorphousTask task, Map<InetAddress, MorphousTaskResponse> responses) { logger.info("MorphusTimestamp: InsertMorphusTask {}", System.currentTimeMillis()); logger.info("InsertMorphousTask is over in {}ms (since reconfiguration was started)", System.currentTimeMillis() - startTimestamp); logger.debug("The InsertMorphousTask {} is done! Now doing the next step", task); // Create AtomicSwitchMorphousTask MorphousTask newMorphousTask = new MorphousTask(); newMorphousTask.taskType = MorphousTaskType.ATOMIC_SWITCH; newMorphousTask.keyspace = task.keyspace; newMorphousTask.columnFamily = task.columnFamily; newMorphousTask.newPartitionKey = task.newPartitionKey; newMorphousTask.callback = getAtomicSwitchMorphousTaskCallback(); newMorphousTask.taskStartedAtInMicro = task.taskStartedAtInMicro; Keyspace keyspace = Keyspace.open(task.keyspace); ColumnFamilyStore originalCfs = keyspace.getColumnFamilyStore(task.columnFamily); String originalPartitionKey = getPartitionKeyName(originalCfs); // Put lock on write requests on this column family setWriteLockOnColumnFamily(task.keyspace, task.columnFamily, true); migrateColumnFamilyDefinitionToUseNewPartitonKey(task.keyspace, originalCfs.name, task.newPartitionKey); migrateColumnFamilyDefinitionToUseNewPartitonKey(task.keyspace, tempColumnFamilyName(originalCfs.name), originalPartitionKey); MorphousTaskMessageSender.instance().sendMorphousTaskToAllEndpoints(newMorphousTask); } }; } public MorphousTaskCallback getAtomicSwitchMorphousTaskCallback() { return new MorphousTaskCallback() { @Override public void callback(MorphousTask task, Map<InetAddress, MorphousTaskResponse> responses) { // Unlock write lock on this column family setWriteLockOnColumnFamily(task.keyspace, task.columnFamily, false); logger.info("MorphusTimestamp: AtomicSwitchMorphusTask {}", System.currentTimeMillis()); logger.info("AtomicSwitchMorphousTask is over in {}ms (since reconfiguration was started)", System.currentTimeMillis() - startTimestamp); logger.debug("The AtomicSwitchMorphousTask {} is done! Now doing the next step", task); // Create CatchupMorphousTask MorphousTask newMorphousTask = new MorphousTask(); newMorphousTask.taskType = MorphousTaskType.CATCH_UP; newMorphousTask.keyspace = task.keyspace; newMorphousTask.columnFamily = task.columnFamily; newMorphousTask.newPartitionKey = task.newPartitionKey; newMorphousTask.callback = getCatchupMorphousTaskCallback(); newMorphousTask.taskStartedAtInMicro = task.taskStartedAtInMicro; MorphousTaskMessageSender.instance().sendMorphousTaskToAllEndpoints(newMorphousTask); } }; } public MorphousTaskCallback getCatchupMorphousTaskCallback() { return new MorphousTaskCallback() { @Override public void callback(MorphousTask task, Map<InetAddress, MorphousTaskResponse> responses) { logger.debug("The CatchupMorphousTask {} is done.", task); for (Map.Entry<InetAddress, MorphousTaskResponse> entry : responses.entrySet()) { logger.debug("From: {}, Response : {}", entry.getKey(), entry.getValue()); } logger.info("MorphusTimestamp: CatchupMorphusTask {}", System.currentTimeMillis()); logger.info("CatchupMorphousTask is over in {}ms (since reconfiguration was started)", System.currentTimeMillis() - startTimestamp); } }; } public void createTempColumnFamily(String ksName, String oldCfName, String newPartitionKey) { logger.debug("Creating a temporary column family for changing Column Family {}'s partition key to {}", oldCfName, newPartitionKey); CFMetaData oldCfm = Keyspace.open(ksName).getColumnFamilyStore(oldCfName).metadata; String tempCfName = tempColumnFamilyName(oldCfName); CFMetaData cfm = createNewCFMetaDataFromOldCFMetaDataWithNewCFNameAndNewPartitonKey(oldCfm, tempCfName, newPartitionKey); createNewColumnFamilyWithCFMetaData(cfm); } public static String tempColumnFamilyName(String originalCfName) { return "temp_" + originalCfName; } public static ByteBuffer getPartitionKeyNameByteBuffer(ColumnFamilyStore cfs) { return getPartitionKeyNameByteBuffer(cfs.metadata); } public static ByteBuffer getPartitionKeyNameByteBuffer(CFMetaData metadata) { return ((ByteBuffer) metadata.partitionKeyColumns().get(0).name.asReadOnlyBuffer()); } public static String getPartitionKeyName(ColumnFamilyStore cfs) { String originalPartitionKey = null; try { originalPartitionKey = ByteBufferUtil.string(getPartitionKeyNameByteBuffer(cfs)); return originalPartitionKey; } catch (CharacterCodingException e) { throw new MorphousException("Unable to decode partition key's name", e); } } public MorphousConfiguration parseMorphousConfiguration(String configString) { logger.debug("Parsing Morphous config {}", configString); MorphousConfiguration config = new MorphousConfiguration(); if (configString == null || configString.isEmpty()) { return config; } try { JSONObject json = (JSONObject) new JSONParser().parse(configString); String columnName = (String) json.get("column"); boolean shouldCompact = Boolean.parseBoolean((String) json.get("compact")); int numMorphusMutationSenderThreads = Integer.parseInt((String) json.get("numMorphusMutationSenderThreads")); config.columnName = columnName; config.shouldCompact = shouldCompact; config.numMorphusMutationSenderThreads = numMorphusMutationSenderThreads; } catch (ParseException e) { throw new RuntimeException(e); } return config; } public void createNewColumnFamilyWithCFMetaData(CFMetaData meta) { try { MigrationManager.announceNewColumnFamily(meta); } catch (ConfigurationException e) { throw new RuntimeException("Failed to create new Column Family", e); } } /** Create a new CFMetaData * * @param oldMeta * @param newPartitionKey * @return */ public CFMetaData createNewCFMetaDataFromOldCFMetaDataWithNewCFNameAndNewPartitonKey(CFMetaData oldMeta, String newCfName, String newPartitionKey) { CFMetaData newMeta = new CFMetaData(oldMeta.ksName, newCfName, oldMeta.cfType, oldMeta.comparator); edu.uiuc.dprg.morphous.Util.invokePrivateMethodWithReflection(newMeta, "copyOpts", newMeta, oldMeta); changePartitionKeyOfCFMetaData(newMeta, newPartitionKey); return newMeta; } public void changePartitionKeyOfCFMetaData(CFMetaData meta, String newPartitionKey) { ColumnDefinition newRegularColumn = null; ColumnDefinition newPartitionKeyColumn = null; for (ColumnDefinition columnDefinition : meta.allColumns()) { try { String deserializedColumnName = ByteBufferUtil.string(columnDefinition.name.asReadOnlyBuffer()); logger.debug("ColumnDefinition for column {} : {}", deserializedColumnName, columnDefinition); if (columnDefinition.type == ColumnDefinition.Type.PARTITION_KEY) { // Change old partiton key to regular column newRegularColumn = new ColumnDefinition(columnDefinition.name.asReadOnlyBuffer(), columnDefinition.getValidator(), 0, ColumnDefinition.Type.REGULAR); } else if (deserializedColumnName.equals(newPartitionKey)) { // Change old regular column that matches newPartitionKeyName to new PartitonKey newPartitionKeyColumn = new ColumnDefinition(columnDefinition.name.asReadOnlyBuffer(), columnDefinition.getValidator(), null, ColumnDefinition.Type.PARTITION_KEY); } } catch (CharacterCodingException e) { throw new RuntimeException(e); } } meta.addOrReplaceColumnDefinition(newPartitionKeyColumn); meta.addOrReplaceColumnDefinition(newRegularColumn); } public void migrateColumnFamilyDefinitionToUseNewPartitonKey( String keyspaceName, String columnFamilyName, String newPartitionKeyName) { Keyspace keyspace = Keyspace.open(keyspaceName); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(columnFamilyName); CFMetaData meta = cfs.metadata.clone(); logger.debug("Migrating CFMetaData : {} with new partition key {}", meta, newPartitionKeyName); changePartitionKeyOfCFMetaData(meta, newPartitionKeyName); logger.debug("After changing CFMetaData : {}", meta); CFMetaData oldMeta = cfs.metadata; RowMutation rm = edu.uiuc.dprg.morphous.Util .invokePrivateMethodWithReflection( MigrationManager.instance, "addSerializedKeyspace", oldMeta.toSchemaUpdate(meta, FBUtilities.timestampMicros(), false), keyspaceName); logger.info("About to announce change on partition key with RowMutation = {}", rm); edu.uiuc.dprg.morphous.Util.invokePrivateMethodWithReflection( MigrationManager.instance, "announce", rm); } /** * * @param rm * @param n one-based number that represents what replication order it has */ public void sendRowMutationToNthReplicaNode(final RowMutation rm, final int n) { getExecutor().submit(new WrappedRunnable() { @Override protected void runMayThrow() throws Exception { InetAddress destinationNode = edu.uiuc.dprg.morphous.Util.getNthReplicaNodeForKey(rm.getKeyspaceName(), rm.key(), n); if (FailureDetector.instance.isAlive(destinationNode)) { MessageOut<RowMutation> message = rm.createMessage(MessagingService.Verb.MORPHUS_MUTATION); WriteResponseHandler handler = new WriteResponseHandler(Collections.singletonList(destinationNode), Collections.<InetAddress>emptyList(), ConsistencyLevel.ONE, Keyspace.open(rm.getKeyspaceName()), null, WriteType.SIMPLE); MessagingService.instance().sendRR(message, destinationNode, handler, false); //TODO Maybe use more robust way to send message try { handler.get(); } catch (WriteTimeoutException e) { logger.warn("Write timeout exception for Morphus RowMutation {}", rm); } } } }); } public static class MorphousConfiguration { public String columnName; public boolean shouldCompact; public int numMorphusMutationSenderThreads; @Override public String toString() { return "MorphousConfiguration{" + "columnName='" + columnName + '\'' + ", shouldCompact=" + shouldCompact + ", numMorphusMutationSenderThreads=" + numMorphusMutationSenderThreads + '}'; } } public ExecutorService getExecutor() { if (executor == null) { BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(numConcurrentRowMutationSenderThreads); RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy(); executor = new ThreadPoolExecutor(numConcurrentRowMutationSenderThreads, numConcurrentRowMutationSenderThreads, 0L, TimeUnit.MILLISECONDS, blockingQueue, rejectedExecutionHandler); } return executor; } public void updateNumConcurrentRowMutationSenderThreads(int numConcurrentRowMutationSenderThreads) { this.numConcurrentRowMutationSenderThreads = numConcurrentRowMutationSenderThreads; } }
package com.sun.facelets.tag; import javax.el.ELException; import javax.el.ExpressionFactory; import javax.el.MethodExpression; import javax.el.ValueExpression; import com.sun.facelets.FaceletContext; import com.sun.facelets.el.ELText; /** * Representation of a Tag's attribute in a Facelet File * * @author Jacob Hookom * @version $Id: TagAttribute.java,v 1.2 2005-07-13 02:56:15 jhook Exp $ */ public final class TagAttribute { protected final boolean literal; protected final String localName; protected final Location location; protected final String namespace; protected final String qName; protected final String value; public TagAttribute(Location location, String ns, String localName, String qName, String value) { this.location = location; this.namespace = ns; this.localName = localName; this.qName = qName; this.value = value; try { this.literal = ELText.isLiteral(this.value); } catch (ELException e) { throw new TagAttributeException(this, e); } } /** * If literal, return * {@link Boolean#getBoolean(java.lang.String) Boolean.getBoolean(java.lang.String)} * passing our value, otherwise call * {@link #getObject(FaceletContext, Class) getObject(FaceletContext, Class)}. * * @see Boolean#getBoolean(java.lang.String) * @see #getObject(FaceletContext, Class) * @param ctx * FaceletContext to use * @return boolean value */ public boolean getBoolean(FaceletContext ctx) { if (this.literal) { return Boolean.getBoolean(this.value); } else { return ((Boolean) this.getObject(ctx, Boolean.class)) .booleanValue(); } } /** * If literal, call * {@link Integer#parseInt(java.lang.String) Integer.parseInt(String)}, * otherwise call * {@link #getObject(FaceletContext, Class) getObject(FaceletContext, Class)}. * * @see Integer#parseInt(java.lang.String) * @see #getObject(FaceletContext, Class) * @param ctx * FaceletContext to use * @return int value */ public int getInt(FaceletContext ctx) { if (this.literal) { return Integer.parseInt(this.value); } else { return ((Number) this.getObject(ctx, Number.class)).intValue(); } } /** * Local name of this attribute * * @return local name of this attribute */ public String getLocalName() { return this.localName; } /** * The location of this attribute in the FaceletContext * * @return the TagAttribute's location */ public Location getLocation() { return this.location; } /** * Create a MethodExpression, using this attribute's value as the expression * String. * * @see ExpressionFactory#createMethodExpression(javax.el.ELContext, * java.lang.String, java.lang.Class, java.lang.Class[]) * @see MethodExpression * @param ctx * FaceletContext to use * @param type * expected return type * @param paramTypes * parameter type * @return a MethodExpression instance */ public MethodExpression getMethodExpression(FaceletContext ctx, Class type, Class[] paramTypes) { try { ExpressionFactory f = ctx.getExpressionFactory(); return f.createMethodExpression(ctx, this.value, type, paramTypes); } catch (Exception e) { throw new TagAttributeException(this, e); } } /** * The resolved Namespace for this attribute * * @return resolved Namespace */ public String getNamespace() { return this.namespace; } /** * Delegates to getObject with Object.class as a param * * @see #getObject(FaceletContext, Class) * @param ctx * FaceletContext to use * @return Object representation of this attribute's value */ public Object getObject(FaceletContext ctx) { return this.getObject(ctx, Object.class); } /** * The qualified name for this attribute * * @return the qualified name for this attribute */ public String getQName() { return this.qName; } /** * Return the literal value of this attribute * * @return literal value */ public String getValue() { return this.value; } /** * If literal, then return our value, otherwise delegate to getObject, * passing String.class. * * @see #getObject(FaceletContext, Class) * @param ctx * FaceletContext to use * @return String value of this attribute */ public String getValue(FaceletContext ctx) { if (this.literal) { return this.value; } else { return (String) this.getObject(ctx, String.class); } } /** * If literal, simply coerce our String literal value using an * ExpressionFactory, otherwise create a ValueExpression and evaluate it. * * @see ExpressionFactory#coerceToType(java.lang.Object, java.lang.Class) * @see ExpressionFactory#createValueExpression(javax.el.ELContext, * java.lang.String, java.lang.Class) * @see ValueExpression * @param ctx * FaceletContext to use * @param type * expected return type * @return Object value of this attribute */ public Object getObject(FaceletContext ctx, Class type) { if (this.literal) { if (String.class.equals(type)) { return this.value; } else { try { return ctx.getExpressionFactory().coerceToType(this.value, type); } catch (Exception e) { throw new TagAttributeException(this, e); } } } else { ValueExpression ve = this.getValueExpression(ctx, type); try { return ve.getValue(ctx); } catch (Exception e) { throw new TagAttributeException(this, e); } } } /** * Create a ValueExpression, using this attribute's literal value and the * passed expected type. * * @see ExpressionFactory#createValueExpression(javax.el.ELContext, * java.lang.String, java.lang.Class) * @see ValueExpression * @param ctx * FaceletContext to use * @param type * expected return type * @return ValueExpression instance */ public ValueExpression getValueExpression(FaceletContext ctx, Class type) { try { ExpressionFactory f = ctx.getExpressionFactory(); return f.createValueExpression(ctx, this.value, type); } catch (Exception e) { throw new TagAttributeException(this, e); } } /** * If this TagAttribute is literal (not #{..} or ${..}) * * @return true if this attribute is literal */ public boolean isLiteral() { return this.literal; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ public String toString() { return this.location + " " + this.qName + "=\"" + this.value + "\""; } }
package net.sf.samtools.util; /** * Grab-bag of stateless String-oriented utilities. */ public class StringUtil { private static final byte UPPER_CASE_OFFSET = 'A' - 'a'; /** * * @param separator String to interject between each string in strings arg * @param strings List of strings to be joined. * @return String that concatenates each item of strings arg, with separator btw each of them. */ public static String join(final String separator, final String... strings) { if (strings.length == 0) { return ""; } final StringBuilder ret = new StringBuilder(strings[0]); for (int i = 1; i < strings.length; ++i) { ret.append(separator); ret.append(strings[i]); } return ret.toString(); } /** * Split the string into tokens separated by the given delimiter. Profiling has * revealed that the standard string.split() method typically takes > 1/2 * the total time when used for parsing ascii files. * Note that if tokens arg is not large enough to all the tokens in the string, excess tokens are discarded. * * @param aString the string to split * @param tokens an array to hold the parsed tokens * @param delim character that delimits tokens * @return the number of tokens parsed */ public static int split(final String aString, final String[] tokens, final char delim) { final int maxTokens = tokens.length; int nTokens = 0; int start = 0; int end = aString.indexOf(delim); if(end < 0) { tokens[nTokens++] = aString; return nTokens; } while ((end > 0) && (nTokens < maxTokens)) { tokens[nTokens++] = aString.substring(start, end); start = end + 1; end = aString.indexOf(delim, start); } // Add the trailing string, if there is room and if it is not empty. if (nTokens < maxTokens) { final String trailingString = aString.substring(start); if (trailingString.length() > 0) { tokens[nTokens++] = trailingString; } } return nTokens; } /** * Split the string into tokens separated by the given delimiter. Profiling has * revealed that the standard string.split() method typically takes > 1/2 * the total time when used for parsing ascii files. * Note that the string is split into no more elements than tokens arg will hold, so the final tokenized * element may contain delimiter chars. * * @param aString the string to split * @param tokens an array to hold the parsed tokens * @param delim character that delimits tokens * @return the number of tokens parsed */ public static int splitConcatenateExcessTokens(final String aString, final String[] tokens, final char delim) { final int maxTokens = tokens.length; int nTokens = 0; int start = 0; int end = aString.indexOf(delim); if(end < 0) { tokens[nTokens++] = aString; return nTokens; } while ((end > 0) && (nTokens < maxTokens - 1)) { tokens[nTokens++] = aString.substring(start, end); start = end + 1; end = aString.indexOf(delim, start); } // Add the trailing string, if it is not empty. final String trailingString = aString.substring(start); if (trailingString.length() > 0) { tokens[nTokens++] = trailingString; } return nTokens; } /** * @param b ASCII character * @return uppercase version of arg if it was lowercase, otherwise returns arg */ public static byte toUpperCase(final byte b) { if (b < 'a' || b > 'z') { return b; } return (byte)(b + UPPER_CASE_OFFSET); } /** * Converts in place all lower case letters to upper case in the byte array provided. */ public static void toUpperCase(final byte[] bytes) { final int length = bytes.length; for (int i=0; i<length; ++i) { if (bytes[i] >= 'a' && bytes[i] <= 'z') { bytes[i] = (byte) (bytes[i] + UPPER_CASE_OFFSET); } } } public static String assertCharactersNotInString(final String illegalChars, final char... chars) { for (final char illegalChar : illegalChars.toCharArray()) { for (final char ch: chars) { if (illegalChar == ch) { throw new IllegalArgumentException("Supplied String contains illegal character '" + illegalChar + "'."); } } } return illegalChars; } /** * Return input string with newlines inserted to ensure that all lines * have length <= maxLineLength. if a word is too long, it is simply broken * at maxLineLength. Does not handle tabs intelligently (due to implementer laziness). */ public static String wordWrap(final String s, final int maxLineLength) { final String[] lines = s.split("\n"); final StringBuilder sb = new StringBuilder(); for (final String line: lines) { if (sb.length() > 0) { sb.append("\n"); } sb.append(wordWrapSingleLine(line, maxLineLength)); } if (s.endsWith("\n")) { sb.append("\n"); } return sb.toString(); } public static String wordWrapSingleLine(final String s, final int maxLineLength) { if (s.length() <= maxLineLength) { return s; } final StringBuilder sb = new StringBuilder(); int startCopyFrom = 0; while (startCopyFrom < s.length()) { int lastSpaceIndex = startCopyFrom; int i; // Find break point (if it exists) for (i = startCopyFrom; i < s.length() && i - startCopyFrom < maxLineLength; ++i) { if (Character.isWhitespace(s.charAt(i))) { lastSpaceIndex = i; } } if (i - startCopyFrom < maxLineLength) { lastSpaceIndex = i; } // Include any trailing whitespace for (; lastSpaceIndex < s.length() && Character.isWhitespace(s.charAt(lastSpaceIndex)); ++lastSpaceIndex) {} if (sb.length() > 0) { sb.append("\n"); } // Handle situation in which there is no word break. Just break the word in the middle. if (lastSpaceIndex == startCopyFrom) { lastSpaceIndex = i; } sb.append(s.substring(startCopyFrom, lastSpaceIndex)); startCopyFrom = lastSpaceIndex; } return sb.toString(); } // The following methods all convert btw bytes and Strings, without // using the Java character set mechanism. public static String bytesToString(final byte[] data) { if (data == null) { return null; } return bytesToString(data, 0, data.length); } @SuppressWarnings("deprecation") public static String bytesToString(final byte[] buffer, final int offset, final int length) { /* The non-deprecated way, that requires allocating char[] final char[] charBuffer = new char[length]; for (int i = 0; i < length; ++i) { charBuffer[i] = (char)buffer[i+offset]; } return new String(charBuffer); */ return new String(buffer, 0, offset, length); } @SuppressWarnings("deprecation") public static byte[] stringToBytes(final String s) { /* The non-deprecated way, that requires allocating char[] final byte[] byteBuffer = new byte[s.length()]; final char[] charBuffer = s.toCharArray(); for (int i = 0; i < charBuffer.length; ++i) { byteBuffer[i] = (byte)(charBuffer[i] & 0xff); } return byteBuffer; */ final byte[] byteBuffer = new byte[s.length()]; s.getBytes(0, byteBuffer.length, byteBuffer, 0); return byteBuffer; } @SuppressWarnings("deprecation") public static byte[] stringToBytes(final String s, final int offset, final int length) { final byte[] byteBuffer = new byte[length]; s.getBytes(offset, offset + length, byteBuffer, 0); return byteBuffer; } // This method might more appropriately live in BinaryCodec, but all the byte <=> char conversion // should be in the same place. public static String readNullTerminatedString(final BinaryCodec binaryCodec) { final StringBuilder ret = new StringBuilder(); for (byte b = binaryCodec.readByte(); b != 0; b = binaryCodec.readByte()) { ret.append((char)(b & 0xff)); } return ret.toString(); } /** * Convert chars to bytes merely by casting * @param chars input chars * @param charOffset where to start converting from chars array * @param length how many chars to convert * @param bytes where to put the converted output * @param byteOffset where to start writing the converted output. */ public static void charsToBytes(final char[] chars, final int charOffset, final int length, final byte[] bytes, final int byteOffset) { for (int i = 0; i < length; ++i) { bytes[byteOffset + i] = (byte)chars[charOffset + i]; } } /** * Convert a byte array into a String hex representation. * @param data Input to be converted. * @return String twice as long as data.length with hex representation of data. */ public static String bytesToHexString(final byte[] data) { final char[] chars = new char[2 * data.length]; for (int i = 0; i < data.length; i++) { final byte b = data[i]; chars[2*i] = toHexDigit((b >> 4) & 0xF); chars[2*i+1] = toHexDigit(b & 0xF); } return new String(chars); } /** * Convert a String containing hex characters into an array of bytes with the binary representation * of the hex string * @param s Hex string. Length must be even because each pair of hex chars is converted into a byte. * @return byte array with binary representation of hex string. * @throws NumberFormatException */ public static byte[] hexStringToBytes(final String s) throws NumberFormatException { if (s.length() % 2 != 0) { throw new NumberFormatException("Hex representation of byte string does not have even number of hex chars: " + s); } final byte[] ret = new byte[s.length() / 2]; for (int i = 0; i < ret.length; ++i) { ret[i] = (byte) ((fromHexDigit(s.charAt(i * 2)) << 4) | fromHexDigit(s.charAt(i * 2 + 1))); } return ret; } public static char toHexDigit(final int value) { return (char) ((value < 10) ? ('0' + value) : ('A' + value - 10)); } public static int fromHexDigit(final char c) throws NumberFormatException { final int ret = Character.digit(c, 16); if (ret == -1) { throw new NumberFormatException("Not a valid hex digit: " + c); } return ret; } /** * Reverse the given string. Does not check for null. * @param s String to be reversed. * @return New string that is the reverse of the input string. */ public static String reverseString(final String s) { final StringBuilder sb = new StringBuilder(s); sb.reverse(); return sb.toString(); } /** * <p>Checks if a String is whitespace, empty ("") or null.</p> * * <pre> * StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true * StringUtils.isBlank(" ") = true * StringUtils.isBlank("sam") = false * StringUtils.isBlank(" sam ") = false * </pre> * * @param str the String to check, may be null * @return <code>true</code> if the String is null, empty or whitespace */ public static boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i)) ) { return false; } } return true; } }
package aterm.pure; import java.io.BufferedInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import aterm.AFun; import aterm.ATerm; import aterm.ATermList; import aterm.ParseError; public class BAFReader { private static final int BAF_MAGIC = 0xBAF; private static final int BAF_VERSION = 0x300; private static final int HEADER_BITS = 32; private BitStream reader; private int nrUniqueSymbols = -1; private SymEntry[] symbols; private PureFactory factory; class SymEntry { public AFun fun; public int arity; public int nrTerms; public int termWidth; public ATerm[] terms; public int[] nrTopSyms; public int[] symWidth; public int[][] topSyms; } public BAFReader(PureFactory factory, InputStream inputStream) { this.factory = factory; reader = new BitStream(inputStream); } public ATerm readFromBinaryFile(boolean headerAlreadyRead) throws ParseError, IOException { if(!headerAlreadyRead && !isBinaryATerm(reader)) throw new ParseError("Input is not a BAF file"); int val = reader.readInt(); if (val != BAF_VERSION) throw new ParseError("Wrong BAF version (wanted " + BAF_VERSION + ", got " + val + "), giving up"); nrUniqueSymbols = reader.readInt(); int nrUniqueTerms = reader.readInt(); debug("" + nrUniqueSymbols + " unique symbols"); debug("" + nrUniqueTerms + " unique terms"); symbols = new SymEntry[nrUniqueSymbols]; readAllSymbols(); int i = reader.readInt(); return readTerm(symbols[i]); } public static boolean isBinaryATerm(BufferedInputStream in) throws IOException { in.mark(10); if(isBinaryATerm(new BitStream(in))) return true; in.reset(); return false; } private static boolean isBinaryATerm(BitStream in) throws IOException { try { int w0 = in.readInt(); int w1 = in.readInt(); if (w0 == 0 && w1 == BAF_MAGIC) return true; } catch(EOFException e) {} return false; } private void debug(String s) { // System.out.println(s); } private ATerm readTerm(SymEntry e) throws ParseError, IOException { int arity = e.arity; ATerm[] args = new ATerm[arity]; debug("readTerm() - " + e.fun.getName() + "[" + arity + "]"); for (int i = 0; i < arity; i++) { int val = reader.readBits(e.symWidth[i]); debug(" [" + i + "] - " + val); debug(" [" + i + "] - " + e.topSyms[i].length); SymEntry argSym = symbols[e.topSyms[i][val]]; val = reader.readBits(argSym.termWidth); if (argSym.terms[val] == null) { debug(" [" + i + "] - recurse"); argSym.terms[val] = readTerm(argSym); } if (argSym.terms[val] == null) throw new ParseError("Cannot be null"); args[i] = argSym.terms[val]; } /* switch (e.fun.getType()) { case ATerm.BLOB: reader.flushBitsFromReader(); String t = reader.readString(); return factory.makeBlob(t.getBytes()); case ATerm.PLACEHOLDER: return factory.makePlaceholder(args[0]); } */ if (e.fun.getName().equals("<int>")) { int val = reader.readBits(HEADER_BITS); return factory.makeInt(val); } if (e.fun.getName().equals("<real>")) { reader.flushBitsFromReader(); String s = reader.readString(); return factory.makeReal(new Double(s).doubleValue()); } if (e.fun.getName().equals("[_,_]")) { debug(" for (int i = 0; i < args.length; i++) debug(" + " + args[i].getClass()); return ((ATermList) args[1]).insert(args[0]); } if (e.fun.getName().equals("[]")) return factory.makeList(); // FIXME: Add annotation case // FIXME: Add blob case // FIXME: Add placeholder case debug(e.fun + " / " + args); for (int i = 0; i < args.length; i++) debug("" + args[i]); return factory.makeAppl(e.fun, args); } private void readAllSymbols() throws IOException { for (int i = 0; i < nrUniqueSymbols; i++) { SymEntry e = new SymEntry(); symbols[i] = e; AFun fun = readSymbol(); e.fun = fun; int arity = e.arity = fun.getArity(); int v = reader.readInt(); e.nrTerms = v; e.termWidth = bitWidth(v); // FIXME: original code is inconsistent at this point! e.terms = (v == 0) ? null : new ATerm[v]; if (arity == 0) { e.nrTopSyms = null; e.symWidth = null; e.topSyms = null; } else { e.nrTopSyms = new int[arity]; e.symWidth = new int[arity]; e.topSyms = new int[arity][]; } for (int j = 0; j < arity; j++) { v = reader.readInt(); e.nrTopSyms[j] = v; e.symWidth[j] = bitWidth(v); e.topSyms[j] = new int[v]; for (int k = 0; k < e.nrTopSyms[j]; k++) { v = reader.readInt(); e.topSyms[j][k] = v; } } } } private int bitWidth(int v) { int nrBits = 0; if (v <= 1) return 0; while (v != 0) { v >>= 1; nrBits++; } return nrBits; } private AFun readSymbol() throws IOException { String s = reader.readString(); int arity = reader.readInt(); int quoted = reader.readInt(); debug(s + " / " + arity + " / " + quoted); return factory.makeAFun(s, arity, quoted != 0); } public static class BitStream { InputStream stream; private int bitsInBuffer; private int bitBuffer; public BitStream(InputStream inputStream) { stream = inputStream; } public int readInt() throws IOException { int[] buf = new int[5]; buf[0] = readByte(); // Check if 1st character is enough if((buf[0] & 0x80) == 0) return buf[0]; buf[1] = readByte(); // Check if 2nd character is enough if((buf[0] & 0x40) == 0) return buf[1] + ((buf[0] & ~0xc0) << 8); buf[2] = readByte(); // Check if 3rd character is enough if((buf[0] & 0x20) == 0 ) return buf[2] + (buf[1] << 8) + ((buf[0] & ~0xe0) << 16); buf[3] = readByte(); // Check if 4th character is enough if((buf[0] & 0x10) == 0 ) return buf[3] + (buf[2] << 8) + (buf[1] << 16) + ((buf[0] & ~0xf0) << 24); buf[4] = readByte(); return buf[4] + (buf[3] << 8) + (buf[2] << 16) + (buf[1] << 24); } private int readByte() throws IOException { int c = stream.read(); if(c == -1) throw new EOFException(); return c; } public String readString() throws IOException { int l = readInt(); byte[] b = new byte[l]; stream.read(b, 0, b.length); return new String(b); } public int readBits(int nrBits) throws IOException { int mask = 1; int val = 0; for (int i=0; i<nrBits; i++) { if (bitsInBuffer == 0) { int v = readByte(); if (v == -1) return -1; bitBuffer = v; bitsInBuffer = 8; } val |= (((bitBuffer & 0x80) != 0) ? mask : 0); mask <<= 1; bitBuffer <<= 1; bitsInBuffer } return val; } public void flushBitsFromReader() { bitsInBuffer = 0; } } }
// $Id: FrameManager.java,v 1.2 2002/04/23 03:10:59 mdb Exp $ package com.threerings.media; import java.applet.Applet; import java.awt.Component; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Window; import java.awt.image.BufferStrategy; import java.awt.image.VolatileImage; import java.awt.EventQueue; import javax.swing.JComponent; import javax.swing.RepaintManager; import java.util.ArrayList; import com.samskivert.util.Interval; import com.samskivert.util.IntervalManager; import com.samskivert.util.StringUtil; import com.threerings.media.util.PerformanceMonitor; import com.threerings.media.util.PerformanceObserver; /** * Provides a central point from which the computation for each "frame" or * tick can be dispatched. This assumed that the application structures * its activity around the rendering of each frame, which is a common * architecture for games. The animation and sprite support provided by * other classes in this package are structured for use in an application * that uses a frame manager to tick everything once per frame. * * <p> The frame manager goes through a simple two part procedure every * frame: * * <ul> * <li> Ticking all of the frame participants: in {@link * FrameParticipant#tick}, any processing that need be performed during * this frame should be performed. Care should be taken not to execute * code that will take unduly long, instead such processing should be * broken up so that it can be performed in small pieces every frame (or * performed on a separate thread with the results safely communicated * back to the frame participants for incorporation into the rendering * loop). * * <li> Painting the user interface hierarchy: the top-level component * (the frame) is painted (via a call to {@link Frame#paint}) into a flip * buffer (if supported, an off-screen buffer if not). Updates that were * computed during the tick should be rendered in this call to paint. The * paint call will propagate down to all components in the UI hierarchy, * some of which may be {@link FrameParticipants} and will have prepared * themselves for their upcoming painting in the previous call to {@link * FrameParticipant#tick}. When the call to paint completes, the flip * buffer is flipped and the process starts all over again. * </ul> * * <p> The ticking and rendering takes place on the AWT thread so as to * avoid the need for complicated coordination between AWT event handler * code and frame code. However, this means that all AWT (and Swing) event * handlers <em>must not</em> perform any complicated processing. After * each frame, control of the AWT thread is given back to the AWT which * processes all pending AWT events before giving the frame manager an * opportunity to process the next frame. Thus the convenience of * everything running on the AWT thread comes with the price of requiring * that AWT event handlers not block or perform any intensive processing. * In general, this is a sensible structure for an application anyhow, so * this organization tends to be preferable to an organization where the * AWT and frame threads are separate and must tread lightly so as not to * collide. */ public class FrameManager implements PerformanceObserver { /** * Constructs a frame manager that will do its rendering to the * supplied frame. It is likely that the caller will want to have put * the frame into full-screen exclusive mode prior to providing it to * the frame manager so that the frame manager can take advantage of * optimizations available in that mode. * * @see GraphicsDevice#setFullScreenWindow */ public FrameManager (Frame frame) { _frame = frame; _frame.setIgnoreRepaint(true); // set up our custom repaint manager _remgr = new FrameRepaintManager(); RepaintManager.setCurrentManager(_remgr); // turn off double buffering for the whole business because we // handle repaints _remgr.setDoubleBufferingEnabled(false); // register with the performance monitor PerformanceMonitor.register(this, "frame-rate", 1000l); } /** * Instructs the frame manager to target the specified number of * frames per second. If the computation and rendering for a frame are * completed with time to spare, the frame manager will wait until the * proper time to begin processing for the next frame. If a frame * takes longer than its alotted time, the frame manager will * immediately begin processing on the next frame. */ public void setTargetFrameRate (int fps) { // compute the number of milliseconds per frame _millisPerFrame = 1000/fps; } /** * Registers a frame participant. The participant will be given the * opportunity to do processing and rendering on each frame. */ public void registerFrameParticipant (FrameParticipant participant) { _participants.add(participant); } /** * Removes a frame participant. */ public void removeFrameParticipant (FrameParticipant participant) { _participants.remove(participant); } /** * Starts up the per-frame tick */ public void start () { if (_ticker == null) { // create ticker for queueing up tick requests on AWT thread _ticker = new Ticker(); // and start it up _ticker.start(); // and kick off our first frame _ticker.tickIn(_millisPerFrame, System.currentTimeMillis()); } } /** * Stops the per-frame tick. */ public synchronized void stop () { if (_ticker != null) { _ticker = null; } } /** * Returns true if the tick interval is be running (not necessarily at * that instant, but in general). */ public synchronized boolean isRunning () { return (_ticker != null); } /** * Called to perform the frame processing and rendering. */ protected void tick () { // if our frame is not showing (or is impossibly sized), don't try // rendering anything if (_frame.isShowing() && _frame.getWidth() > 0 && _frame.getHeight() > 0) { long tickStamp = System.currentTimeMillis(); // tick our participants tickParticipants(tickStamp); // repaint our participants paintParticipants(tickStamp); } // now determine how many milliseconds we have left before we need // to start the next frame (if any) long end = System.currentTimeMillis(); long duration = end - _frameStart; long remaining = _millisPerFrame - duration; // note that we've done a frame PerformanceMonitor.tick(this, "frame-rate"); // if we have no time remaining, queue up another tick immediately if (remaining <= 0) { // make a note that we're starting our next frame now _frameStart = end; EventQueue.invokeLater(_callTick); } else { // otherwise queue one up in the requisite number of millis _ticker.tickIn(remaining, end); } } /** * Called once per frame to invoke {@link FrameParticipant#tick} on * all of our frame participants. */ protected void tickParticipants (long tickStamp) { // tick all of our frame participants int pcount = _participants.size(); for (int ii = 0; ii < pcount; ii++) { FrameParticipant part = (FrameParticipant) _participants.get(ii); try { part.tick(tickStamp); } catch (Throwable t) { Log.warning("Frame participant choked during tick " + "[part=" + StringUtil.safeToString(part) + "]."); Log.logStackTrace(t); } } // validate any invalid components try { _remgr.validateComponents(); } catch (Throwable t) { Log.warning("Failure validating components."); Log.logStackTrace(t); } } /** * Called once per frame to invoke {@link FrameParticipant#paint} on * all of our frame participants. */ protected void paintParticipants (long tickStamp) { // create our buffer strategy if we don't already have one if (_bufstrat == null) { _frame.createBufferStrategy(2); _bufstrat = _frame.getBufferStrategy(); } // create our off-screen buffer if necessary GraphicsConfiguration gc = _frame.getGraphicsConfiguration(); if (_backimg == null) { createBackBuffer(gc); } // render into our back buffer do { // make sure our back buffer hasn't disappeared int valres = _backimg.validate(gc); // if we've changed resolutions, recreate the buffer if (valres == VolatileImage.IMAGE_INCOMPATIBLE) { Log.info("Back buffer incompatible, recreating."); createBackBuffer(gc); } Rectangle bounds = new Rectangle(); Graphics g = null, fg = null; Insets fi = _frame.getInsets(); try { g = _backimg.getGraphics(); fg = _frame.getGraphics(); // if the image wasn't A-OK, we need to rerender the // whole business rather than just the dirty parts if (valres != VolatileImage.IMAGE_OK) { Log.info("Lost back buffer, redrawing."); } // repaint any widgets that have declared there need to be // repainted since the last tick _remgr.paintComponents(g); // paint our frame participants (which want to be handled // specially) int pcount = _participants.size(); for (int ii = 0; ii < pcount; ii++) { FrameParticipant part = (FrameParticipant) _participants.get(ii); Component pcomp = part.getComponent(); if (pcomp == null) { continue; } // get the bounds of this component pcomp.getBounds(bounds); // the bounds adjustment we're about to call will add // in the components initial bounds offsets, so we // remove them here bounds.setLocation(0, 0); // convert them into top-level coordinates; also note // that if this component does not have a valid or // visible root, we don't want to paint it either if (getRoot(pcomp, bounds) == null) { continue; } try { // render this participant // Log.info("Rendering [comp=" + pcomp.getClass().getName() + // ", bounds=" + StringUtil.toString(bounds) + "]."); g.setClip(bounds); g.translate(bounds.x, bounds.y); pcomp.paint(g); g.translate(-bounds.x, -bounds.y); // // copy the off-screen buffer on-screen // fg.setClip(bounds); // fg.drawImage(_backimg, fi.left, fi.top, null); } catch (Throwable t) { String ptos = StringUtil.safeToString(part); Log.warning("Frame participant choked during paint " + "[part=" + ptos + "]."); Log.logStackTrace(t); } } // Log.info("insets: " + fi + ", fb: " + _frame.getBounds()); // _frame.paint(g); fg.drawImage(_backimg, 0, 0, null); } finally { if (g != null) { g.dispose(); } if (fg != null) { fg.dispose(); } } } while (_backimg.contentsLost()); // Graphics g = null; // try { // g = _bufstrat.getDrawGraphics(); // _frame.paint(g); // _bufstrat.show(); // } catch (Throwable t) { // Log.warning("Frame rendering choked."); // Log.logStackTrace(t); // } finally { // if (g != null) { // g.dispose(); } // documentation inherited public void checkpoint (String name, int ticks) { // Log.info("Frames in last second: " + ticks); } /** * Used to queue up frame ticks on the AWT thread at some point in the * future. */ protected class Ticker extends Thread { /** * Tells the ticker to queue up a frame in the requisite number of * milliseconds. */ public synchronized void tickIn (long millis, long now) { _sleepfor = millis; _now = now; this.notify(); } public void run () { synchronized (this) { while (_sleepfor != -1) { try { if (_sleepfor == 0) { this.wait(); } if (_sleepfor > 0) { Thread.sleep(_sleepfor); // make a note of our frame start time _frameStart = System.currentTimeMillis(); // long error =_frameStart - (_sleepfor + _now); // if (Math.abs(error) > 3) { // Log.warning("Funny business: " + error); // queue up our ticker on the AWT thread EventQueue.invokeLater(_callTick); _sleepfor = 0; } } catch (InterruptedException ie) { Log.warning("Girl interrupted!"); } } } } protected long _sleepfor = 0l; protected long _now = 0l; } /** * Creates the off-screen buffer used to perform double buffered * rendering of the animated panel. */ protected void createBackBuffer (GraphicsConfiguration gc) { _backimg = gc.createCompatibleVolatileImage( _frame.getWidth(), _frame.getHeight()); } /** * Returns the root component for the supplied component or null if it * is not part of a rooted hierarchy or if any parent along the way is * found to be hidden or without a peer. Along the way, it adjusts the * supplied component-relative rectangle to be relative to the * returned root component. */ public static Component getRoot (Component comp, Rectangle rect) { for (Component c = comp; c != null; c = c.getParent()) { if (!c.isVisible() || c.getPeer() == null) { return null; } if (c instanceof Window || c instanceof Applet) { return c; } rect.x += c.getX(); rect.y += c.getY(); } return null; } /** The frame into which we do our rendering. */ protected Frame _frame; /** Our custom repaint manager. */ protected FrameRepaintManager _remgr; /** The buffer strategy used to do our rendering. */ protected BufferStrategy _bufstrat; /** The image used to render off-screen. */ protected VolatileImage _backimg; /** The number of milliseconds per frame (33 by default, which gives * an fps of 30). */ protected long _millisPerFrame = 33; /** The time at which we started the most recent "frame". */ protected long _frameStart; /** Used to queue up a tick. */ protected Ticker _ticker; /** Used to queue up a call to {@link #tick} on the AWT thread. */ protected Runnable _callTick = new Runnable () { public void run () { tick(); } }; /** The entites that are ticked each frame. */ protected ArrayList _participants = new ArrayList(); }
package hello; import com.mangofactory.swagger.configuration.SpringSwaggerConfig; import com.mangofactory.swagger.plugin.EnableSwagger; import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import javax.inject.Inject; /** * {@code HelloWorldSwagger} <strong>needs documentation</strong>. * * @author <a href="mailto:boxley@thoughtworks.com">Brian Oxley</a> * @todo Needs documentation */ @ComponentScan("hello") @Configuration @EnableWebMvc @EnableSwagger public class HelloWorldSwagger { @Inject private SpringSwaggerConfig config; @Bean public SwaggerSpringMvcPlugin custom() { return new SwaggerSpringMvcPlugin(config); } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util; import java.util.Collection; import java.util.Enumeration; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.text.MessageFormat; import com.samskivert.text.MessageUtil; import com.samskivert.util.StringUtil; import static com.threerings.NaryaLog.log; /** * A message bundle provides an easy mechanism by which to obtain * translated message strings from a resource bundle. It uses the {@link * MessageFormat} class to substitute arguments into the translation * strings. Message bundles would generally be obtained via the {@link * MessageManager}, but could be constructed individually if so desired. */ public class MessageBundle { /** * Call this to "taint" any string that has been entered by an entity * outside the application so that the translation code knows not to * attempt to translate this string when doing recursive translations * (see {@link #xlate}). */ public static String taint (Object text) { return MessageUtil.taint(text); } /** * Composes a message key with a single argument. The message can * subsequently be translated in a single call using {@link #xlate}. */ public static String compose (String key, Object arg) { return MessageUtil.compose(key, new Object[] { arg }); } /** * Composes a message key with an array of arguments. The message can * subsequently be translated in a single call using {@link #xlate}. */ public static String compose (String key, Object... args) { return MessageUtil.compose(key, args); } /** * Composes a message key with an array of arguments. The message can * subsequently be translated in a single call using {@link #xlate}. */ public static String compose (String key, String... args) { return MessageUtil.compose(key, args); } /** * A convenience method for calling {@link #compose(String,Object[])} * with an array of arguments that will be automatically tainted (see * {@link #taint}). */ public static String tcompose (String key, Object... args) { return MessageUtil.tcompose(key, args); } /** * Required for backwards compatibility. Alas. */ public static String tcompose (String key, Object arg) { return MessageUtil.tcompose(key, new Object[] { arg }); } /** * Required for backwards compatibility. Alas. */ public static String tcompose (String key, Object arg1, Object arg2) { return MessageUtil.tcompose(key, new Object[] { arg1, arg2 }); } /** * A convenience method for calling {@link #compose(String,String[])} * with an array of arguments that will be automatically tainted (see * {@link #taint}). */ public static String tcompose (String key, String... args) { return MessageUtil.tcompose(key, args); } /** * Returns a fully qualified message key which, when translated by * some other bundle, will know to resolve and utilize the supplied * bundle to translate this particular key. */ public static String qualify (String bundle, String key) { return MessageUtil.qualify(bundle, key); } /** * Returns the bundle name from a fully qualified message key. * * @see #qualify */ public static String getBundle (String qualifiedKey) { return MessageUtil.getBundle(qualifiedKey); } /** * Returns the unqualified portion of the key from a fully qualified * message key. * * @see #qualify */ public static String getUnqualifiedKey (String qualifiedKey) { return MessageUtil.getUnqualifiedKey(qualifiedKey); } /** * Initializes the message bundle which will obtain localized messages * from the supplied resource bundle. The path is provided purely for * reporting purposes. */ public void init (MessageManager msgmgr, String path, ResourceBundle bundle, MessageBundle parent) { _msgmgr = msgmgr; _path = path; _bundle = bundle; _parent = parent; } /** * Obtains the translation for the specified message key. No arguments * are substituted into the translated string. If a translation * message does not exist for the specified key, an error is logged * and the key itself is returned so that the caller need not worry * about handling a null response. */ public String get (String key) { // if this string is tainted, we don't translate it, instead we // simply remove the taint character and return it to the caller if (key.startsWith(MessageUtil.TAINT_CHAR)) { return key.substring(1); } String msg = getResourceString(key); return (msg != null) ? msg : key; } /** * Adds all messages whose key starts with the specified prefix to the * supplied collection. * * @param includeParent if true, messages from our parent bundle (and its * parent bundle, all the way up the chain will be included). */ public void getAll (String prefix, Collection<String> messages, boolean includeParent) { Enumeration<String> iter = _bundle.getKeys(); while (iter.hasMoreElements()) { String key = iter.nextElement(); if (key.startsWith(prefix)) { messages.add(get(key)); } } if (includeParent && _parent != null) { _parent.getAll(prefix, messages, includeParent); } } /** * Adds all keys for messages whose key starts with the specified prefix to the * supplied collection. * * @param includeParent if true, messages from our parent bundle (and its * parent bundle, all the way up the chain will be included). */ public void getAllKeys (String prefix, Collection<String> keys, boolean includeParent) { Enumeration<String> iter = _bundle.getKeys(); while (iter.hasMoreElements()) { String key = iter.nextElement(); if (key.startsWith(prefix)) { keys.add(key); } } if (includeParent && _parent != null) { _parent.getAllKeys(prefix, keys, includeParent); } } /** * Returns true if we have a translation mapping for the supplied key, * false if not. */ public boolean exists (String key) { return getResourceString(key, false) != null; } /** * Get a String from the resource bundle, or null if there was an error. */ protected String getResourceString (String key) { return getResourceString(key, true); } /** * Get a String from the resource bundle, or null if there was an * error. * * @param key the resource key. * @param reportMissing whether or not the method should log an error * if the resource didn't exist. */ protected String getResourceString (String key, boolean reportMissing) { try { if (_bundle != null) { return _bundle.getString(key); } } catch (MissingResourceException mre) { // fall through and try the parent } // if we have a parent, try getting the string from them if (_parent != null) { String value = _parent.getResourceString(key, false); if (value != null) { return value; } // if we didn't find it in our parent, we want to fall // through and report missing appropriately } if (reportMissing) { log.warning("Missing translation message", "bundle", _path, "key", key, new Exception()); } return null; } /** * Obtains the translation for the specified message key. The * specified arguments are substituted into the translated string. * * <p> If the first argument in the array is an {@link Integer} * object, a translation will be selected accounting for plurality in * the following manner. Assume a message key of * <code>m.widgets</code>, the following translations should be * defined: * <pre> * m.widgets.0 = no widgets. * m.widgets.1 = {0} widget. * m.widgets.n = {0} widgets. * </pre> * * The specified argument is substituted into the translated string as * appropriate. Consider using: * * <pre> * m.widgets.n = {0,number,integer} widgets. * </pre> * * to obtain proper insertion of commas and dots as appropriate for * the locale. * * <p> See {@link MessageFormat} for more information on how the * substitution is performed. If a translation message does not exist * for the specified key, an error is logged and the key itself (plus * the arguments) is returned so that the caller need not worry about * handling a null response. */ public String get (String key, Object... args) { // if this is a qualified key, we need to pass the buck to the // appropriate message bundle if (key.startsWith(MessageUtil.QUAL_PREFIX)) { MessageBundle qbundle = _msgmgr.getBundle(getBundle(key)); return qbundle.get(getUnqualifiedKey(key), args); } // Select the proper suffix if our first argument can be coaxed into an integer String suffix = getSuffix(args); String msg = getResourceString(key + suffix, false); if (msg == null) { // Playing with fire: This only works because it's the same "" reference we return from getSuffix() // Don't try this at home. Keep out of reach of children. If swallowed, consult StringUtil.isBlank() if (suffix != "") { // Try the original key msg = getResourceString(key, false); } if (msg == null) { log.warning("Missing translation message", "bundle", _path, "key", key, new Exception()); // return something bogus return (key + StringUtil.toString(args)); } } return MessageFormat.format(MessageUtil.escape(msg), args); } /** * Obtains the translation for the specified message key. The * specified arguments are substituted into the translated string. */ public String get (String key, String... args) { return get(key, (Object[]) args); } /** * A helper function for {@link #get(String,Object[])} that allows us * to automatically perform plurality processing if our first argument * can be coaxed to an {@link Integer}. */ protected String getSuffix (Object[] args) { if (args.length > 0 && args[0] != null) { try { int count = (args[0] instanceof Integer) ? (Integer)args[0] : Integer.parseInt(args[0].toString()); switch (count) { case 0: return ".0"; case 1: return ".1"; default: return ".n"; } } catch (NumberFormatException e) { // Fall out } } return ""; } /** * Obtains the translation for the specified compound message key. A * compound key contains the message key followed by a tab separated * list of message arguments which will be subsituted into the * translation string. * * <p> See {@link MessageFormat} for more information on how the * substitution is performed. If a translation message does not exist * for the specified key, an error is logged and the key itself (plus * the arguments) is returned so that the caller need not worry about * handling a null response. */ public String xlate (String compoundKey) { // if this is a qualified key, we need to pass the buck to the // appropriate message bundle; we have to do it here because we // want the compound arguments of this key to be translated in the // context of the containing message bundle qualification if (compoundKey.startsWith(MessageUtil.QUAL_PREFIX)) { MessageBundle qbundle = _msgmgr.getBundle(getBundle(compoundKey)); return qbundle.xlate(getUnqualifiedKey(compoundKey)); } // to be more efficient about creating unnecessary objects, we // do some checking before splitting int tidx = compoundKey.indexOf('|'); if (tidx == -1) { return get(compoundKey); } else { String key = compoundKey.substring(0, tidx); String argstr = compoundKey.substring(tidx+1); String[] args = StringUtil.split(argstr, "|"); // unescape and translate the arguments for (int i = 0; i < args.length; i++) { // if the argument is tainted, do no further translation // (it might contain |s or other fun stuff) if (args[i].startsWith(MessageUtil.TAINT_CHAR)) { args[i] = MessageUtil.unescape(args[i].substring(1)); } else { args[i] = xlate(MessageUtil.unescape(args[i])); } } return get(key, (Object[]) args); } } @Override public String toString () { return "[bundle=" + _bundle + ", path=" + _path + "]"; } /** The message manager via whom we'll resolve fully qualified * translation strings. */ protected MessageManager _msgmgr; /** The path that identifies the resource bundle we are using to * obtain our messages. */ protected String _path; /** The resource bundle from which we obtain our messages. */ protected ResourceBundle _bundle; /** Our parent bundle if we're not the global bundle. */ protected MessageBundle _parent; }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Cursor; import java.awt.Dialog; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Insets; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Robot; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractListModel; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JProgressBar; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.auth.DefaultUserNameStore; import org.jdesktop.swingx.auth.LoginAdapter; import org.jdesktop.swingx.auth.LoginEvent; import org.jdesktop.swingx.auth.LoginListener; import org.jdesktop.swingx.auth.LoginService; import org.jdesktop.swingx.auth.PasswordStore; import org.jdesktop.swingx.auth.UserNameStore; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.plaf.LoginPaneAddon; import org.jdesktop.swingx.plaf.LoginPaneUI; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.plaf.UIManagerExt; import org.jdesktop.swingx.util.WindowUtils; /** * <p>JXLoginPane is a JPanel that implements a Login dialog with * support for saving passwords supplied for future use in a secure * manner. It is intended to work with <strong>LoginService</strong> * and <strong>PasswordStore</strong> to implement the * authentication.</p> * * <p> In order to perform the authentication, <strong>JXLoginPane</strong> * calls the <code>authenticate</code> method of the <strong>LoginService * </strong>. In order to perform the persistence of the password, * <strong>JXLoginPane</strong> calls the put method of the * <strong>PasswordStore</strong> object that is supplied. If * the <strong>PasswordStore</strong> is <code>null</code>, then the password * is not saved. Similarly, if a <strong>PasswordStore</strong> is * supplied and the password is null, then the <strong>PasswordStore</strong> * will be queried for the password using the <code>get</code> method. * * @author Bino George * @author Shai Almog * @author rbair * @author Karl Schaefer * @author rah003 */ public class JXLoginPane extends JXImagePanel { /** * The Logger */ private static final Logger LOG = Logger.getLogger(JXLoginPane.class.getName()); /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 3544949969896288564L; /** * UI Class ID */ public final static String uiClassID = "LoginPaneUI"; /** * Action key for an Action in the ActionMap that initiates the Login * procedure */ public static final String LOGIN_ACTION_COMMAND = "login"; /** * Action key for an Action in the ActionMap that cancels the Login * procedure */ public static final String CANCEL_LOGIN_ACTION_COMMAND = "cancel-login"; /** * The JXLoginPane can attempt to save certain user information such as * the username, password, or both to their respective stores. * This type specifies what type of save should be performed. */ public static enum SaveMode {NONE, USER_NAME, PASSWORD, BOTH} /** * Returns the status of the login process */ public enum Status {NOT_STARTED, IN_PROGRESS, FAILED, CANCELLED, SUCCEEDED} /** * Used as a prefix when pulling data out of UIManager for i18n */ private static String CLASS_NAME = JXLoginPane.class.getSimpleName(); /** * The current login status for this panel */ private Status status = Status.NOT_STARTED; /** * An optional banner at the top of the panel */ private JXImagePanel banner; /** * Text that should appear on the banner */ private String bannerText; /** * Custom label allowing the developer to display some message to the user */ private JLabel messageLabel; /** * Shows an error message such as "user name or password incorrect" or * "could not contact server" or something like that if something * goes wrong */ private JXLabel errorMessageLabel; /** * A Panel containing all of the input fields, check boxes, etc necessary * for the user to do their job. The items on this panel change whenever * the SaveMode changes, so this panel must be recreated at runtime if the * SaveMode changes. Thus, I must maintain this reference so I can remove * this panel from the content panel at runtime. */ private JXPanel loginPanel; /** * The panel on which the input fields, messageLabel, and errorMessageLabel * are placed. While the login thread is running, this panel is removed * from the dialog and replaced by the progressPanel */ private JXPanel contentPanel; /** * This is the area in which the name field is placed. That way it can toggle on the fly * between text field and a combo box depending on the situation, and have a simple * way to get the user name */ private NameComponent namePanel; /** * The password field presented allowing the user to enter their password */ private JPasswordField passwordField; /** * A combo box presenting the user with a list of servers to which they * may log in. This is an optional feature, which is only enabled if * the List of servers supplied to the JXLoginPane has a length greater * than 1. */ private JComboBox serverCombo; /** * Check box presented if a PasswordStore is used, allowing the user to decide whether to * save their password */ private JCheckBox saveCB; /** * Label displayed whenever caps lock is on. */ private JLabel capsOn; /** * A special panel that displays a progress bar and cancel button, and * which notify the user of the login process, and allow them to cancel * that process. */ private JXPanel progressPanel; /** * A JLabel on the progressPanel that is used for informing the user * of the status of the login procedure (logging in..., canceling login...) */ private JLabel progressMessageLabel; /** * The LoginService to use. This must be specified for the login dialog to operate. * If no LoginService is defined, a default login service is used that simply * allows all users access. This is useful for demos or prototypes where a proper login * server is not available. */ private LoginService loginService; /** * Optional: a PasswordStore to use for storing and retrieving passwords for a specific * user. */ private PasswordStore passwordStore; /** * Optional: a UserNameStore to use for storing user names and retrieving them */ private UserNameStore userNameStore; /** * A list of servers where each server is represented by a String. If the * list of Servers is greater than 1, then a combo box will be presented to * the user to choose from. If any servers are specified, the selected one * (or the only one if servers.size() == 1) will be passed to the LoginService */ private List<String> servers; /** * Whether to save password or username or both */ private SaveMode saveMode; /** * Tracks the cursor at the time that authentication was started, and restores to that * cursor after authentication ends, or is cancelled; */ private Cursor oldCursor; /** * The default login listener used by this panel. */ private LoginListener defaultLoginListener; private CapsOnTest capsOnTest = new CapsOnTest(); private boolean caps; private boolean isTestingCaps; private KeyEventDispatcher capsOnListener = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() != KeyEvent.KEY_PRESSED) { return false; } if (e.getKeyCode() == 20) { setCapsLock(!isCapsLockOn()); } return false; }}; /** * Caps lock detection support */ private boolean capsLockSupport = true; /** * Login/cancel control pane; */ private JXBtnPanel buttonPanel; /** * Window event listener responsible for triggering caps lock test on vindow activation and * focus changes. */ private CapsOnWinListener capsOnWinListener = new CapsOnWinListener(capsOnTest); private boolean initDone; /** * Creates a default JXLoginPane instance */ static { LookAndFeelAddons.contribute(new LoginPaneAddon()); } /** * Populates UIDefaults with the localizable Strings we will use * in the Login panel. */ private void reinitLocales(Locale l) { setBannerText(UIManagerExt.getString(CLASS_NAME + ".bannerString", getLocale())); banner.setImage(createLoginBanner()); // TODO: Can't change the error message since it might have been already changed by the user! //errorMessageLabel.setText(UIManager.getString(CLASS_NAME + ".errorMessage", getLocale())); progressMessageLabel.setText(UIManagerExt.getString(CLASS_NAME + ".pleaseWait", getLocale())); recreateLoginPanel(); Window w = SwingUtilities.getWindowAncestor(this); if (w instanceof JXLoginFrame) { JXLoginFrame f = (JXLoginFrame) w; f.setTitle(UIManagerExt.getString(CLASS_NAME + ".titleString", getLocale())); if (buttonPanel != null) { buttonPanel.getOk().setText(UIManagerExt.getString(CLASS_NAME + ".loginString", getLocale())); buttonPanel.getCancel().setText(UIManagerExt.getString(CLASS_NAME + ".cancelString", getLocale())); } } JLabel lbl = (JLabel) passwordField.getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManagerExt.getString(CLASS_NAME + ".passwordString", getLocale())); } lbl = (JLabel) namePanel.getComponent().getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManagerExt.getString(CLASS_NAME + ".nameString", getLocale())); } if (serverCombo != null) { lbl = (JLabel) serverCombo.getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManagerExt.getString(CLASS_NAME + ".serverString", getLocale())); } } saveCB.setText(UIManagerExt.getString(CLASS_NAME + ".rememberPasswordString", getLocale())); // by default, caps is initialized in off state - i.e. without warning. Setting to // whitespace preserves formatting of the panel. capsOn.setText(isCapsLockOn() ? UIManagerExt.getString(CLASS_NAME + ".capsOnWarning", getLocale()) : " "); } /** * Create a {@code JXLoginPane} that always accepts the user, never stores * passwords or user ids, and has no target servers. * <p> * This constructor should <i>NOT</i> be used in a real application. It is * provided for compliance to the bean specification and for use with visual * editors. */ public JXLoginPane() { this(null); } /** * Create a {@code JXLoginPane} with the specified {@code LoginService} * that does not store user ids or passwords and has no target servers. * * @param service * the {@code LoginService} to use for logging in */ public JXLoginPane(LoginService service) { this(service, null, null); } /** * Create a {@code JXLoginPane} with the specified {@code LoginService}, * {@code PasswordStore}, and {@code UserNameStore}, but without a server * list. * <p> * If you do not want to store passwords or user ids, those parameters can * be {@code null}. {@code SaveMode} is autoconfigured from passed in store * parameters. * * @param service * the {@code LoginService} to use for logging in * @param passwordStore * the {@code PasswordStore} to use for storing password * information * @param userStore * the {@code UserNameStore} to use for storing user information */ public JXLoginPane(LoginService service, PasswordStore passwordStore, UserNameStore userStore) { this(service, passwordStore, userStore, null); } /** * Create a {@code JXLoginPane} with the specified {@code LoginService}, * {@code PasswordStore}, {@code UserNameStore}, and server list. * <p> * If you do not want to store passwords or user ids, those parameters can * be {@code null}. {@code SaveMode} is autoconfigured from passed in store * parameters. * <p> * Setting the server list to {@code null} will unset all of the servers. * The server list is guaranteed to be non-{@code null}. * * @param service * the {@code LoginService} to use for logging in * @param passwordStore * the {@code PasswordStore} to use for storing password * information * @param userStore * the {@code UserNameStore} to use for storing user information * @param servers * a list of servers to authenticate against */ public JXLoginPane(LoginService service, PasswordStore passwordStore, UserNameStore userStore, List<String> servers) { setLoginService(service); setPasswordStore(passwordStore); setUserNameStore(userStore); setServers(servers); //create the login and cancel actions, and add them to the action map getActionMap().put(LOGIN_ACTION_COMMAND, createLoginAction()); getActionMap().put(CANCEL_LOGIN_ACTION_COMMAND, createCancelAction()); //initialize the save mode if (passwordStore != null && userStore != null) { saveMode = SaveMode.BOTH; } else if (passwordStore != null) { saveMode = SaveMode.PASSWORD; } else if (userStore != null) { saveMode = SaveMode.USER_NAME; } else { saveMode = SaveMode.NONE; } updateUI(); if (!initDone) { initComponents(); } updateUI(); } /** * Sets current state of the caps lock key as detected by the component. * @param b True when caps lock is turned on, false otherwise. */ private void setCapsLock(boolean b) { caps = b; capsOn.setText(caps ? UIManagerExt.getString(CLASS_NAME + ".capsOnWarning", getLocale()) : " "); } /** * Gets current state of the caps lock as seen by the login panel. The state seen by the login * panel and therefore returned by this method can be delayed in comparison to the real caps * lock state and displayed by the keyboard light. This is usually the case when component or * its text fields are not focused. * * @return True when caps lock is on, false otherwise. Returns always false when * <code>isCapsLockDetectionSupported()</code> returns false. */ public boolean isCapsLockOn() { return caps; } /** * Check current state of the caps lock state detection. Note that the value can change after * component have been made visible. Due to current problems in locking key state detection by * core java detection of the changes in caps lock can be always reliably determined. When * component can't guarantee reliable detection it will switch it off. This is usually the case * for unsigned applets and webstart invoked application. Since your users are going to pass * their password in the component you should always sign it when distributing application over * the network. * @return True if changes in caps lock state can be monitored by the component, false otherwise. */ public boolean isCapsLockDetectionSupported() { return capsLockSupport; } /** * {@inheritDoc} */ public LoginPaneUI getUI() { return (LoginPaneUI) super.getUI(); } /** * Sets the look and feel (L&F) object that renders this component. * * @param ui the LoginPaneUI L&F object * @see javax.swing.UIDefaults#getUI */ public void setUI(LoginPaneUI ui) { super.setUI(ui); } /** * Notification from the <code>UIManager</code> that the L&F has changed. * Replaces the current UI object with the latest version from the * <code>UIManager</code>. * * @see javax.swing.JComponent#updateUI */ public void updateUI() { if (!initDone) { // called by jpanel <init> when components are not ready yet. return; } setUI((LoginPaneUI) LookAndFeelAddons.getUI(this, LoginPaneUI.class)); } /** * Returns the name of the L&F class that renders this component. * * @return the string {@link #uiClassID} * @see javax.swing.JComponent#getUIClassID * @see javax.swing.UIDefaults#getUI */ public String getUIClassID() { return uiClassID; } /** * Recreates the login panel, and replaces the current one with the new one */ protected void recreateLoginPanel() { contentPanel.remove(loginPanel); loginPanel = createLoginPanel(); loginPanel.setBorder(BorderFactory.createEmptyBorder(0, 36, 7, 11)); contentPanel.add(loginPanel, 1); } /** * Creates and returns a new LoginPanel, based on the SaveMode state of * the login panel. Whenever the SaveMode changes, the panel is recreated. * I do this rather than hiding/showing components, due to a cleaner * implementation (no invisible components, components are not sharing * locations in the LayoutManager, etc). */ private JXPanel createLoginPanel() { JXPanel loginPanel = new JXPanel(); //create the NameComponent if (saveMode == SaveMode.NONE) { namePanel = new SimpleNamePanel(); } else { namePanel = new ComboNamePanel(userNameStore); } JLabel nameLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".nameString", getLocale())); nameLabel.setLabelFor(namePanel.getComponent()); //create the password component passwordField = new JPasswordField("", 15); JLabel passwordLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".passwordString", getLocale())); passwordLabel.setLabelFor(passwordField); //create the server combo box if necessary JLabel serverLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".serverString", getLocale())); if (servers.size() > 1) { serverCombo = new JComboBox(servers.toArray()); serverLabel.setLabelFor(serverCombo); } else { serverCombo = null; } //create the save check box. By default, it is not selected saveCB = new JCheckBox(UIManagerExt.getString(CLASS_NAME + ".rememberPasswordString", getLocale())); saveCB.setIconTextGap(10); saveCB.setSelected(false); //TODO should get this from prefs!!! And, it should be based on the user //determine whether to show/hide the save check box based on the SaveMode saveCB.setVisible(saveMode == SaveMode.PASSWORD || saveMode == SaveMode.BOTH); capsOn = new JLabel(" "); // don't show by default. We perform test when login panel gets focus. int lShift = 3;// lShift is used to align all other components with the checkbox GridLayout grid = new GridLayout(2,1); grid.setVgap(5); JPanel fields = new JPanel(grid); fields.add(namePanel.getComponent()); fields.add(passwordField); loginPanel.setLayout(new GridBagLayout()); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(4, lShift, 5, 11); loginPanel.add(nameLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 1; gridBagConstraints.gridheight = 2; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(fields, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(5, lShift, 5, 11); loginPanel.add(passwordLabel, gridBagConstraints); if (serverCombo != null) { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, lShift, 5, 11); loginPanel.add(serverLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(serverCombo, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 4, 0); loginPanel.add(saveCB, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, lShift, 0, 11); loginPanel.add(capsOn, gridBagConstraints); } else { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 4, 0); loginPanel.add(saveCB, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, lShift, 0, 11); loginPanel.add(capsOn, gridBagConstraints); } return loginPanel; } /** * This method adds functionality to support bidi languages within this * component */ public void setComponentOrientation(ComponentOrientation orient) { // this if is used to avoid needless creations of the image if(orient != super.getComponentOrientation()) { super.setComponentOrientation(orient); banner.setImage(createLoginBanner()); progressPanel.applyComponentOrientation(orient); } } /** * Create all of the UI components for the login panel */ private void initComponents() { //create the default banner banner = new JXImagePanel(); banner.setImage(createLoginBanner()); //create the default label messageLabel = new JLabel(" "); messageLabel.setOpaque(true); messageLabel.setFont(messageLabel.getFont().deriveFont(Font.BOLD)); //create the main components loginPanel = createLoginPanel(); //create the message and hyperlink and hide them errorMessageLabel = new JXLabel(UIManagerExt.getString(CLASS_NAME + ".errorMessage", getLocale())); errorMessageLabel.setIcon(UIManager.getIcon(CLASS_NAME + ".errorIcon", getLocale())); errorMessageLabel.setVerticalTextPosition(SwingConstants.TOP); errorMessageLabel.setLineWrap(true); errorMessageLabel.setPaintBorderInsets(false); errorMessageLabel.setBackgroundPainter(new MattePainter(UIManager.getColor(CLASS_NAME + ".errorBackground", getLocale()), true)); errorMessageLabel.setMaxLineSpan(320); errorMessageLabel.setVisible(false); //aggregate the optional message label, content, and error label into //the contentPanel contentPanel = new JXPanel(new VerticalLayout()); messageLabel.setBorder(BorderFactory.createEmptyBorder(12, 12, 7, 11)); contentPanel.add(messageLabel); loginPanel.setBorder(BorderFactory.createEmptyBorder(0, 36, 7, 11)); contentPanel.add(loginPanel); errorMessageLabel.setBorder(UIManager.getBorder(CLASS_NAME + ".errorBorder", getLocale())); contentPanel.add(errorMessageLabel); //create the progress panel progressPanel = new JXPanel(new GridBagLayout()); progressMessageLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".pleaseWait", getLocale())); progressMessageLabel.setFont(UIManager.getFont("JXLoginPane.pleaseWaitFont", getLocale())); JProgressBar pb = new JProgressBar(); pb.setIndeterminate(true); JButton cancelButton = new JButton(getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND)); progressPanel.add(progressMessageLabel, new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(12, 12, 11, 11), 0, 0)); progressPanel.add(pb, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 24, 11, 7), 0, 0)); progressPanel.add(cancelButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 11, 11), 0, 0)); //layout the panel setLayout(new BorderLayout()); add(banner, BorderLayout.NORTH); add(contentPanel, BorderLayout.CENTER); initDone = true; } /** * Create and return an image to use for the Banner. This may be overridden * to return any image you like */ protected Image createLoginBanner() { return getUI() == null ? null : getUI().getBanner(); } /** * Create and return an Action for logging in */ protected Action createLoginAction() { return new LoginAction(this); } /** * Create and return an Action for canceling login */ protected Action createCancelAction() { return new CancelAction(this); } //TODO need to fire property change events!!! /** * @return Returns the saveMode. */ public SaveMode getSaveMode() { return saveMode; } /** * The save mode indicates whether the "save" password is checked by default. This method * makes no difference if the passwordStore is null. * * @param saveMode The saveMode to set either SAVE_NONE, SAVE_PASSWORD or SAVE_USERNAME */ public void setSaveMode(SaveMode saveMode) { if (this.saveMode != saveMode) { SaveMode oldMode = getSaveMode(); this.saveMode = saveMode; recreateLoginPanel(); firePropertyChange("saveMode", oldMode, getSaveMode()); } } /** * @return the List of servers */ public List<String> getServers() { return Collections.unmodifiableList(servers); } /** * Sets the list of servers. See the servers field javadoc for more info */ public void setServers(List<String> servers) { //only at startup if (this.servers == null) { this.servers = servers == null ? new ArrayList<String>() : servers; } else if (this.servers != servers) { List<String> old = getServers(); this.servers = servers == null ? new ArrayList<String>() : servers; recreateLoginPanel(); firePropertyChange("servers", old, getServers()); } } private LoginListener getDefaultLoginListener() { if (defaultLoginListener == null) { defaultLoginListener = new LoginListenerImpl(); } return defaultLoginListener; } /** * Sets the {@code LoginService} for this panel. Setting the login service * to {@code null} will actually set the service to use * {@code NullLoginService}. * * @param service * the service to set. If {@code service == null}, then a * {@code NullLoginService} is used. */ public void setLoginService(LoginService service) { LoginService oldService = getLoginService(); LoginService newService = service == null ? new NullLoginService() : service; //newService is guaranteed to be nonnull if (!newService.equals(oldService)) { if (oldService != null) { oldService.removeLoginListener(getDefaultLoginListener()); } loginService = newService; this.loginService.addLoginListener(getDefaultLoginListener()); firePropertyChange("loginService", oldService, getLoginService()); } } /** * Gets the <strong>LoginService</strong> for this panel. * * @return service service */ public LoginService getLoginService() { return loginService; } /** * Sets the <strong>PasswordStore</strong> for this panel. * * @param store PasswordStore */ public void setPasswordStore(PasswordStore store) { PasswordStore oldStore = getPasswordStore(); PasswordStore newStore = store == null ? new NullPasswordStore() : store; //newStore is guaranteed to be nonnull if (!newStore.equals(oldStore)) { passwordStore = newStore; firePropertyChange("passwordStore", oldStore, getPasswordStore()); } } /** * Gets the {@code UserNameStore} for this panel. * * @return the {@code UserNameStore} */ public UserNameStore getUserNameStore() { return userNameStore; } /** * Sets the user name store for this panel. * @param store */ public void setUserNameStore(UserNameStore store) { UserNameStore oldStore = getUserNameStore(); UserNameStore newStore = store == null ? new DefaultUserNameStore() : store; //newStore is guaranteed to be nonnull if (!newStore.equals(oldStore)) { userNameStore = newStore; firePropertyChange("userNameStore", oldStore, getUserNameStore()); } } /** * Gets the <strong>PasswordStore</strong> for this panel. * * @return store PasswordStore */ public PasswordStore getPasswordStore() { return passwordStore; } /** * Sets the <strong>User name</strong> for this panel. * * @param username User name */ public void setUserName(String username) { if (namePanel != null) { namePanel.setUserName(username); } } /** * Gets the <strong>User name</strong> for this panel. * @return the user name */ public String getUserName() { return namePanel == null ? null : namePanel.getUserName(); } /** * Sets the <strong>Password</strong> for this panel. * * @param password Password */ public void setPassword(char[] password) { passwordField.setText(new String(password)); } /** * Gets the <strong>Password</strong> for this panel. * * @return password Password */ public char[] getPassword() { return passwordField.getPassword(); } /** * Return the image used as the banner */ public Image getBanner() { return banner.getImage(); } /** * Set the image to use for the banner. If the {@code img} is {@code null}, * then no image will be displayed. * * @param img * the image to display */ public void setBanner(Image img) { // we do not expose the ImagePanel, so we will produce property change // events here Image oldImage = getBanner(); if (oldImage != img) { banner.setImage(img); firePropertyChange("banner", oldImage, getBanner()); } } /** * Set the text to use when creating the banner. If a custom banner image is * specified, then this is ignored. If {@code text} is {@code null}, then * no text is displayed. * * @param text * the text to display */ public void setBannerText(String text) { if (text == null) { text = ""; } if (!text.equals(this.bannerText)) { String oldText = this.bannerText; this.bannerText = text; //fix the login banner banner.setImage(createLoginBanner()); firePropertyChange("bannerText", oldText, text); } } /** * Returns text used when creating the banner */ public String getBannerText() { return bannerText; } /** * Returns the custom message for this login panel */ public String getMessage() { return messageLabel.getText(); } /** * Sets a custom message for this login panel */ public void setMessage(String message) { messageLabel.setText(message); } /** * Returns the error message for this login panel */ public String getErrorMessage() { return errorMessageLabel.getText(); } /** * Sets the error message for this login panel */ public void setErrorMessage(String errorMessage) { errorMessageLabel.setText(errorMessage); } /** * Returns the panel's status */ public Status getStatus() { return status; } /** * Change the status */ protected void setStatus(Status newStatus) { if (status != newStatus) { Status oldStatus = status; status = newStatus; firePropertyChange("status", oldStatus, newStatus); } } public void setLocale(Locale l) { super.setLocale(l); reinitLocales(l); } /** * Initiates the login procedure. This method is called internally by * the LoginAction. This method handles cursor management, and actually * calling the LoginService's startAuthentication method. */ protected void startLogin() { oldCursor = getCursor(); try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); progressMessageLabel.setText(UIManagerExt.getString(CLASS_NAME + ".pleaseWait", getLocale())); String name = getUserName(); char[] password = getPassword(); String server = servers.size() == 1 ? servers.get(0) : serverCombo == null ? null : (String)serverCombo.getSelectedItem(); loginService.startAuthentication(name, password, server); } catch(Exception ex) { //The status is set via the loginService listener, so no need to set //the status here. Just log the error. LOG.log(Level.WARNING, "Authentication exception while logging in", ex); } finally { setCursor(oldCursor); } } /** * Cancels the login procedure. Handles cursor management and interfacing * with the LoginService's cancelAuthentication method */ protected void cancelLogin() { progressMessageLabel.setText(UIManagerExt.getString(CLASS_NAME + ".cancelWait", getLocale())); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(false); loginService.cancelAuthentication(); setCursor(oldCursor); } /** * Puts the password into the password store. If password store is not set, method will do * nothing. */ protected void savePassword() { if (saveCB.isSelected() && (saveMode == SaveMode.BOTH || saveMode == SaveMode.PASSWORD) && passwordStore != null) { passwordStore.set(getUserName(),getLoginService().getServer(),getPassword()); } } public void removeNotify() { try { // TODO: keep it here until all ui stuff is moved to uidelegate. if (capsLockSupport) KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(capsOnListener); Container c = JXLoginPane.this; while (c.getParent() != null) { c = c.getParent(); } if (c instanceof Window) { Window w = (Window) c; w.removeWindowFocusListener(capsOnWinListener ); w.removeWindowListener(capsOnWinListener ); } } catch (Exception e) { // bail out probably in unsigned app distributed over web } super.removeNotify(); } public void addNotify() { try { KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher( capsOnListener); Container c = JXLoginPane.this; while (c.getParent() != null) { c = c.getParent(); } if (c instanceof Window) { Window w = (Window) c; w.addWindowFocusListener(capsOnWinListener ); w.addWindowListener(capsOnWinListener); } } catch (Exception e) { // probably unsigned app over web, disable capslock support and bail out capsLockSupport = false; } super.addNotify(); } /* For Login (initiated in LoginAction): 0) set the status 1) Immediately disable the login action 2) Immediately disable the close action (part of enclosing window) 3) initialize the progress pane a) enable the cancel login action b) set the message text 4) hide the content pane, show the progress pane When cancelling (initiated in CancelAction): 0) set the status 1) Disable the cancel login action 2) Change the message text on the progress pane When cancel finishes (handled in LoginListener): 0) set the status 1) hide the progress pane, show the content pane 2) enable the close action (part of enclosing window) 3) enable the login action When login fails (handled in LoginListener): 0) set the status 1) hide the progress pane, show the content pane 2) enable the close action (part of enclosing window) 3) enable the login action 4) Show the error message 5) resize the window (part of enclosing window) When login succeeds (handled in LoginListener): 0) set the status 1) close the dialog/frame (part of enclosing window) */ /** * Listener class to track state in the LoginService */ protected class LoginListenerImpl extends LoginAdapter { public void loginSucceeded(LoginEvent source) { //save the user names and passwords String userName = namePanel.getUserName(); savePassword(); if ((getSaveMode() == SaveMode.USER_NAME || getSaveMode() == SaveMode.BOTH) && userName != null && !userName.trim().equals("")) { userNameStore.addUserName(userName); userNameStore.saveUserNames(); } setStatus(Status.SUCCEEDED); } public void loginStarted(LoginEvent source) { getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(false); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(true); remove(contentPanel); add(progressPanel, BorderLayout.CENTER); revalidate(); repaint(); setStatus(Status.IN_PROGRESS); } public void loginFailed(LoginEvent source) { remove(progressPanel); add(contentPanel, BorderLayout.CENTER); getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(true); errorMessageLabel.setVisible(true); revalidate(); repaint(); setStatus(Status.FAILED); } public void loginCanceled(LoginEvent source) { remove(progressPanel); add(contentPanel, BorderLayout.CENTER); getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(true); errorMessageLabel.setVisible(false); revalidate(); repaint(); setStatus(Status.CANCELLED); } } /** * Action that initiates a login procedure. Delegates to JXLoginPane.startLogin */ private static final class LoginAction extends AbstractActionExt { private JXLoginPane panel; public LoginAction(JXLoginPane p) { super(UIManagerExt.getString(CLASS_NAME + ".loginString", p.getLocale()), LOGIN_ACTION_COMMAND); this.panel = p; } public void actionPerformed(ActionEvent e) { panel.startLogin(); } public void itemStateChanged(ItemEvent e) {} } /** * Action that cancels the login procedure. */ private static final class CancelAction extends AbstractActionExt { private JXLoginPane panel; public CancelAction(JXLoginPane p) { //TODO localize super(UIManager.getString(CLASS_NAME + ".cancelLogin"), CANCEL_LOGIN_ACTION_COMMAND); this.panel = p; this.setEnabled(false); } public void actionPerformed(ActionEvent e) { panel.cancelLogin(); } public void itemStateChanged(ItemEvent e) {} } /** * Simple login service that allows everybody to login. This is useful in demos and allows * us to avoid having to check for LoginService being null */ private static final class NullLoginService extends LoginService { public boolean authenticate(String name, char[] password, String server) throws Exception { return true; } public boolean equals(Object obj) { return obj instanceof NullLoginService; } public int hashCode() { return 7; } } /** * Simple PasswordStore that does not remember passwords */ private static final class NullPasswordStore extends PasswordStore { private static final char[] EMPTY = new char[0]; public boolean set(String username, String server, char[] password) { //null op return false; } public char[] get(String username, String server) { return EMPTY; } public boolean equals(Object obj) { return obj instanceof NullPasswordStore; } public int hashCode() { return 7; } } public static interface NameComponent { public String getUserName(); public void setUserName(String userName); public JComponent getComponent(); } /** * If a UserNameStore is not used, then this text field is presented allowing the user * to simply enter their user name */ public static final class SimpleNamePanel extends JTextField implements NameComponent { public SimpleNamePanel() { super("", 15); } public String getUserName() { return getText(); } public void setUserName(String userName) { setText(userName); } public JComponent getComponent() { return this; } } /** * If a UserNameStore is used, then this combo box is presented allowing the user * to select a previous login name, or type in a new login name */ public static final class ComboNamePanel extends JComboBox implements NameComponent { private UserNameStore userNameStore; public ComboNamePanel(UserNameStore userNameStore) { super(); this.userNameStore = userNameStore; setModel(new NameComboBoxModel()); setEditable(true); } public String getUserName() { Object item = getModel().getSelectedItem(); return item == null ? null : item.toString(); } public void setUserName(String userName) { getModel().setSelectedItem(userName); } public void setUserNames(String[] names) { setModel(new DefaultComboBoxModel(names)); } public JComponent getComponent() { return this; } private final class NameComboBoxModel extends AbstractListModel implements ComboBoxModel { private Object selectedItem; public void setSelectedItem(Object anItem) { selectedItem = anItem; fireContentsChanged(this, -1, -1); } public Object getSelectedItem() { return selectedItem; } public Object getElementAt(int index) { return userNameStore.getUserNames()[index]; } public int getSize() { return userNameStore.getUserNames().length; } } } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc) { return showLoginDialog(parent, svc, null, null); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc, PasswordStore ps, UserNameStore us) { return showLoginDialog(parent, svc, ps, us, null); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc, PasswordStore ps, UserNameStore us, List<String> servers) { JXLoginPane panel = new JXLoginPane(svc, ps, us, servers); return showLoginDialog(parent, panel); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, JXLoginPane panel) { Window w = WindowUtils.findWindow(parent); JXLoginDialog dlg = null; if (w == null) { dlg = new JXLoginDialog((Frame)null, panel); } else if (w instanceof Dialog) { dlg = new JXLoginDialog((Dialog)w, panel); } else if (w instanceof Frame) { dlg = new JXLoginDialog((Frame)w, panel); } else { throw new AssertionError("Shouldn't be able to happen"); } dlg.setVisible(true); return dlg.getStatus(); } /** * Shows a login frame. A JFrame is not modal, and thus does not block */ public static JXLoginFrame showLoginFrame(LoginService svc) { return showLoginFrame(svc, null, null); } public static JXLoginFrame showLoginFrame(LoginService svc, PasswordStore ps, UserNameStore us) { return showLoginFrame(svc, ps, us, null); } public static JXLoginFrame showLoginFrame(LoginService svc, PasswordStore ps, UserNameStore us, List<String> servers) { JXLoginPane panel = new JXLoginPane(svc, ps, us, servers); return showLoginFrame(panel); } public static JXLoginFrame showLoginFrame(JXLoginPane panel) { return new JXLoginFrame(panel); } public static final class JXLoginDialog extends JDialog { private JXLoginPane panel; public JXLoginDialog(Frame parent, JXLoginPane p) { super(parent, true); init(p); } public JXLoginDialog(Dialog parent, JXLoginPane p) { super(parent, true); init(p); } protected void init(JXLoginPane p) { setTitle(UIManagerExt.getString(CLASS_NAME + ".titleString", getLocale())); this.panel = p; initWindow(this, panel); } public JXLoginPane.Status getStatus() { return panel.getStatus(); } } public static final class JXLoginFrame extends JFrame { private JXLoginPane panel; public JXLoginFrame(JXLoginPane p) { super(UIManagerExt.getString(CLASS_NAME + ".titleString", p.getLocale())); this.panel = p; initWindow(this, panel); } public JXLoginPane.Status getStatus() { return panel.getStatus(); } public JXLoginPane getPanel() { return panel; } } /** * Utility method for initializing a Window for displaying a LoginDialog. * This is particularly useful because the differences between JFrame and * JDialog are so minor. * * Note: This method is package private for use by JXLoginDialog (proper, * not JXLoginPane.JXLoginDialog). Change to private if JXLoginDialog is * removed. */ static void initWindow(final Window w, final JXLoginPane panel) { w.setLayout(new BorderLayout()); w.add(panel, BorderLayout.CENTER); JButton okButton = new JButton(panel.getActionMap().get(LOGIN_ACTION_COMMAND)); final JButton cancelButton = new JButton( UIManagerExt.getString(CLASS_NAME + ".cancelString", panel.getLocale())); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //change panel status to cancelled! panel.status = JXLoginPane.Status.CANCELLED; w.setVisible(false); w.dispose(); } }); panel.addPropertyChangeListener("status", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { JXLoginPane.Status status = (JXLoginPane.Status)evt.getNewValue(); switch (status) { case NOT_STARTED: break; case IN_PROGRESS: cancelButton.setEnabled(false); break; case CANCELLED: cancelButton.setEnabled(true); w.pack(); break; case FAILED: cancelButton.setEnabled(true); w.pack(); break; case SUCCEEDED: w.setVisible(false); w.dispose(); } for (PropertyChangeListener l : w.getPropertyChangeListeners("status")) { PropertyChangeEvent pce = new PropertyChangeEvent(w, "status", evt.getOldValue(), evt.getNewValue()); l.propertyChange(pce); } } }); // FIX for #663 - commented out two lines below. Not sure why they were here in a first place. // cancelButton.setText(UIManager.getString(CLASS_NAME + ".cancelString")); // okButton.setText(UIManager.getString(CLASS_NAME + ".loginString")); JXBtnPanel buttonPanel = new JXBtnPanel(okButton, cancelButton); panel.setButtonPanel(buttonPanel); JXPanel controls = new JXPanel(new FlowLayout(FlowLayout.RIGHT)); new BoxLayout(controls, BoxLayout.X_AXIS); controls.add(Box.createHorizontalGlue()); controls.add(buttonPanel); w.add(controls, BorderLayout.SOUTH); w.addWindowListener(new WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { panel.cancelLogin(); } }); if (w instanceof JFrame) { final JFrame f = (JFrame)w; f.getRootPane().setDefaultButton(okButton); f.setResizable(false); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); ActionListener closeAction = new ActionListener() { public void actionPerformed(ActionEvent e) { f.setVisible(false); f.dispose(); } }; f.getRootPane().registerKeyboardAction(closeAction, ks, JComponent.WHEN_IN_FOCUSED_WINDOW); } else if (w instanceof JDialog) { final JDialog d = (JDialog)w; d.getRootPane().setDefaultButton(okButton); d.setResizable(false); KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); ActionListener closeAction = new ActionListener() { public void actionPerformed(ActionEvent e) { d.setVisible(false); } }; d.getRootPane().registerKeyboardAction(closeAction, ks, JComponent.WHEN_IN_FOCUSED_WINDOW); } w.pack(); w.setLocation(WindowUtils.getPointForCentering(w)); } private void setButtonPanel(JXBtnPanel buttonPanel) { this.buttonPanel = buttonPanel; } private static class JXBtnPanel extends JXPanel { private JButton cancel; private JButton ok; public JXBtnPanel(JButton okButton, JButton cancelButton) { GridLayout layout = new GridLayout(1,2); layout.setHgap(5); setLayout(layout); this.ok = okButton; this.cancel = cancelButton; add(okButton); add(cancelButton); setBorder(new EmptyBorder(0,0,7,11)); } /** * @return the cancel */ public JButton getCancel() { return cancel; } /** * @return the ok */ public JButton getOk() { return ok; } } private class CapsOnTest { public void runTest() { boolean success = false; // TODO: check the progress from time to time //try { // java.awt.Toolkit.getDefaultToolkit().getLockingKeyState(java.awt.event.KeyEvent.VK_CAPS_LOCK); // System.out.println("GOTCHA"); //} catch (Exception ex) { //ex.printStackTrace(); //success = false; if (!success) { try { //Temporarily installed listener with auto-uninstall after test is finished. KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher( new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() != KeyEvent.KEY_PRESSED) { return true; } if (isTestingCaps && e.getKeyCode() > 64 && e.getKeyCode() < 91) { setCapsLock (!e.isShiftDown() && Character.isUpperCase(e.getKeyChar())); } if (isTestingCaps && (e.getKeyCode() == KeyEvent.VK_BACK_SPACE)) { //uninstall isTestingCaps = false; KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(this); } return true; }}); Robot r = new Robot(); isTestingCaps = true; r.keyPress(65); r.keyRelease(65); r.keyPress(KeyEvent.VK_BACK_SPACE); r.keyRelease(KeyEvent.VK_BACK_SPACE); } catch (Exception e1) { // this can happen for example due to security reasons in unsigned applets // when we can't test caps lock state programatically bail out silently } } } } /** * Window event listener to invoke capslock test when login panel get activated. */ public static class CapsOnWinListener extends WindowAdapter implements WindowFocusListener { private CapsOnTest cot; private long stamp; public CapsOnWinListener(CapsOnTest cot) { this.cot = cot; } public void windowActivated(WindowEvent e) { cot.runTest(); stamp = System.currentTimeMillis(); } public void windowGainedFocus(WindowEvent e) { // repeat test only if more then 20ms passed between activation test and now. if (stamp + 20 < System.currentTimeMillis()) { cot.runTest(); } } public void windowLostFocus(WindowEvent e) { // ignore } } }
package org.jsimpledb.util; import com.google.common.base.Function; import java.io.File; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URL; import java.net.URLClassLoader; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashSet; import org.dellroad.stuff.main.MainClass; import org.dellroad.stuff.net.TCPNetwork; import org.jsimpledb.JSimpleDBFactory; import org.jsimpledb.annotation.JFieldType; import org.jsimpledb.core.Database; import org.jsimpledb.core.FieldType; import org.jsimpledb.kv.KVDatabase; import org.jsimpledb.kv.array.ArrayKVDatabase; import org.jsimpledb.kv.array.AtomicArrayKVStore; import org.jsimpledb.kv.bdb.BerkeleyKVDatabase; import org.jsimpledb.kv.fdb.FoundationKVDatabase; import org.jsimpledb.kv.leveldb.LevelDBAtomicKVStore; import org.jsimpledb.kv.leveldb.LevelDBKVDatabase; import org.jsimpledb.kv.mvcc.AtomicKVDatabase; import org.jsimpledb.kv.mvcc.AtomicKVStore; import org.jsimpledb.kv.raft.RaftKVDatabase; import org.jsimpledb.kv.raft.fallback.FallbackKVDatabase; import org.jsimpledb.kv.raft.fallback.FallbackTarget; import org.jsimpledb.kv.raft.fallback.MergeStrategy; import org.jsimpledb.kv.raft.fallback.NullMergeStrategy; import org.jsimpledb.kv.raft.fallback.OverwriteMergeStrategy; import org.jsimpledb.kv.rocksdb.RocksDBAtomicKVStore; import org.jsimpledb.kv.rocksdb.RocksDBKVDatabase; import org.jsimpledb.kv.simple.SimpleKVDatabase; import org.jsimpledb.kv.simple.XMLKVDatabase; import org.jsimpledb.kv.sql.MySQLKVDatabase; import org.jsimpledb.spring.JSimpleDBClassScanner; import org.jsimpledb.spring.JSimpleDBFieldTypeScanner; import org.springframework.jdbc.datasource.DriverManagerDataSource; /** * Support superclass for main entry point classes. */ public abstract class AbstractMain extends MainClass { private static final File DEMO_XML_FILE = new File("demo-database.xml"); private static final File DEMO_SUBDIR = new File("demo-classes"); private static final String MYSQL_DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver"; // DBTypes that have multiple config flags protected FoundationDBType foundationDBType; protected BerkeleyDBType berkeleyDBType; protected RaftDBType raftDBType; protected FallbackDBType fallbackDBType; // Schema protected int schemaVersion; protected HashSet<Class<?>> schemaClasses; protected HashSet<Class<? extends FieldType<?>>> fieldTypeClasses; protected boolean allowNewSchema; protected DBType<?> dbType; protected KVDatabase kvdb; protected String databaseDescription; // Misc protected boolean verbose; protected boolean readOnly; protected boolean allowAutoDemo = true; /** * Parse command line options. * * @param params command line parameters * @return -1 to proceed, otherwise process exit value */ public int parseOptions(ArrayDeque<String> params) { // Parse options final ArrayList<DBType<?>> dbTypes = new ArrayList<>(); String raftFallbackUnavailableMergeClassName = OverwriteMergeStrategy.class.getName(); String raftFallbackRejoinMergeClassName = NullMergeStrategy.class.getName(); final LinkedHashSet<String> modelPackages = new LinkedHashSet<>(); final LinkedHashSet<String> typePackages = new LinkedHashSet<>(); while (!params.isEmpty() && params.peekFirst().startsWith("-")) { final String option = params.removeFirst(); if (option.equals("-h") || option.equals("--help")) { this.usageMessage(); return 0; } else if (option.equals("-ro") || option.equals("--read-only")) this.readOnly = true; else if (option.equals("-cp") || option.equals("--classpath")) { if (params.isEmpty()) this.usageError(); if (!this.appendClasspath(params.removeFirst())) return 1; } else if (option.equals("--verbose")) this.verbose = true; else if (option.equals("-v") || option.equals("--schema-version")) { if (params.isEmpty()) this.usageError(); final String vstring = params.removeFirst(); try { this.schemaVersion = Integer.parseInt(vstring); if (this.schemaVersion < 0) throw new IllegalArgumentException("schema version is negative"); } catch (Exception e) { System.err.println(this.getName() + ": invalid schema version `" + vstring + "': " + e.getMessage()); return 1; } } else if (option.equals("--model-pkg")) { if (params.isEmpty()) this.usageError(); modelPackages.add(params.removeFirst()); } else if (option.equals("--type-pkg")) { if (params.isEmpty()) this.usageError(); typePackages.add(params.removeFirst()); } else if (option.equals("-p") || option.equals("--pkg")) { if (params.isEmpty()) this.usageError(); final String packageName = params.removeFirst(); modelPackages.add(packageName); typePackages.add(packageName); } else if (option.equals("--new-schema")) { this.allowNewSchema = true; this.allowAutoDemo = false; } else if (option.equals("--mem")) dbTypes.add(new MemoryDBType()); else if (option.equals("--fdb-prefix")) { if (params.isEmpty()) this.usageError(); if (this.foundationDBType == null) { System.err.println(this.getName() + ": `--fdb' must appear before `" + option + "'"); return 1; } final String value = params.removeFirst(); byte[] prefix; try { prefix = ByteUtil.parse(value); } catch (IllegalArgumentException e) { prefix = value.getBytes(Charset.forName("UTF-8")); } if (prefix.length > 0) this.allowAutoDemo = false; this.foundationDBType.setPrefix(prefix); } else if (option.equals("--fdb")) { if (params.isEmpty()) this.usageError(); final String clusterFile = params.removeFirst(); if (!new File(clusterFile).exists()) { System.err.println(this.getName() + ": file `" + clusterFile + "' does not exist"); return 1; } this.foundationDBType = new FoundationDBType(clusterFile); dbTypes.add(this.foundationDBType); } else if (option.equals("--xml")) { if (params.isEmpty()) this.usageError(); dbTypes.add(new XMLDBType(new File(params.removeFirst()))); } else if (option.equals("--bdb")) { if (params.isEmpty()) this.usageError(); final File dir = new File(params.removeFirst()); if (!this.createDirectory(dir)) return 1; this.berkeleyDBType = new BerkeleyDBType(dir); dbTypes.add(this.berkeleyDBType); } else if (option.equals("--bdb-database")) { if (params.isEmpty()) this.usageError(); if (this.berkeleyDBType == null) { System.err.println(this.getName() + ": `--bdb' must appear before `" + option + "'"); return 1; } this.berkeleyDBType.setDatabaseName(params.removeFirst()); } else if (option.equals("--mysql")) { if (params.isEmpty()) this.usageError(); dbTypes.add(new MySQLDBType(params.removeFirst())); } else if (option.equals("--leveldb")) { if (params.isEmpty()) this.usageError(); final File dir = new File(params.removeFirst()); if (!this.createDirectory(dir)) return 1; dbTypes.add(new LevelDBType(dir)); } else if (option.equals("--rocksdb")) { if (params.isEmpty()) this.usageError(); final File dir = new File(params.removeFirst()); if (!this.createDirectory(dir)) return 1; dbTypes.add(new RocksDBType(dir)); } else if (option.equals("--arraydb")) { if (params.isEmpty()) this.usageError(); final File dir = new File(params.removeFirst()); if (!this.createDirectory(dir)) return 1; dbTypes.add(new ArrayDBType(dir)); } else if (option.equals("--raft") || option.equals("--raft-dir")) { // --raft-dir is backward compat. if (params.isEmpty()) this.usageError(); final File dir = new File(params.removeFirst()); if (!this.createDirectory(dir)) return 1; this.raftDBType = new RaftDBType(dir); dbTypes.add(this.raftDBType); } else if (option.matches("--raft-((min|max)-election|heartbeat)-timeout")) { if (params.isEmpty()) this.usageError(); if (this.raftDBType == null) { System.err.println(this.getName() + ": `--raft' must appear before `" + option + "'"); return 1; } final String tstring = params.removeFirst(); final int timeout; try { timeout = Integer.parseInt(tstring); } catch (Exception e) { System.err.println(this.getName() + ": invalid timeout value `" + tstring + "': " + e.getMessage()); return 1; } if (option.equals("--raft-min-election-timeout")) this.raftDBType.setMinElectionTimeout(timeout); else if (option.equals("--raft-max-election-timeout")) this.raftDBType.setMaxElectionTimeout(timeout); else if (option.equals("--raft-heartbeat-timeout")) this.raftDBType.setHeartbeatTimeout(timeout); else throw new RuntimeException("internal error"); } else if (option.equals("--raft-identity")) { if (params.isEmpty()) this.usageError(); if (this.raftDBType == null) { System.err.println(this.getName() + ": `--raft' must appear before `" + option + "'"); return 1; } this.raftDBType.setIdentity(params.removeFirst()); } else if (option.equals("--raft-address")) { if (params.isEmpty()) this.usageError(); if (this.raftDBType == null) { System.err.println(this.getName() + ": `--raft' must appear before `" + option + "'"); return 1; } final String address = params.removeFirst(); this.raftDBType.setAddress(TCPNetwork.parseAddressPart(address)); this.raftDBType.setPort(TCPNetwork.parsePortPart(address, this.raftDBType.getPort())); } else if (option.equals("--raft-port")) { if (params.isEmpty()) this.usageError(); if (this.raftDBType == null) { System.err.println(this.getName() + ": `--raft' must appear before `" + option + "'"); return 1; } final String portString = params.removeFirst(); final int port = TCPNetwork.parsePortPart("x:" + portString, -1); if (port == -1) { System.err.println(this.getName() + ": invalid TCP port `" + portString + "'"); return 1; } this.raftDBType.setPort(port); } else if (option.equals("--raft-fallback")) { if (this.fallbackDBType != null) { System.err.println(this.getName() + ": duplicate `" + option + "' flag"); return 1; } this.fallbackDBType = new FallbackDBType(); dbTypes.add(this.fallbackDBType); } else if (option.matches("--raft-fallback-(check-(interval|timeout)|min-(un)?available)")) { if (params.isEmpty()) this.usageError(); if (this.fallbackDBType == null) { System.err.println(this.getName() + ": `--raft-fallback' must appear before `" + option + "'"); return 1; } final String tstring = params.removeFirst(); final int millis; try { millis = Integer.parseInt(tstring); } catch (Exception e) { System.err.println(this.getName() + ": invalid milliseconds value `" + tstring + "': " + e.getMessage()); return 1; } if (option.equals("--raft-fallback-check-interval")) this.fallbackDBType.getFallbackTarget().setCheckInterval(millis); else if (option.equals("--raft-fallback-check-timeout")) this.fallbackDBType.getFallbackTarget().setTransactionTimeout(millis); else if (option.equals("--raft-fallback-min-available")) this.fallbackDBType.getFallbackTarget().setMinAvailableTime(millis); else if (option.equals("--raft-fallback-min-unavailable")) this.fallbackDBType.getFallbackTarget().setMinUnavailableTime(millis); else throw new RuntimeException("internal error"); } else if (option.equals("--raft-fallback-unavailable-merge")) { if (params.isEmpty()) this.usageError(); if (this.fallbackDBType == null) { System.err.println(this.getName() + ": `--raft-fallback' must appear before `" + option + "'"); return 1; } raftFallbackUnavailableMergeClassName = params.removeFirst(); } else if (option.equals("--raft-fallback-rejoin-merge")) { if (params.isEmpty()) this.usageError(); if (this.fallbackDBType == null) { System.err.println(this.getName() + ": `--raft-fallback' must appear before `" + option + "'"); return 1; } raftFallbackRejoinMergeClassName = params.removeFirst(); } else if (option.equals(" break; else if (!this.parseOption(option, params)) { System.err.println(this.getName() + ": unknown option `" + option + "'"); this.usageError(); return 1; } } // Additional logic post-processing of options if (!modelPackages.isEmpty() || !typePackages.isEmpty()) this.allowAutoDemo = false; // Pull out standalone k/v type for Raft fallback if (this.fallbackDBType != null) { final int fallbackIndex = dbTypes.indexOf(this.fallbackDBType); if (fallbackIndex == dbTypes.size() - 1) { System.err.println(this.getName() + ": Raft fallback mode requires an additional peristent store" + " to be used for standalone mode, specified after `--raft-fallback'; use one of `--arraydb', etc."); return 1; } final DBType<?> standaloneDBType = dbTypes.remove(fallbackIndex + 1); if (!standaloneDBType.canBeFallbackStandalone()) { System.err.println(this.getName() + ": incompatible key/value database `" + standaloneDBType.getDescription() + "' for Raft fallback standalone mode"); return 1; } this.fallbackDBType.setStandaloneDBType(standaloneDBType); } // Pull out local store k/v type for Raft if (this.raftDBType != null) { final int raftIndex = dbTypes.indexOf(this.raftDBType); if (raftIndex == dbTypes.size() - 1) { System.err.println(this.getName() + ": Raft raft requires an additional peristent store" + " to be used for private local storage, specified after `--raft'; use one of `--arraydb', etc."); return 1; } final DBType<?> localStorageDBType = dbTypes.remove(raftIndex + 1); if (!localStorageDBType.canBeRaftLocalStorage()) { System.err.println(this.getName() + ": incompatible key/value database `" + localStorageDBType.getDescription() + "' for Raft local storage"); return 1; } this.raftDBType.setLocalStorageDBType(localStorageDBType); } // Pull out Raft k/v type for Raft fallback if (this.fallbackDBType != null) { if (this.raftDBType == null) { System.err.println(this.getName() + ": Raft fallback mode requires a configured Raft database; use `--raft', etc."); return 1; } this.fallbackDBType.setRaftDBType(this.raftDBType); dbTypes.remove(this.raftDBType); } // Resolve fallback merge strategy class names (do this here so we benefit from any `--classpath' additions) if (this.fallbackDBType != null) { final String[] classNames = new String[] { raftFallbackUnavailableMergeClassName, raftFallbackRejoinMergeClassName }; final MergeStrategy[] mergeStrategies = new MergeStrategy[2]; for (int i = 0; i < 2; i++) { try { mergeStrategies[i] = (MergeStrategy)this.loadClass(classNames[i]).newInstance(); } catch (Exception e) { System.err.println(this.getName() + ": invalid Raft fallback merge strategy `" + classNames[i] + "': " + e.getMessage()); this.usageError(); return 1; } } this.fallbackDBType.getFallbackTarget().setUnavailableMergeStrategy(mergeStrategies[0]); this.fallbackDBType.getFallbackTarget().setRejoinMergeStrategy(mergeStrategies[1]); } // Check database choice(s) switch (dbTypes.size()) { case 0: if (this.allowAutoDemo && DEMO_XML_FILE.exists() && DEMO_SUBDIR.exists()) { // Configure database System.err.println(this.getName() + ": auto-configuring use of demo database `" + DEMO_XML_FILE + "'"); if (dbTypes.isEmpty()) dbTypes.add(new XMLDBType(DEMO_XML_FILE)); // Add demo subdirectory to class path this.appendClasspath(DEMO_SUBDIR.toString()); // Scan classes this.scanModelClasses("org.jsimpledb.demo"); } else { System.err.println(this.getName() + ": no key/value store specified; use one of `--arraydb', etc."); this.usageError(); return 1; } break; case 1: break; default: System.err.println(this.getName() + ": more than one key/value store was specified"); this.usageError(); return 1; } this.dbType = dbTypes.get(0); // Scan for model and type classes final LinkedHashSet<String> emptyPackages = new LinkedHashSet<>(); emptyPackages.addAll(modelPackages); emptyPackages.addAll(typePackages); for (String packageName : modelPackages) { if (this.scanModelClasses(packageName) > 0) emptyPackages.remove(packageName); } for (String packageName : typePackages) { if (this.scanTypeClasses(packageName) > 0) emptyPackages.remove(packageName); } // Warn if we didn't find anything for (String packageName : emptyPackages) { final boolean isModel = modelPackages.contains(packageName); final boolean isType = typePackages.contains(packageName); if (isModel && isType) this.log.warn("no Java model or custom FieldType classes found under package `" + packageName + "'"); else if (isModel) this.log.warn("no Java model classes found under package `" + packageName + "'"); else this.log.warn("no custom FieldType classes found under package `" + packageName + "'"); } // Done return -1; } public int getSchemaVersion() { return this.schemaVersion; } public boolean isAllowNewSchema() { return this.allowNewSchema; } public boolean isReadOnly() { return this.readOnly; } public String getDatabaseDescription() { return this.databaseDescription; } public JSimpleDBFactory getJSimpleDBFactory(Database db) { return new JSimpleDBFactory() .setModelClasses(this.schemaClasses) .setSchemaVersion(this.schemaVersion) .setDatabase(db); } /** * Subclass hook to parse unrecognized command line options. * * @param option command line option (starting with `-') * @param params subsequent command line parameters * @return true if successful, false otherwise */ protected boolean parseOption(String option, ArrayDeque<String> params) { return false; } /** * Append path(s) to the classpath. * * @param path classpath path component * @return true if successful, false if an error occured */ protected boolean appendClasspath(String path) { this.log.trace("adding classpath `" + path + "' to system classpath"); try { // Get URLClassLoader.addURL() method and make accessible final Method addURLMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); addURLMethod.setAccessible(true); // Split path and add components for (String file : path.split(System.getProperty("path.separator", ":"))) { if (file.length() == 0) continue; addURLMethod.invoke(ClassLoader.getSystemClassLoader(), new Object[] { new File(file).toURI().toURL() }); this.log.trace("added path component `" + file + "' to system classpath"); } return true; } catch (Exception e) { this.log.error("can't append `" + path + " to classpath: " + e, e); return false; } } private int scanModelClasses(String pkgname) { if (this.schemaClasses == null) this.schemaClasses = new HashSet<>(); int count = 0; for (String className : new JSimpleDBClassScanner().scanForClasses(pkgname.split("[\\s,]"))) { this.log.debug("loading Java model class " + className); this.schemaClasses.add(this.loadClass(className)); count++; } return count; } private int scanTypeClasses(String pkgname) { // Check types of annotated classes as we scan them final Function<Class<?>, Class<? extends FieldType<?>>> checkFunction = new Function<Class<?>, Class<? extends FieldType<?>>>() { @Override @SuppressWarnings("unchecked") public Class<? extends FieldType<?>> apply(Class<?> type) { try { return (Class<? extends FieldType<?>>)type.asSubclass(FieldType.class); } catch (ClassCastException e) { throw new IllegalArgumentException("invalid @" + JFieldType.class.getSimpleName() + " annotation on " + type + ": type is not a subclass of " + FieldType.class); } } }; // Scan classes if (this.fieldTypeClasses == null) this.fieldTypeClasses = new HashSet<>(); int count = 0; for (String className : new JSimpleDBFieldTypeScanner().scanForClasses(pkgname.split("[\\s,]"))) { this.log.debug("loading custom FieldType class " + className); this.fieldTypeClasses.add(checkFunction.apply(this.loadClass(className))); count++; } return count; } private boolean createDirectory(File dir) { if (!dir.exists() && !dir.mkdirs()) { System.err.println(this.getName() + ": could not create directory `" + dir + "'"); return false; } if (!dir.isDirectory()) { System.err.println(this.getName() + ": file `" + dir + "' is not a directory"); return false; } return true; } /** * Load a class. * * @param className class name * @return class with name {@code className} * @throws RuntimeException if load fails */ protected Class<?> loadClass(String className) { try { return Class.forName(className, false, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { throw new RuntimeException("failed to load class `" + className + "'", e); } } /** * Start the {@link Database} based on the configured {@link KVDatabase} and {@link #fieldTypeClasses} and return it. * * @return initialized database */ protected Database startupKVDatabase() { // Create and start up database this.kvdb = this.dbType.createKVDatabase(); this.databaseDescription = this.dbType.getDescription(); AbstractMain.startKVDatabase(this.dbType, this.kvdb); this.log.debug("using database: " + this.databaseDescription); // Construct core Database final Database db = new Database(this.kvdb); // Register custom field types if (this.fieldTypeClasses != null) db.getFieldTypeRegistry().addClasses(this.fieldTypeClasses); // Done return db; } // This method exists solely to bind the generic type parameters private static <T extends KVDatabase> void startKVDatabase(DBType<T> dbType, KVDatabase kvdb) { dbType.startKVDatabase(dbType.cast(kvdb)); } /** * Shutdown the {@link KVDatabase}. */ protected void shutdownKVDatabase() { AbstractMain.stopKVDatabase(this.dbType, this.kvdb); } // This method exists solely to bind the generic type parameters private static <T extends KVDatabase> void stopKVDatabase(DBType<T> dbType, KVDatabase kvdb) { dbType.stopKVDatabase(dbType.cast(kvdb)); } protected abstract String getName(); /** * Output usage message flag listing. * * @param subclassOpts array containing flag and description pairs */ protected void outputFlags(String[][] subclassOpts) { final String[][] baseOpts = new String[][] { { "--arraydb directory", "Use ArrayKVDatabase in specified directory" }, { "--classpath, -cp path", "Append to the classpath (useful with `java -jar ...')" }, { "--fdb file", "Use FoundationDB with specified cluster file" }, { "--fdb-prefix prefix", "FoundationDB key prefix (hex or string)" }, { "--bdb directory", "Use Berkeley DB Java Edition in specified directory" }, { "--bdb-database", "Specify Berkeley DB database name (default `" + BerkeleyKVDatabase.DEFAULT_DATABASE_NAME + "')" }, { "--leveldb directory", "Use LevelDB in specified directory" }, { "--mem", "Use an empty in-memory database (default)" }, { "--mysql URL", "Use MySQL with the given JDBC URL" }, { "--raft directory", "Use Raft in specified directory" }, { "--raft-min-election-timeout", "Raft minimum election timeout in ms (default " + RaftKVDatabase.DEFAULT_MIN_ELECTION_TIMEOUT + ")" }, { "--raft-max-election-timeout", "Raft maximum election timeout in ms (default " + RaftKVDatabase.DEFAULT_MAX_ELECTION_TIMEOUT + ")" }, { "--raft-heartbeat-timeout", "Raft leader heartbeat timeout in ms (default " + RaftKVDatabase.DEFAULT_HEARTBEAT_TIMEOUT + ")" }, { "--raft-identity", "Raft identity" }, { "--raft-address address", "Specify local Raft node's IP address" }, { "--raft-port", "Specify local Raft node's TCP port (default " + RaftKVDatabase.DEFAULT_TCP_PORT + ")" }, { "--raft-fallback", "Use Raft fallback database" }, { "--raft-fallback-check-interval", "Specify Raft fallback check interval in milliseconds (default " + FallbackTarget.DEFAULT_CHECK_INTERVAL + ")" }, { "--raft-fallback-min-available", "Specify Raft fallback min available time in milliseconds (default " + FallbackTarget.DEFAULT_MIN_AVAILABLE_TIME + ")" }, { "--raft-fallback-min-unavailable", "Specify Raft fallback min unavailable time in milliseconds (default " + FallbackTarget.DEFAULT_MIN_UNAVAILABLE_TIME + ")" }, { "--raft-fallback-check-timeout", "Specify Raft fallback availability check TX timeout in milliseconds (default " + FallbackTarget.DEFAULT_TRANSACTION_TIMEOUT + ")" }, { "--raft-fallback-unavailable-merge", "Specify Raft fallback unavailable merge strategy class name (default `" + OverwriteMergeStrategy.class.getName() + "')" }, { "--raft-fallback-rejoin-merge", "Specify Raft fallback rejoin merge strategy class name (default `" + NullMergeStrategy.class.getName() + "')" }, { "--read-only, -ro", "Disallow database modifications" }, { "--rocksdb directory", "Use RocksDB in specified directory" }, { "--new-schema", "Allow recording of a new database schema version" }, { "--xml file", "Use the specified XML flat file database" }, { "--schema-version, -v num", "Specify database schema version (default highest recorded)" }, { "--model-pkg package", "Scan for @JSimpleClass model classes under Java package (=> JSimpleDB mode)" }, { "--type-pkg package", "Scan for @JFieldType types under Java package to register custom types" }, { "--pkg, -p package", "Equivalent to `--model-pkg package --type-pkg package'" }, { "--help, -h", "Show this help message" }, { "--verbose", "Show verbose error messages" }, }; final String[][] combinedOpts = new String[baseOpts.length + subclassOpts.length][]; System.arraycopy(baseOpts, 0, combinedOpts, 0, baseOpts.length); System.arraycopy(subclassOpts, 0, combinedOpts, baseOpts.length, subclassOpts.length); Arrays.sort(combinedOpts, new Comparator<String[]>() { @Override public int compare(String[] opt1, String[] opt2) { return opt1[0].compareTo(opt2[0]); } }); int width = 0; for (String[] opt : combinedOpts) width = Math.max(width, opt[0].length()); for (String[] opt : combinedOpts) System.err.println(String.format(" %-" + width + "s %s", opt[0], opt[1])); } // DBType protected abstract class DBType<T extends KVDatabase> { private final Class<T> type; protected DBType(Class<T> type) { this.type = type; } public T cast(KVDatabase db) { return this.type.cast(db); } public AtomicKVStore createAtomicKVStore() { return new AtomicKVDatabase(this.createKVDatabase()); } public abstract T createKVDatabase(); public void startKVDatabase(T db) { db.start(); } public void stopKVDatabase(T db) { db.stop(); } public boolean canBeFallbackStandalone() { return true; } public boolean canBeRaftLocalStorage() { return true; } public abstract String getDescription(); } protected final class MemoryDBType extends DBType<SimpleKVDatabase> { protected MemoryDBType() { super(SimpleKVDatabase.class); } @Override public SimpleKVDatabase createKVDatabase() { return new SimpleKVDatabase(); } @Override public String getDescription() { return "In-Memory Database"; } } protected final class FoundationDBType extends DBType<FoundationKVDatabase> { private final String clusterFile; private byte[] prefix; protected FoundationDBType(String clusterFile) { super(FoundationKVDatabase.class); this.clusterFile = clusterFile; } public void setPrefix(byte[] prefix) { this.prefix = prefix; } @Override public FoundationKVDatabase createKVDatabase() { final FoundationKVDatabase fdb = new FoundationKVDatabase(); fdb.setClusterFilePath(this.clusterFile); fdb.setKeyPrefix(prefix); return fdb; } @Override public String getDescription() { String desc = "FoundationDB " + new File(this.clusterFile).getName(); if (this.prefix != null) desc += " [0x" + ByteUtil.toString(this.prefix) + "]"; return desc; } } protected final class BerkeleyDBType extends DBType<BerkeleyKVDatabase> { private final File dir; private String databaseName = BerkeleyKVDatabase.DEFAULT_DATABASE_NAME; protected BerkeleyDBType(File dir) { super(BerkeleyKVDatabase.class); this.dir = dir; } public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } @Override public BerkeleyKVDatabase createKVDatabase() { final BerkeleyKVDatabase bdb = new BerkeleyKVDatabase(); bdb.setDirectory(this.dir); bdb.setDatabaseName(this.databaseName); return bdb; } @Override public String getDescription() { return "BerkeleyDB " + this.dir.getName(); } } protected final class XMLDBType extends DBType<XMLKVDatabase> { private final File xmlFile; protected XMLDBType(File xmlFile) { super(XMLKVDatabase.class); this.xmlFile = xmlFile; } @Override public XMLKVDatabase createKVDatabase() { return new XMLKVDatabase(this.xmlFile); } @Override public String getDescription() { return "XML DB " + this.xmlFile.getName(); } } protected final class LevelDBType extends DBType<LevelDBKVDatabase> { private final File dir; protected LevelDBType(File dir) { super(LevelDBKVDatabase.class); this.dir = dir; } @Override public LevelDBKVDatabase createKVDatabase() { final LevelDBKVDatabase leveldb = new LevelDBKVDatabase(); leveldb.setKVStore(this.createAtomicKVStore()); return leveldb; } @Override public LevelDBAtomicKVStore createAtomicKVStore() { final LevelDBAtomicKVStore kvstore = new LevelDBAtomicKVStore(); kvstore.setDirectory(this.dir); kvstore.setCreateIfMissing(true); return kvstore; } @Override public String getDescription() { return "LevelDB " + this.dir.getName(); } } protected final class RocksDBType extends DBType<RocksDBKVDatabase> { private final File dir; protected RocksDBType(File dir) { super(RocksDBKVDatabase.class); this.dir = dir; } @Override public RocksDBKVDatabase createKVDatabase() { final RocksDBKVDatabase rocksdb = new RocksDBKVDatabase(); rocksdb.setKVStore(this.createAtomicKVStore()); return rocksdb; } @Override public RocksDBAtomicKVStore createAtomicKVStore() { final RocksDBAtomicKVStore kvstore = new RocksDBAtomicKVStore(); kvstore.setDirectory(this.dir); return kvstore; } @Override public String getDescription() { return "RocksDB " + this.dir.getName(); } } protected final class ArrayDBType extends DBType<ArrayKVDatabase> { private final File dir; protected ArrayDBType(File dir) { super(ArrayKVDatabase.class); this.dir = dir; } @Override public ArrayKVDatabase createKVDatabase() { final ArrayKVDatabase arraydb = new ArrayKVDatabase(); arraydb.setKVStore(this.createAtomicKVStore()); return arraydb; } @Override public AtomicArrayKVStore createAtomicKVStore() { final AtomicArrayKVStore kvstore = new AtomicArrayKVStore(); kvstore.setDirectory(this.dir); return kvstore; } @Override public String getDescription() { return "ArrayDB " + this.dir.getName(); } } protected final class MySQLDBType extends DBType<MySQLKVDatabase> { private final String jdbcUrl; protected MySQLDBType(String jdbcUrl) { super(MySQLKVDatabase.class); this.jdbcUrl = jdbcUrl; } @Override public MySQLKVDatabase createKVDatabase() { try { Class.forName(MYSQL_DRIVER_CLASS_NAME); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("can't load MySQL driver class `" + MYSQL_DRIVER_CLASS_NAME + "'", e); } final MySQLKVDatabase mysql = new MySQLKVDatabase(); mysql.setDataSource(new DriverManagerDataSource(this.jdbcUrl)); return mysql; } @Override public String getDescription() { return "MySQL"; } } protected final class RaftDBType extends DBType<RaftKVDatabase> { private final File directory; private final RaftKVDatabase raft = new RaftKVDatabase(); private DBType<?> localStorageDBType; private String address; private int port = RaftKVDatabase.DEFAULT_TCP_PORT; protected RaftDBType(File directory) { super(RaftKVDatabase.class); this.directory = directory; this.raft.setLogDirectory(this.directory); } @Override public RaftKVDatabase createKVDatabase() { // Set up Raft local storage this.raft.setKVStore(this.localStorageDBType.createAtomicKVStore()); // Setup network final TCPNetwork network = new TCPNetwork(RaftKVDatabase.DEFAULT_TCP_PORT); try { network.setListenAddress(this.address != null ? new InetSocketAddress(InetAddress.getByName(this.address), this.port) : new InetSocketAddress(this.port)); } catch (UnknownHostException e) { throw new RuntimeException("can't resolve address `" + this.address + "'", e); } this.raft.setNetwork(network); // Done return this.raft; } public void setLocalStorageDBType(DBType<?> localStorageDBType) { this.localStorageDBType = localStorageDBType; } public void setIdentity(String identity) { this.raft.setIdentity(identity); } public void setAddress(String address) { this.address = address; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } public void setMinElectionTimeout(int minElectionTimeout) { this.raft.setMinElectionTimeout(minElectionTimeout); } public void setMaxElectionTimeout(int maxElectionTimeout) { this.raft.setMaxElectionTimeout(maxElectionTimeout); } public void setHeartbeatTimeout(int heartbeatTimeout) { this.raft.setHeartbeatTimeout(heartbeatTimeout); } @Override public boolean canBeRaftLocalStorage() { return false; } @Override public boolean canBeFallbackStandalone() { return false; } @Override public String getDescription() { return "Raft " + (this.directory != null ? this.directory.getName() : "?"); } } protected final class FallbackDBType extends DBType<FallbackKVDatabase> { private final FallbackTarget fallbackTarget = new FallbackTarget(); private RaftDBType raftDBType; private DBType<?> standaloneDBType; protected FallbackDBType() { super(FallbackKVDatabase.class); } @Override public FallbackKVDatabase createKVDatabase() { this.fallbackTarget.setRaftKVDatabase(this.raftDBType.createKVDatabase()); final FallbackKVDatabase fallback = new FallbackKVDatabase(); fallback.setFallbackTarget(this.fallbackTarget); fallback.setStandaloneTarget(this.standaloneDBType.createKVDatabase()); return fallback; } public void setStandaloneDBType(DBType<?> standaloneDBType) { this.standaloneDBType = standaloneDBType; } public void setRaftDBType(RaftDBType raftDBType) { this.raftDBType = raftDBType; } public FallbackTarget getFallbackTarget() { return this.fallbackTarget; } @Override public boolean canBeRaftLocalStorage() { return false; } @Override public boolean canBeFallbackStandalone() { return false; } @Override public String getDescription() { return this.raftDBType.getDescription() + " with fallback " + this.standaloneDBType.getDescription(); } } }