answer
stringlengths
17
10.2M
package gameWorld; import gameRender.IsoCanvas; import gameWorld.Inventory.itemTypes; import java.awt.Point; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayDeque; import java.util.ArrayList; import com.sun.accessibility.internal.resources.accessibility; import runGame.Main; import sun.text.normalizer.UBiDiProps; import tile.TileMultiton.type; import dataStorage.Data; import dataStorage.Tuple; /** * This is the main class for controling what a player can do on their turn and * how they interact with the world. * * @author ChrisMcIntosh * */ public class World { private boolean isActive; //This contains all gameobjects in the world the player can interact with private GameObject[][] gameBoard; //This is the map of all the tile that make up the world private LogicalTile[][] worldMap; private UnitPlayer avatar; private UnitCursor cursor; private IsoCanvas canvas; /** * Constructor * * @return */ public World(LogicalTile[][] tiles, GameObject[][] gameboard, int ID) { this.canvas = Main.cvs; this.gameBoard = gameboard; worldMap = tiles; UnitPlayer tempPlayer = null; for (int x = 0; x < gameboard.length; x++) { for (int y = 0; y < gameboard[0].length; y++) { if (gameboard[x][y] instanceof UnitPlayer) { if (((UnitPlayer) gameboard[x][y]).ID == ID) { avatar = (UnitPlayer) gameboard[x][y]; } } } } if (avatar == null) { avatar = randomPositionAvatar(); } cursor = new UnitCursor(avatar.curLocation, -1); checkPlayerStatus(); startTurn(); updateGameBoardGraphics(); } /** * Constructor * * @return */ public World( LogicalTile[][] tiles, GameObject[][] gameboard) { worldMap = tiles; this.canvas = Main.cvs; this.gameBoard = gameboard; avatar = randomPositionAvatar(); cursor = new UnitCursor(avatar.curLocation, -1); checkPlayerStatus(); startTurn(); updateGameBoardGraphics(); } /** * Generates a new player at a random position on the map; * @return The New Avatar */ private UnitPlayer randomPositionAvatar() { int id = -1; //Get the current Highest ID to set the new Avatars ID to one higher than that ID for (int x = 0; x < gameBoard.length; x++) { for (int y = 0; y < gameBoard[0].length; y++) { if (gameBoard[x][y] instanceof UnitPlayer) { id = Math.max(id, ((UnitPlayer) gameBoard[x][y]).getID()); } } } //Generate random map positions on the map until one is free then put the player there. while(true){ //Limited until map scrolling is implemented. int x = 5;//(int) (Math.random() * gameBoard.length); int y = 5;//(int) (Math.random() * gameBoard[0].length); if(gameBoard[x][y] == null){ gameBoard[x][y] = new UnitPlayer(new Point(x,y), id+1); return (UnitPlayer) gameBoard[x][y]; } } } /** *Updates active player *Then re calculates possible movements */ public boolean checkPlayerStatus() { //Return false if if(!avatar.isNotTurnEnd()){ isActive = false; return isActive; } //Otherwise refresh moevment and return true calculatePossibleMovments(); updateGameBoardGraphics(); return true; } /** * Resets turn information at the start of the turn */ public void startTurn(){ avatar.activate(); isActive = true; calculatePossibleMovments(); } /** * This is the method for handling mouse based movment however due to * problems with translating mouse position to bored position all movement is * now keyboard based and this is left in deprecated for if we are able to * solve the problems with it and properly implement it. */ @Deprecated public void intepretMouseCommand(Point coords){ int x = coords.x; int y = coords.y; // x = canvas.toCart(x, y).x; // Sorry Chris this dosn't work yet // y = canvas.toCart(x, y).y; if (move(x, y)) return; if (gameBoard[x][y] instanceof InteractiveObject) if(nextTo(x,y,avatar.curLocation.x, avatar.curLocation.y)) interactWith((InteractiveObject)gameBoard[x][y]); } /** * Handles interaction with InteractiveObjects by calling to their internal * methods * * @param x * @param y */ private void interactWith(InteractiveObject obj) { if(obj instanceof InteractiveObjectChest) avatar.addToInventory(((InteractiveObjectChest)obj).getContents()); if(obj instanceof InteractiveObjectMonster){ //Fight the monster with all the Katanas you have int[] loot = ((InteractiveObjectMonster)obj).fight(avatar.getInventory()[itemTypes.KATANA.ordinal()]); if(loot == null) avatar.loseFight(); else avatar.addToInventory(loot); } } /** * Moves the Cursor based on keyboard imput and if the movment is valid. * @param i */ public void moveFromKeyBoard(int i) { // 0 is up // 1 is down // 2 is left // 3 is right if(i > 3 || i < 0) return; int x = cursor.getLocation().x; int y = cursor.getLocation().y; if (i == 0) y++; if (i == 1) y if (i == 2) x if (i == 3) x++; if (inBounds(x, y)) if (worldMap[x][y].isIsTile()) { // If it's a door only a player with a key can go through if (worldMap[x][y] instanceof LogicalTileDoor) { if (!((LogicalTileDoor) worldMap[x][y]).isOpen()) { if (!avatar.hasKey()) return; avatar.useKey(); ((LogicalTileDoor) worldMap[x][y]).setOpen(true); } } // If the XY is within one movement of the active player if (worldMap[x][y].isReachableByActive()) { cursor.setLocation(x,y); canvas.moveCursor(cursor); } } } /** * Works out which tiles can be reached in one action. * This is used to be passed to the renderer. * @return */ private ArrayList<Point> tilesToHightlight() { ArrayList<Point> highPoints = new ArrayList<Point>(); for(int x = 0; x < worldMap.length; x++) for(int y = 0; y < worldMap[0].length; y++) if(worldMap[x][y].isReachableByActive() && !(gameBoard[x][y] instanceof StationaryObject)) highPoints.add(new Point(x, y)); return highPoints; } /** * Resets information about what can move where. * @param u */ private void refresh() { for(int x = 0; x < worldMap.length; x++) for(int y =0; y < worldMap[0].length; y++){ worldMap[x][y].setPath(null); worldMap[x][y].setReachableByActive(false); } checkPlayerStatus(); } /** * Calculates all possible movements the player can make and saves them into * tiles and then highlights squares reachable by one movement * * @param curLocation */ private void calculatePossibleMovements(Point curLocation) { checkMoveFrom(curLocation.x, curLocation.y, 6, new ArrayDeque<Point>()); canvas.highlight(tilesToHightlight()); } /** * Recursivly calculates all movements that can be made from a given XY with * remaining allotment of movement this is controled by the method * calculatePossibleMovments * * @param x * @param y * @param numMoves * @param path */ private void checkMoveFrom(int x, int y, int numMoves, ArrayDeque<Point> path){ path.add(new Point(x, y)); worldMap[x][y].setPath(path); worldMap[x][y].setReachableByActive(true); if(numMoves==0) return; if(validMove(x+1, y, path)) checkMoveFrom(x+1, y, numMoves-1, path.clone()); if(validMove(x-1, y, path)) checkMoveFrom(x-1, y, numMoves-1, path.clone()); if(validMove(x,y-1, path)) checkMoveFrom(x,y-1, numMoves-1,path.clone()); if(validMove(x,y+1, path)) checkMoveFrom(x,y+1, numMoves-1,path.clone()); } /** * Checks if a tile is valid to move to * @param x * @param y * @param path * @return */ private boolean validMove(int x, int y, ArrayDeque<Point> path){ //Return false if it out of bounds of the map array. if(!inBounds(x,y)) return false; //Returns false if the tile does not correspond to a accessible square if(!worldMap[x][y].isIsTile()) return false; //Return false if there is another player in that square if(gameBoard[x][y] instanceof UnitPlayer) return false; //Return true if there is no path yet calculated for that square if(worldMap[x][y].getPath() == null) return true; // Return false if the path calculated already for that square is more // efficient than this one if(worldMap[x][y].getPath().size() < path.size()) return false; //Otherwise return true return true; } /** * Moves the player avatar to the given XY * * @param ID * @param destination * @return */ public boolean move(int x, int y) { if (!inBounds(x, y)) return false; if(worldMap[x][y].isIsTile()) if(worldMap[x][y].isReachableByActive()){ GameObject currentContents = gameBoard[x][y]; gameBoard[avatar.getLocation().x][avatar.getLocation().y] = null; canvas.moveUnit(avatar, worldMap[x][y].getPath()); avatar.depleateMoves(); gameBoard[x][y] = avatar; avatar.upDateLocation(new Point(x,y)); calculatePossibleMovments(x,y); if(currentContents instanceof InteractiveObject) interactWith((InteractiveObject)currentContents); return true; } return false; } /** * Helper method to allow move to be called with a point */ public boolean move(Point p){ return move(p.x,p.y); } /** * Moves the active player to the cursor * @return */ public boolean moveToCursor() { if (move(cursor.curLocation)) { refresh(); return true; } return false; } /** * @return the canvas */ public IsoCanvas getCanvas() { return canvas; } /** * @param canvas the canvas to set */ public void setCanvas(IsoCanvas canvas) { this.canvas = canvas; } /** * Checks if two points are next to each other by * checking if the absolute value of the change in X and Y is * equal to 1 * @param p1 * @param p2 * @return */ private boolean nextTo(Point p1, Point p2){ return ((Math.abs(p1.x-p2.x) + Math.abs(p1.y-p2.y)) == 1); } /** * Calls method of same name with points instead of xy * @param x1 * @param y1 * @param x2 * @param y2 * @return */ private boolean nextTo(int x1, int y1, int x2, int y2){ return nextTo(new Point(x1,y1), new Point(x2,y2)); } /** * Checks if a point is on the GameBoard * @param x * @param y * @return */ private boolean inBounds(int x, int y) { if (x >= gameBoard.length) return false; if (y >= gameBoard[0].length) return false; if (x < 0) return false; if (y < 0) return false; return true; } /** * Calls the method of the same name converting XY to the required point * input * * @param x * @param y */ private void calculatePossibleMovments(int x, int y) { calculatePossibleMovements(new Point(x,y)); } /** * Calculates all possible movments from the active players current location */ private void calculatePossibleMovments() { calculatePossibleMovements(avatar.getLocation()); } /** * Returns the [] of counts of items in the players inventory * @return */ public int[] getInventory(){ return avatar.getInventory(); } /** * Replaces the game board with an updated one given by the network * * @param updatedGameBoard */ public void setGameBoard(GameObject[][] updatedGameBoard){ this.gameBoard = updatedGameBoard; } /** * Returns the current game board * @return */ public GameObject[][] getGameBoard(){ return this.gameBoard; } /** * Returns the current [][] of logical tiles. * @return */ public LogicalTile[][] getWorldMap(){ return worldMap; } /** * Replaces the current world map with an updated one from the server * @param updatedMap */ public void setWorldMap(LogicalTile[][] updatedMap){ this.worldMap = updatedMap; } /** * Returns UnitPlayer because i needed it - Sorry Chris * @return Local Player */ public UnitPlayer getAvatar(){ return avatar; } // public byte[] getGameBoard(){ // try { // return toByteArray(gameBoard); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // return null; // public byte[] getWorldMap(){ // try { // return toByteArray(worldMap); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // return null; // public static byte[] toByteArray(Object obj) throws IOException { // byte[] bytes = null; // ByteArrayOutputStream bos = null; // ObjectOutputStream oos = null; // try { // bos = new ByteArrayOutputStream(); // oos = new ObjectOutputStream(bos); // oos.writeObject(obj); // oos.flush(); // bytes = bos.toByteArray(); // } finally { // if (oos != null) { // oos.close(); // if (bos != null) { // bos.close(); // return bytes; /** * This method checks if player has finished the turn * @return if player is still active */ public boolean isTurn() { return isActive; } //Graphics methods /** * Gets the canvas to redraw all GameObjects on the gameBoard */ public void updateGameBoardGraphics(){ ArrayList<GameObject> t = new ArrayList<GameObject>(); for(int x =0; x < gameBoard.length; x++) for(int y = 0; y < gameBoard[0].length; y++) if(gameBoard[x][y] != null) t.add(gameBoard[x][y]); canvas.updateGameBoardGraphics(t); } }
package org.jboss.as.console.client.widgets.nav.v3; import com.google.gwt.cell.client.ButtonCell; import com.google.gwt.cell.client.Cell; import com.google.gwt.cell.client.SafeHtmlCell; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.TableRowElement; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.AttachEvent; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.cellview.client.CellTable; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.cellview.client.RowHoverEvent; import com.google.gwt.user.cellview.client.RowStyles; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.LayoutPanel; import com.google.gwt.user.client.ui.MenuBar; import com.google.gwt.user.client.ui.MenuItem; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.view.client.CellPreviewEvent; import com.google.gwt.view.client.ProvidesKey; import com.google.gwt.view.client.SelectionChangeEvent; import com.google.gwt.view.client.SingleSelectionModel; import com.gwtplatform.mvp.client.proxy.PlaceManager; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.domain.model.SimpleCallback; import org.jboss.ballroom.client.rbac.SecurityContext; import org.jboss.ballroom.client.rbac.SecurityContextAware; import org.jboss.ballroom.client.rbac.SecurityService; import org.jboss.ballroom.client.spi.Framework; import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; import java.util.List; /** * @author Heiko Braun * @since 09/01/15 */ public class FinderColumn<T> { private static final String CLICK = "click"; private final SingleSelectionModel<T> selectionModel; private final CellTable<T> cellTable; private final FinderId correlationId; private final String title; private final Display display; private final ProvidesKey keyProvider; private final String id; private final String token; private LayoutPanel header; private boolean plain = false; private MenuDelegate[] menuItems = new MenuDelegate[]{}; private MenuDelegate[] topMenuItems = new MenuDelegate[]{}; private HTML headerTitle; private ValueProvider<T> valueProvider; private String filter; private LayoutPanel layout; private HTMLPanel headerMenu; public enum FinderId { DEPLOYMENT, CONFIGURATION, RUNTIME} private boolean showSize = false; static Framework FRAMEWORK = GWT.create(Framework.class); static SecurityService SECURITY_SERVICE = FRAMEWORK.getSecurityService(); private String resourceAddress = null; /** * Thje default finder preview */ private final PreviewFactory DEFAULT_PREVIEW = new PreviewFactory() { @Override public void createPreview(Object data, AsyncCallback callback) { SafeHtmlBuilder builder = new SafeHtmlBuilder(); String icon = display.isFolder(data) ? "icon-folder-close-alt" : "icon-file-text-alt"; builder.appendHtmlConstant("<center><i class='"+icon+"' style='font-size:48px;top:100px;position:relative'></i></center>"); callback.onSuccess(builder.toSafeHtml()); } }; private PreviewFactory<T> previewFactory = DEFAULT_PREVIEW; public FinderColumn(final FinderId correlationId, final String title, final Display display, final ProvidesKey keyProvider) { this.correlationId = correlationId; this.title = title; this.display = display; this.keyProvider = keyProvider; // RBAC related this.token = SECURITY_SERVICE.resolveToken(); this.id = Document.get().createUniqueId(); selectionModel = new SingleSelectionModel<T>(keyProvider); cellTable = new CellTable<T>(200, DefaultCellTable.DEFAULT_CELL_TABLE_RESOURCES , keyProvider); cellTable.setStyleName("navigation-cell-table"); cellTable.getElement().setAttribute("style", "border:none!important"); cellTable.setLoadingIndicator(new HTML()); cellTable.setEmptyTableWidget(new HTML("<div class='empty-finder-column'>No Items!</div>")); Column<T, SafeHtml> titleColumn = new Column<T, SafeHtml>(new SafeHtmlCell()) { @Override public SafeHtml getValue(T data) { return display.render("navigation-column-item", data); } }; final Column<T, String> menuColumn = new Column<T, String>(new ButtonCell() { public void render(Cell.Context context, SafeHtml data, SafeHtmlBuilder sb) { if(menuItems.length>0) { sb.appendHtmlConstant("<div class='nav-menu'>"); sb.appendHtmlConstant("<div class='btn-group'>"); sb.appendHtmlConstant("<button action='default' class='btn' type='button' tabindex=\"-1\">"); if (data != null) { sb.append(data); } sb.appendHtmlConstant("</button>"); if(menuItems.length>1) { sb.appendHtmlConstant("<button action='menu' class='btn dropdown-toggle' type='button' tabindex=\"-1\">"); sb.appendHtmlConstant("<span><i class='icon-caret-down'></i></span>"); sb.appendHtmlConstant("</button>"); sb.appendHtmlConstant("</div>"); sb.appendHtmlConstant("</div>"); } } } }) { @Override public String getValue(T object) { return menuItems.length>0 ? menuItems[0].getTitle() : ""; } }; Column<T, SafeHtml> iconColumn = new Column<T, SafeHtml>(new SafeHtmlCell()) { @Override public SafeHtml getValue(T data) { SafeHtmlBuilder builder = new SafeHtmlBuilder(); builder.appendHtmlConstant("<i class='icon-caret-right row-icon' style='vertical-align:middle'></i>"); return builder.toSafeHtml(); } }; menuColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT); cellTable.addColumn(titleColumn); cellTable.addColumn(menuColumn); cellTable.addColumn(iconColumn); // width constraints, overflow, etc cellTable.getElement().getStyle().setTableLayout(Style.TableLayout.FIXED); cellTable.setColumnWidth(titleColumn, 150, Style.Unit.PX); cellTable.setColumnWidth(menuColumn, 120, Style.Unit.PX); cellTable.setColumnWidth(iconColumn, 30, Style.Unit.PX); cellTable.setSelectionModel(selectionModel); // visibility of the context menu column cellTable.addRowHoverHandler(new RowHoverEvent.Handler() { @Override public void onRowHover(RowHoverEvent event) { TableRowElement hoveringRow = event.getHoveringRow(); // skip empty menus if(menuItems.length==0) return; if(event.isUnHover()) { hoveringRow.removeClassName("nav-hover"); } else { hoveringRow.addClassName("nav-hover"); } } }); cellTable.addCellPreviewHandler(new CellPreviewEvent.Handler<T>() { @Override public void onCellPreview(final CellPreviewEvent<T> event) { boolean isClick = CLICK.equals(event.getNativeEvent().getType()); if(isClick && 1==event.getColumn()) { // update breadcrumb navigation triggerBreadcrumbEvent(true); event.getNativeEvent().preventDefault(); final Element element = Element.as(event.getNativeEvent().getEventTarget()); String action = element.getAttribute("action"); if("default".equals(action)) { menuItems[0].getCommand().executeOn(event.getValue()); } else if("menu".equals(action)) { openContextMenu(event.getNativeEvent(), event.getValue()); } } else if(isClick && 0==event.getColumn()) { triggerPreviewEvent(); } } }); cellTable.setRowStyles(new RowStyles<T>() { @Override public String getStyleNames(T row, int rowIndex) { boolean isFolder = display.isFolder(row); String css = display.rowCss(row); return isFolder ? css + " folder-view" : css + " file-view"; } }); selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { @Override public void onSelectionChange(SelectionChangeEvent event) { triggerBreadcrumbEvent(false); triggerPreviewEvent(); // skip empty menus if(menuItems.length==0) return; // toggle row level tools boolean hasSelection = selectionModel.getSelectedObject()!=null; if(hasSelection) { int row = cellTable.getKeyboardSelectedRow(); TableRowElement rowElement = cellTable.getRowElement(row); if (hasSelection) { rowElement.addClassName("nav-hover"); } else { rowElement.removeClassName("nav-hover"); } } } }); } private void applySecurity(final SecurityContext securityContext, boolean update) { boolean writePrivilege = this.resourceAddress != null ? securityContext.getWritePrivilege(this.resourceAddress).isGranted() : securityContext.getWritePriviledge().isGranted(); if(writePrivilege) { headerMenu.getElement().removeClassName("rbac-suppressed"); } else { headerMenu.getElement().addClassName("rbac-suppressed"); } } public FinderColumn<T> setShowSize(boolean b) { this.showSize = b; return this; } public FinderColumn<T> setResourceAddress(String address) { this.resourceAddress = address; return this; } private void triggerPreviewEvent() { // preview and place management sometimes compete, hence the timed event Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() { @Override public boolean execute() { // preview events PlaceManager placeManager = Console.MODULES.getPlaceManager(); final T selectedObject = selectionModel.getSelectedObject(); if(selectedObject!=null) { previewFactory.createPreview(selectedObject, new SimpleCallback<SafeHtml>() { @Override public void onSuccess(SafeHtml content) { PreviewEvent.fire(placeManager, content); } }); } return false; } }, 200); } private void triggerBreadcrumbEvent(boolean isMenuEvent) { PlaceManager placeManager = Console.MODULES.getPlaceManager(); final T selectedObject = selectionModel.getSelectedObject(); String typeIdentifier = title; // not used naymore; if(selectedObject!=null) { // delegate to value provider if given, otherwise the keyprovider will do fine String value = valueProvider!=null ? valueProvider.get(selectedObject) : String.valueOf(keyProvider.getKey(selectedObject)); BreadcrumbEvent.fire(placeManager, correlationId, typeIdentifier, title, selectedObject != null, value, isMenuEvent); } else { BreadcrumbEvent.fire(placeManager, correlationId, typeIdentifier, title, selectedObject != null, "", isMenuEvent); } } private void openTopContextMenu(Element anchor, final NativeEvent event) { Element el = Element.as(event.getEventTarget()); //Element anchor = el.getParentElement().getParentElement(); final PopupPanel popupPanel = new PopupPanel(true); final MenuBar popupMenuBar = new MenuBar(true); popupMenuBar.setStyleName("dropdown-menu"); int i=0; for (final MenuDelegate menuitem : topMenuItems) { if(i>0) { // skip the "default" action MenuItem cmd = new MenuItem(menuitem.getTitle(), true, new Command() { @Override public void execute() { Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { menuitem.getCommand().executeOn(null); } }); popupPanel.hide(); } }); popupMenuBar.addItem(cmd); } i++; } popupMenuBar.setVisible(true); popupPanel.setWidget(popupMenuBar); int left = anchor.getAbsoluteLeft(); int top = anchor.getAbsoluteTop() + 30; popupPanel.setPopupPosition(left, top); popupPanel.setAutoHideEnabled(true); popupPanel.show(); } private void openContextMenu(final NativeEvent event, final T object) { Element el = Element.as(event.getEventTarget()); Element anchor = el.getParentElement(); final PopupPanel popupPanel = new PopupPanel(true); final MenuBar popupMenuBar = new MenuBar(true); popupMenuBar.setStyleName("dropdown-menu"); int i=0; for (final MenuDelegate menuitem : menuItems) { if(i>0) { // skip the "default" action MenuItem cmd = new MenuItem(menuitem.getTitle(), true, new Command() { @Override public void execute() { Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { menuitem.getCommand().executeOn((T) object); } }); popupPanel.hide(); } }); popupMenuBar.addItem(cmd); } i++; } popupMenuBar.setVisible(true); popupPanel.setWidget(popupMenuBar); int left = anchor.getAbsoluteLeft(); int top = anchor.getAbsoluteTop() + 22; popupPanel.setPopupPosition(left, top); popupPanel.setAutoHideEnabled(true); popupPanel.show(); } /** * the top level menu items (part of the header) * @param items * @return */ public FinderColumn<T> setTopMenuItems(MenuDelegate<T>... items) { this.topMenuItems = items; return this; } /** * row level menu items. the first item act's as the default action. * @param items * @return */ public FinderColumn<T> setMenuItems(MenuDelegate<T>... items) { this.menuItems = items; return this; } /** * renders the column without a header * @param plain * @return */ public FinderColumn<T> setPlain(boolean plain) { this.plain = plain; return this; } /** * factory for content previews * @param previewFactory * @return */ public FinderColumn<T> setPreviewFactory(PreviewFactory<T> previewFactory) { this.previewFactory = previewFactory; return this; } /** * provides the value part of a key/value breadcrumb tuple. * if this is not given (default) then the column title will be used as the value. * @param valueProvider * @return */ public FinderColumn<T> setValueProvider(ValueProvider<T> valueProvider) { this.valueProvider = valueProvider; return this; } public void addSelectionChangeHandler(SelectionChangeEvent.Handler handler) { selectionModel.addSelectionChangeHandler(handler); } public boolean hasSelectedItem() { return selectionModel.getSelectedObject()!=null; } public T getSelectedItem() { return selectionModel.getSelectedObject(); } public Widget asWidget() { layout = new LayoutPanel() { @Override protected void onLoad() { applySecurity(SECURITY_SERVICE.getSecurityContext(FinderColumn.this.token), false); } }; layout.addStyleName("navigation-column"); layout.getElement().setId(id); // RBAC if(!plain) { // including the header header = new LayoutPanel(); header.addStyleName("fill-layout-width"); header.addStyleName("finder-col-header"); headerTitle = new HTML(title); headerTitle.addStyleName("finder-col-title"); header.add(headerTitle); ScrollPanel nav = new ScrollPanel(cellTable); nav.getElement().getStyle().setOverflowX(Style.Overflow.HIDDEN); String groupId = HTMLPanel.createUniqueId(); SafeHtmlBuilder sb = new SafeHtmlBuilder(); sb.appendHtmlConstant("<div class='nav-headerMenu'>"); sb.appendHtmlConstant("<div id="+groupId+" class='btn-group' style='float:right;padding-right:10px;padding-top:8px'>"); sb.appendHtmlConstant("</div>"); sb.appendHtmlConstant("</div>"); headerMenu = new HTMLPanel(sb.toSafeHtml()); headerMenu.setStyleName("fill-layout"); if(topMenuItems.length>0) { HTML item = new HTML(topMenuItems[0].getTitle()); item.setStyleName("btn"); item.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { topMenuItems[0].getCommand().executeOn(null); } }); headerMenu.add(item, groupId); // remaining menu items move into dropdown if(topMenuItems.length>1) { HTML dropDown = new HTML("<span><i class='icon-caret-down'></i></span>"); dropDown.setStyleName("btn dropdown-toggle"); dropDown.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { openTopContextMenu(headerMenu.getElementById(groupId), event.getNativeEvent()); } }); headerMenu.add(dropDown, groupId); } } header.add(headerMenu); header.setWidgetLeftWidth(headerTitle, 0, Style.Unit.PX, 60, Style.Unit.PCT); header.setWidgetRightWidth(headerMenu, 0, Style.Unit.PX, 40, Style.Unit.PCT); header.setWidgetTopHeight(headerTitle, 1, Style.Unit.PX, 38, Style.Unit.PX); header.setWidgetTopHeight(headerMenu, 1, Style.Unit.PX, 38, Style.Unit.PX); layout.add(header); layout.add(nav); layout.setWidgetTopHeight(header, 0, Style.Unit.PX, 40, Style.Unit.PX); layout.setWidgetTopHeight(nav, 41, Style.Unit.PX, 95, Style.Unit.PCT); } else // embedded mode, w/o header { ScrollPanel nav = new ScrollPanel(cellTable); nav.getElement().getStyle().setOverflowX(Style.Overflow.HIDDEN); layout.add(nav); layout.setWidgetTopHeight(nav, 0, Style.Unit.PX, 100, Style.Unit.PCT); } return layout; } public void updateFrom(List<T> records) { updateFrom(records, false); } public void updateFrom(final List<T> records, final boolean selectDefault) { selectionModel.clear(); cellTable.setRowCount(records.size(), true); cellTable.setRowData(0, records); if(!plain) { if(showSize) headerTitle.setHTML(title+" ("+records.size()+")"); else headerTitle.setHTML(title); } if(selectDefault && records.size()>0) { Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { selectionModel.setSelected(records.get(0), true); } }); } } /** * renderer for the column content * @param <T> */ public interface Display<T> { boolean isFolder(T data); SafeHtml render(String baseCss, T data); String rowCss(T data); } /*public void selectByKey(Object key) { selectionModel.clear(); int i=0; for(T item : cellTable.getVisibleItems()) { if(keyProvider.getKey(item).equals(key)) { selectionModel.setSelected(item, true); cellTable.getRowElement(i).scrollIntoView(); break; } i++; } }*/ }
package com.splicemachine.derby.stream.spark; import com.splicemachine.db.iapi.error.StandardException; import com.splicemachine.derby.iapi.sql.execute.SpliceOperation; import com.splicemachine.derby.impl.sql.execute.operations.LocatedRow; import com.splicemachine.derby.impl.sql.execute.operations.export.ExportExecRowWriter; import com.splicemachine.derby.impl.sql.execute.operations.export.ExportOperation; import com.splicemachine.derby.stream.function.*; import com.splicemachine.derby.stream.iapi.DataSet; import com.splicemachine.derby.stream.iapi.OperationContext; import com.splicemachine.derby.stream.iapi.PairDataSet; import com.splicemachine.derby.stream.output.ExportDataSetWriterBuilder; import com.splicemachine.utils.ByteDataInput; import org.apache.commons.codec.binary.Base64; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.ReflectionUtils; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.storage.StorageLevel; import java.io.IOException; import java.io.OutputStream; import java.util.*; import java.util.zip.GZIPOutputStream; /** * * DataSet Implementation for Spark. * * @see com.splicemachine.derby.stream.iapi.DataSet * @see java.io.Serializable * */ public class SparkDataSet<V> implements DataSet<V> { public JavaRDD<V> rdd; private Map<String,String> attributes; public SparkDataSet(JavaRDD<V> rdd) { this.rdd = rdd; } public SparkDataSet(JavaRDD<V> rdd, String rddname) { this.rdd = rdd; if (rdd != null && rddname != null) this.rdd.setName(rddname); } @Override public List<V> collect() { return rdd.collect(); } @Override public <Op extends SpliceOperation, U> DataSet<U> mapPartitions(SpliceFlatMapFunction<Op,Iterator<V>, U> f) { return new SparkDataSet<>(rdd.mapPartitions(new SparkFlatMapFunction<>(f)),f.getSparkName()); } @Override public <Op extends SpliceOperation, U> DataSet<U> mapPartitions(SpliceFlatMapFunction<Op,Iterator<V>, U> f, boolean isLast) { return new SparkDataSet<>(rdd.mapPartitions(new SparkFlatMapFunction<>(f)), planIfLast(f, isLast)); } @Override public <Op extends SpliceOperation, U> DataSet<U> mapPartitions(SpliceFlatMapFunction<Op,Iterator<V>, U> f, boolean isLast, boolean pushScope, String scopeDetail) { if (pushScope) f.operationContext.pushScopeForOp(scopeDetail); try { return new SparkDataSet<U>(rdd.mapPartitions(new SparkFlatMapFunction<>(f)), planIfLast(f, isLast)); } finally { if (pushScope) f.operationContext.popScope(); } } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public DataSet<V> distinct() { return distinct("Remove Duplicates"); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public DataSet<V> distinct(String name) { JavaRDD rdd1 = rdd.distinct(); rdd1.setName(name /* MapPartitionsRDD */); RDDUtils.setAncestorRDDNames(rdd1, 2, new String[]{"Shuffle Data" /* ShuffledRDD */, "Prepare To Find Distinct" /* MapPartitionsRDD */}); return new SparkDataSet(rdd1); } @Override public <Op extends SpliceOperation, K,U> PairDataSet<K,U> index(SplicePairFunction<Op,V,K,U> function) { return new SparkPairDataSet<>(rdd.mapToPair(new SparkSplittingFunction<>(function)), function.getSparkName()); } @Override public <Op extends SpliceOperation, K,U>PairDataSet<K, U> index(SplicePairFunction<Op,V,K,U> function, boolean isLast) { return new SparkPairDataSet<>(rdd.mapToPair(new SparkSplittingFunction<>(function)), planIfLast(function, isLast)); } @Override public <Op extends SpliceOperation, U> DataSet<U> map(SpliceFunction<Op,V,U> function) { return new SparkDataSet<>(rdd.map(new SparkSpliceFunctionWrapper<>(function)), function.getSparkName()); } public <Op extends SpliceOperation, U> DataSet<U> map(SpliceFunction<Op,V,U> function, String name) { return new SparkDataSet<>(rdd.map(new SparkSpliceFunctionWrapper<>(function)), name); } public <Op extends SpliceOperation, U> DataSet<U> map(SpliceFunction<Op,V,U> function, boolean isLast) { return new SparkDataSet<>(rdd.map(new SparkSpliceFunctionWrapper<>(function)), planIfLast(function, isLast)); } @Override public Iterator<V> toLocalIterator() { return rdd.toLocaliterator(); } @SuppressWarnings("rawtypes") private String planIfLast(AbstractSpliceFunction f, boolean isLast) { if (!isLast) return f.getSparkName(); String plan = f.getOperation().getPrettyExplainPlan(); return (plan != null && !plan.isEmpty() ? plan : f.getSparkName()); } @Override public <Op extends SpliceOperation, K> PairDataSet< K, V> keyBy(SpliceFunction<Op, V, K> f) { return new SparkPairDataSet<>(rdd.keyBy(new SparkSpliceFunctionWrapper<>(f)), f.getSparkName()); } public <Op extends SpliceOperation, K> PairDataSet< K, V> keyBy(SpliceFunction<Op, V, K> f, String name) { return new SparkPairDataSet<>(rdd.keyBy(new SparkSpliceFunctionWrapper<>(f)), name); } @Override public <Op extends SpliceOperation, K> PairDataSet< K, V> keyBy( SpliceFunction<Op, V, K> f, String name, boolean pushScope, String scopeDetail) { if (pushScope) f.operationContext.pushScopeForOp(scopeDetail); try { return new SparkPairDataSet(rdd.keyBy(new SparkSpliceFunctionWrapper<>(f)), name != null ? name : f.getSparkName()); } finally { if (pushScope) f.operationContext.popScope(); } } @Override public long count() { return rdd.count(); } @Override public DataSet<V> union(DataSet< V> dataSet) { return union(dataSet, SparkConstants.RDD_NAME_UNION); } @Override public DataSet< V> union(DataSet< V> dataSet, String name) { JavaRDD<V> union=rdd.union(((SparkDataSet<V>)dataSet).rdd); union.setName(name); return new SparkDataSet<>(union); } @Override public <Op extends SpliceOperation> DataSet< V> filter(SplicePredicateFunction<Op, V> f) { return new SparkDataSet<>(rdd.filter(new SparkSpliceFunctionWrapper<>(f)), f.getSparkName()); } @Override public <Op extends SpliceOperation> DataSet< V> filter( SplicePredicateFunction<Op,V> f, boolean isLast, boolean pushScope, String scopeDetail) { if (pushScope) f.operationContext.pushScopeForOp(scopeDetail); try { return new SparkDataSet(rdd.filter(new SparkSpliceFunctionWrapper<>(f)), planIfLast(f, isLast)); } finally { if (pushScope) f.operationContext.popScope(); } } @Override public DataSet< V> intersect(DataSet< V> dataSet) { return new SparkDataSet<>(rdd.intersection(((SparkDataSet<V>) dataSet).rdd)); } @Override public DataSet< V> subtract(DataSet< V> dataSet) { return new SparkDataSet<>(rdd.subtract( ((SparkDataSet<V>) dataSet).rdd)); } @Override public boolean isEmpty() { return rdd.take(1).isEmpty(); } @Override public <Op extends SpliceOperation, U> DataSet< U> flatMap(SpliceFlatMapFunction<Op, V, U> f) { return new SparkDataSet<>(rdd.flatMap(new SparkFlatMapFunction<>(f)), f.getSparkName()); } public <Op extends SpliceOperation, U> DataSet< U> flatMap(SpliceFlatMapFunction<Op, V, U> f, String name) { return new SparkDataSet<>(rdd.flatMap(new SparkFlatMapFunction<>(f)), name); } public <Op extends SpliceOperation, U> DataSet< U> flatMap(SpliceFlatMapFunction<Op, V, U> f, boolean isLast) { return new SparkDataSet<>(rdd.flatMap(new SparkFlatMapFunction<>(f)), planIfLast(f, isLast)); } @Override public void close() { } @Override public <Op extends SpliceOperation> DataSet<V> offset(OffsetFunction<Op,V> offsetFunction) { return new SparkDataSet<>(rdd.mapPartitions(new SparkFlatMapFunction<>(offsetFunction)),offsetFunction.getSparkName()); } @Override public <Op extends SpliceOperation> DataSet<V> offset(OffsetFunction<Op,V> offsetFunction, boolean isLast) { return new SparkDataSet<>(rdd.mapPartitions(new SparkFlatMapFunction<>(offsetFunction)),planIfLast(offsetFunction,isLast)); } @Override public <Op extends SpliceOperation> DataSet<V> take(TakeFunction<Op,V> takeFunction) { JavaRDD<V> rdd1 = rdd.mapPartitions(new SparkFlatMapFunction<>(takeFunction)); rdd1.setName(takeFunction.getSparkName()); JavaRDD<V> rdd2 = rdd1.coalesce(1, true); rdd2.setName("Coalesce 1 partition"); RDDUtils.setAncestorRDDNames(rdd2, 3, new String[]{"Coalesce Data", "Shuffle Data", "Map For Coalesce"}); JavaRDD<V> rdd3 = rdd2.mapPartitions(new SparkFlatMapFunction<>(takeFunction)); rdd3.setName(takeFunction.getSparkName()); return new SparkDataSet<V>(rdd3); } @Override public ExportDataSetWriterBuilder writeToDisk(){ return new SparkExportDataSetWriter.Builder(rdd); } public static class EOutputFormat extends FileOutputFormat<Void, LocatedRow> { @Override public RecordWriter<Void, LocatedRow> getRecordWriter(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { Configuration conf = taskAttemptContext.getConfiguration(); String encoded = conf.get("exportFunction"); ByteDataInput bdi = new ByteDataInput( Base64.decodeBase64(encoded)); SpliceFunction2<ExportOperation, OutputStream, Iterator<LocatedRow>, Void> exportFunction; try { exportFunction = (SpliceFunction2<ExportOperation, OutputStream, Iterator<LocatedRow>, Void>) bdi.readObject(); } catch (ClassNotFoundException e) { throw new IOException(e); } final ExportOperation op = exportFunction.getOperation(); CompressionCodec codec = null; String extension = ".csv"; boolean isCompressed = op.getExportParams().isCompression(); if (isCompressed) { Class<? extends CompressionCodec> codecClass = getOutputCompressorClass(taskAttemptContext, GzipCodec.class); codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf); extension += ".gz"; } Path file = getDefaultWorkFile(taskAttemptContext, extension); FileSystem fs = file.getFileSystem(conf); OutputStream fileOut = fs.create(file, false); if (isCompressed) { fileOut = new GZIPOutputStream(fileOut); } final ExportExecRowWriter rowWriter = ExportFunction.initializeRowWriter(fileOut, op.getExportParams()); return new RecordWriter<Void, LocatedRow>() { @Override public void write(Void _, LocatedRow locatedRow) throws IOException, InterruptedException { try { rowWriter.writeRow(locatedRow.getRow(), op.getSourceResultColumnDescriptors()); } catch (StandardException e) { throw new IOException(e); } } @Override public void close(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { rowWriter.close(); } }; } } // @Override public void saveAsTextFile(String path) { rdd.saveAsTextFile(path); } @Override public ExportDataSetWriterBuilder<String> saveAsTextFile(){ return new SparkExportDataSetWriter.Builder<>(rdd); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public DataSet<V> coalesce(int numPartitions, boolean shuffle) { JavaRDD rdd1 = rdd.coalesce(numPartitions, shuffle); rdd1.setName(String.format("Coalesce %d partitions", numPartitions)); RDDUtils.setAncestorRDDNames(rdd1, 3, new String[]{"Coalesce Data", "Shuffle Data", "Map For Coalesce"}); return new SparkDataSet<>(rdd1); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public DataSet<V> coalesce(int numPartitions, boolean shuffle, boolean isLast, OperationContext context, boolean pushScope, String scopeDetail) { if (pushScope) context.pushScopeForOp(scopeDetail); try { JavaRDD rdd1 = rdd.coalesce(numPartitions, shuffle); rdd1.setName(String.format("Coalesce %d partitions", numPartitions)); RDDUtils.setAncestorRDDNames(rdd1, 3, new String[]{"Coalesce Data", "Shuffle Data", "Map For Coalesce"}); return new SparkDataSet<V>(rdd1); } finally { if (pushScope) context.popScope(); } } @Override public void persist() { rdd.persist(StorageLevel.MEMORY_AND_DISK_SER_2()); } @Override public Iterator<V> iterator() { return toLocalIterator(); } @Override public void setAttribute(String name, String value) { if (attributes==null) attributes = new HashMap<>(); attributes.put(name,value); } @Override public String getAttribute(String name) { if (attributes ==null) return null; return attributes.get(name); } }
package eu.amidst.huginlink.inference; import COM.hugin.HAPI.*; import eu.amidst.core.distribution.*; import eu.amidst.core.inference.InferenceAlgorithmForBN; import eu.amidst.core.models.BayesianNetwork; import eu.amidst.core.utils.BayesianNetworkGenerator; import eu.amidst.core.variables.Assignment; import eu.amidst.core.variables.HashMapAssignment; import eu.amidst.core.variables.Variable; import eu.amidst.huginlink.converters.BNConverterToHugin; import eu.amidst.huginlink.io.BNWriterToHugin; public class HuginInferenceForBN implements InferenceAlgorithmForBN { BayesianNetwork amidstBN; Domain huginBN; private void setVarEvidence(Variable n, long value) throws ExceptionHugin { if (n.isMultinomial()){ ((DiscreteNode)huginBN.getNodeByName(n.getName())).selectState(value); } else if (n.isGaussian()) { ((ContinuousChanceNode)huginBN.getNodeByName(n.getName())).enterValue(value); } else { throw new IllegalArgumentException("Variable type not allowed."); } } private void printBelief(Node node) throws ExceptionHugin { if (node instanceof DiscreteNode) { DiscreteNode dNode = (DiscreteNode) node; int n = (int) dNode.getNumberOfStates(); for (int i=0;i<n;i++) { System.out.print (" -> " + dNode.getStateLabel(i)+ " " + dNode.getBelief(i)); System.out.println(); } } else { ContinuousChanceNode ccNode = (ContinuousChanceNode) node; System.out.println (" - Mean : " + ccNode.getMean()); System.out.println (" - SD : " + Math.sqrt (ccNode.getVariance())); } } private void printBeliefs () throws ExceptionHugin { NodeList nodes = huginBN.getNodes(); java.util.ListIterator it = nodes.listIterator(); while (it.hasNext()) { Node node = (Node) it.next(); System.out.println(); System.out.println(node.getLabel() + " (" + node.getName() + ")"); printBelief(node); } } @Override public void compileModel() { try { this.huginBN.compile(); huginBN.propagate(Domain.H_EQUILIBRIUM_SUM, Domain.H_EVIDENCE_MODE_NORMAL); } catch (ExceptionHugin exceptionHugin) { exceptionHugin.printStackTrace(); } } @Override public void setModel(BayesianNetwork model) { this.amidstBN = model; try { this.huginBN = BNConverterToHugin.convertToHugin(model); } catch (ExceptionHugin exceptionHugin) { exceptionHugin.printStackTrace(); } } @Override public BayesianNetwork getModel() { return amidstBN; } @Override public void setEvidence(Assignment assignment) { ((HashMapAssignment)assignment).entrySet().stream() .forEach(entry -> { try { this.setVarEvidence(entry.getKey(), entry.getValue().longValue()); } catch (ExceptionHugin exceptionHugin) { exceptionHugin.printStackTrace(); } }); } @Override public <E extends UnivariateDistribution> E getPosterior(Variable var) { try { Node huginNode = huginBN.getNodeByName(var.getName()); if (var.isMultinomial()) { Multinomial dist = new Multinomial(var); for(int i=0;i<var.getNumberOfStates();i++){ dist.setProbabilityOfState(i, ((DiscreteNode) huginNode).getBelief(i)); } return (E)dist; } else if (var.isGaussian()) { Normal dist = new Normal(var); dist.setMean(((ContinuousChanceNode)huginNode).getMean()); dist.setSd(Math.sqrt(((ContinuousChanceNode) huginNode).getVariance())); return (E)dist; } else { throw new IllegalArgumentException("Variable type not allowed."); } } catch (ExceptionHugin exceptionHugin) { exceptionHugin.printStackTrace(); } return null; } public static void main(String args[]) throws ExceptionHugin { BayesianNetworkGenerator.setNumberOfDiscreteVars(2); BayesianNetworkGenerator.setNumberOfContinuousVars(2); BayesianNetwork bn = BayesianNetworkGenerator.generateNaiveBayes(2); BNWriterToHugin.saveToHuginFile(bn,"networks/inference.net"); Variable DiscreteVar0 = bn.getStaticVariables().getVariableById(0); Variable GaussianVar0 = bn.getStaticVariables().getVariableById(1); Variable GaussianVar1 = bn.getStaticVariables().getVariableById(2); Variable ClassVar = bn.getStaticVariables().getVariableById(3); // SET THE EVIDENCE HashMapAssignment assignment = new HashMapAssignment(2); //assignment.setValue(ClassVar, 0.0); assignment.setValue(DiscreteVar0, 1.0); assignment.setValue(GaussianVar0, -2.0); //assignment.setValue(GaussianVar1, 0.0); // INFERENCE HuginInferenceForBN inferenceForBN = new HuginInferenceForBN(); inferenceForBN.setModel(bn); inferenceForBN.setEvidence(assignment); inferenceForBN.compileModel(); // POSTERIOR DISTRIBUTION System.out.println((inferenceForBN.getPosterior(ClassVar)).toString()); //System.out.println((inferenceForBN.getPosterior(DiscreteVar0)).toString()); //System.out.println((inferenceForBN.getPosterior(GaussianVar0)).toString()); //System.out.println((inferenceForBN.getPosterior(GaussianVar1)).toString()); } }
package com.ickstream.player.service; import com.ickstream.common.jsonrpc.*; import com.ickstream.player.model.PlaybackQueueItemInstance; import com.ickstream.player.model.PlayerStatus; import com.ickstream.protocol.common.NetworkAddressHelper; import com.ickstream.protocol.common.exception.ServiceException; import com.ickstream.protocol.common.exception.ServiceTimeoutException; import com.ickstream.protocol.service.core.AddDeviceRequest; import com.ickstream.protocol.service.core.AddDeviceResponse; import com.ickstream.protocol.service.core.CoreServiceFactory; import com.ickstream.protocol.service.core.GetUserResponse; import com.ickstream.protocol.service.player.*; import java.util.*; public class PlayerCommandService { private String apiKey; private PlayerStatus playerStatus; private PlayerManager player; private Timer volumeNotificationTimer; private final Object syncObject; /** * Should only be used for testing purposes, use {@link #PlayerCommandService(String, PlayerManager, com.ickstream.player.model.PlayerStatus, Object)} in other scenarios * * @param playerStatus */ public PlayerCommandService(PlayerStatus playerStatus) { this.playerStatus = playerStatus; this.syncObject = new Object(); } /** * @param syncObject all access to playerStatus will be synchronized against this object. * It is assumed that a PlayerManager will do likewise based on the actual playerstate. * By using the syncObject it can be guaranteed that remote calls and internal state changes * don't get into each other way. */ public PlayerCommandService(String apiKey, PlayerManager player, PlayerStatus playerStatus, final Object syncObject) { this.apiKey = apiKey; this.playerStatus = playerStatus; this.player = player; this.syncObject = syncObject; } public static List<PlaybackQueueItemInstance> createInstanceList(List<PlaybackQueueItem> items) { List<PlaybackQueueItemInstance> instances = new ArrayList<PlaybackQueueItemInstance>(items.size()); for (PlaybackQueueItem item : items) { PlaybackQueueItemInstance instance = new PlaybackQueueItemInstance(); instance.setId(item.getId()); instance.setText(item.getText()); instance.setType(item.getType()); instance.setItemAttributes(item.getItemAttributes()); instance.setStreamingRefs(item.getStreamingRefs()); instance.setImage(item.getImage()); instances.add(instance); } return instances; } public static PlaybackQueueItem createPlaybackQueueItem(PlaybackQueueItemInstance instance) { PlaybackQueueItem item = new PlaybackQueueItem(); item.setId(instance.getId()); item.setText(instance.getText()); item.setType(instance.getType()); item.setItemAttributes(instance.getItemAttributes()); item.setStreamingRefs(instance.getStreamingRefs()); item.setImage(instance.getImage()); return item; } public static List<PlaybackQueueItem> createPlaybackQueueItemList(List<PlaybackQueueItemInstance> instances) { List<PlaybackQueueItem> items = new ArrayList<PlaybackQueueItem>(instances.size()); for (PlaybackQueueItemInstance instance : instances) { items.add(createPlaybackQueueItem(instance)); } return items; } @JsonRpcErrors({ @JsonRpcError(exception = ServiceException.class, code = -32001, message = "Error when registering device"), @JsonRpcError(exception = ServiceTimeoutException.class, code = -32001, message = "Timeout when registering device") }) public PlayerConfigurationResponse setPlayerConfiguration(@JsonRpcParamStructure PlayerConfigurationRequest configuration) throws ServiceException, ServiceTimeoutException { synchronized (syncObject) { boolean sendPlayerStatusChanged = false; if (configuration.getCloudCoreUrl() != null) { if (!player.getCloudCoreUrl().equals(configuration.getCloudCoreUrl())) { if (player.hasAccessToken()) { sendPlayerStatusChanged = true; } player.setCloudCoreUrl(configuration.getCloudCoreUrl()); if (player.hasAccessToken()) { player.setAccessToken(null); } } } if (configuration.getDeviceRegistrationToken() != null && configuration.getDeviceRegistrationToken().length() > 0) { AddDeviceRequest request = new AddDeviceRequest(); request.setAddress(NetworkAddressHelper.getNetworkAddress()); request.setApplicationId(apiKey); request.setHardwareId(player.getHardwareId()); if (player.hasAccessToken()) { player.setAccessToken(null); } // We will send playerStatusChanged when the registration has finished/failed instead of immediately sendPlayerStatusChanged = false; CoreServiceFactory.getCoreService(player.getCloudCoreUrl(), configuration.getDeviceRegistrationToken()).addDevice(request, new MessageHandlerAdapter<AddDeviceResponse>() { @Override public void onMessage(AddDeviceResponse response) { player.setAccessToken(response.getAccessToken()); String userId = response.getUserId(); if (userId == null) { // This is a special case which only happens when used towards an old server that doesn't return userId in addDevice response try { GetUserResponse user = CoreServiceFactory.getCoreService(player.getCloudCoreUrl(), response.getAccessToken()).getUser(); if (user != null) { userId = user.getId(); } } catch (ServiceException e) { e.printStackTrace(); } catch (ServiceTimeoutException e) { e.printStackTrace(); } } player.setUserId(userId); } @Override public void onError(int code, String message, String data) { System.err.println("Error when registering player: " + code + " " + message + " " + data); } @Override public void onFinished() { player.sendPlayerStatusChangedNotification(); } }, 30000); } else if (configuration.getDeviceRegistrationToken() != null) { if (player.hasAccessToken()) { player.setAccessToken(null); sendPlayerStatusChanged = true; } } if (configuration.getPlayerName() != null) { player.setName(configuration.getPlayerName()); } if (sendPlayerStatusChanged) { player.sendPlayerStatusChangedNotification(); } return getPlayerConfiguration(); } } public ProtocolVersionsResponse getProtocolVersions() { return new ProtocolVersionsResponse("1.0", "1.0"); } public PlayerConfigurationResponse getPlayerConfiguration() { synchronized (syncObject) { PlayerConfigurationResponse response = new PlayerConfigurationResponse(); response.setPlayerName(player.getName()); response.setPlayerModel(player.getModel()); response.setCloudCoreUrl(player.getCloudCoreUrl()); if (player != null && player.hasAccessToken()) { response.setCloudCoreStatus(CloudCoreStatus.REGISTERED); response.setUserId(player.getUserId()); } else { response.setCloudCoreStatus(CloudCoreStatus.UNREGISTERED); } return response; } } public PlayerStatusResponse getPlayerStatus() { synchronized (syncObject) { PlayerStatusResponse response = new PlayerStatusResponse(); response.setPlaying(playerStatus.getPlaying()); response.setPlaybackQueuePos(playerStatus.getPlaybackQueuePos()); if (player != null && playerStatus.getPlaybackQueuePos() != null && playerStatus.getPlaying()) { playerStatus.setSeekPos(player.getSeekPosition()); } response.setSeekPos(playerStatus.getSeekPos()); if (playerStatus.getPlaybackQueue().getItems().size() > 0) { response.setTrack(createPlaybackQueueItem(playerStatus.getPlaybackQueue().getItems().get(playerStatus.getPlaybackQueuePos()))); } if (player != null && !playerStatus.getMuted()) { response.setVolumeLevel(player.getVolume()); } else { response.setVolumeLevel(playerStatus.getVolumeLevel()); } response.setLastChanged(playerStatus.getChangedTimestamp()); response.setMuted(playerStatus.getMuted()); response.setPlaybackQueueMode(playerStatus.getPlaybackQueueMode()); if (player != null && player.hasAccessToken()) { response.setCloudCoreStatus(CloudCoreStatus.REGISTERED); response.setUserId(player.getUserId()); } else { response.setCloudCoreStatus(CloudCoreStatus.UNREGISTERED); } return response; } } public SetPlaylistNameResponse setPlaylistName(@JsonRpcParamStructure SetPlaylistNameRequest request) { synchronized (syncObject) { playerStatus.getPlaybackQueue().setId(request.getPlaylistId()); playerStatus.getPlaybackQueue().setName(request.getPlaylistName()); if (player != null) { player.sendPlaylistChangedNotification(); } return new SetPlaylistNameResponse(playerStatus.getPlaybackQueue().getId(), playerStatus.getPlaybackQueue().getName(), playerStatus.getPlaybackQueue().getItems().size()); } } public PlaybackQueueResponse getPlaybackQueue(@JsonRpcParamStructure PlaybackQueueRequest request) { synchronized (syncObject) { PlaybackQueueResponse response = new PlaybackQueueResponse(); response.setPlaylistId(playerStatus.getPlaybackQueue().getId()); response.setPlaylistName(playerStatus.getPlaybackQueue().getName()); if (request.getOrder() != null) { response.setOrder(request.getOrder()); } else { response.setOrder(PlaybackQueueOrder.CURRENT); } List<PlaybackQueueItem> items = createPlaybackQueueItemList(playerStatus.getPlaybackQueue().getItems()); if (response.getOrder().equals(PlaybackQueueOrder.ORIGINAL)) { items = createPlaybackQueueItemList(playerStatus.getPlaybackQueue().getOriginallyOrderedItems()); } Integer offset = request.getOffset() != null ? request.getOffset() : 0; Integer count = request.getCount() != null ? request.getCount() : items.size(); response.setOffset(offset); response.setCountAll(playerStatus.getPlaybackQueue().getItems().size()); if (offset < items.size()) { if (offset + count > items.size()) { response.setItems(items.subList(offset, items.size())); } else { response.setItems(items.subList(offset, offset + count)); } } else { response.setItems(items.subList(offset, items.size())); } response.setCount(response.getItems().size()); response.setLastChanged(playerStatus.getPlaybackQueue().getChangedTimestamp()); return response; } } public PlaybackQueueModificationResponse addTracks(@JsonRpcParamStructure PlaybackQueueAddTracksRequest request) { synchronized (syncObject) { List<PlaybackQueueItemInstance> instances = createInstanceList(request.getItems()); if (request.getPlaybackQueuePos() != null) { // Insert tracks in middle playerStatus.getPlaybackQueue().getItems().addAll(request.getPlaybackQueuePos(), instances); playerStatus.getPlaybackQueue().getOriginallyOrderedItems().addAll(request.getPlaybackQueuePos(), instances); playerStatus.getPlaybackQueue().updateTimestamp(); if (playerStatus.getPlaybackQueuePos() != null && playerStatus.getPlaybackQueuePos() >= request.getPlaybackQueuePos()) { playerStatus.setPlaybackQueuePos(playerStatus.getPlaybackQueuePos() + request.getItems().size()); } } else { if (playerStatus.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_SHUFFLE) || playerStatus.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_REPEAT_SHUFFLE)) { // Add tracks at random position after currently playing track int currentPlaybackQueuePos = 0; if (playerStatus.getPlaybackQueuePos() != null) { currentPlaybackQueuePos = playerStatus.getPlaybackQueuePos(); } int rangeLength = playerStatus.getPlaybackQueue().getItems().size() - currentPlaybackQueuePos - 1; if (rangeLength > 0) { int randomPosition = currentPlaybackQueuePos + (int) (Math.random() * rangeLength) + 1; if (randomPosition < playerStatus.getPlaybackQueue().getItems().size() - 1) { playerStatus.getPlaybackQueue().getItems().addAll(randomPosition, instances); } else { playerStatus.getPlaybackQueue().getItems().addAll(instances); } } else { playerStatus.getPlaybackQueue().getItems().addAll(instances); } playerStatus.getPlaybackQueue().getOriginallyOrderedItems().addAll(instances); } else { // Add tracks at end playerStatus.getPlaybackQueue().getItems().addAll(instances); playerStatus.getPlaybackQueue().getOriginallyOrderedItems().addAll(instances); } playerStatus.getPlaybackQueue().updateTimestamp(); } // Set playback queue position to first track if there weren't any tracks in the playback queue before if (playerStatus.getPlaybackQueuePos() == null) { playerStatus.setPlaybackQueuePos(0); } if (player != null) { player.sendPlaylistChangedNotification(); } return new PlaybackQueueModificationResponse(true, playerStatus.getPlaybackQueuePos()); } } public PlaybackQueueModificationResponse removeTracks(@JsonRpcParamStructure PlaybackQueueRemoveTracksRequest request) { synchronized (syncObject) { List<PlaybackQueueItemInstance> modifiedPlaybackQueue = new ArrayList<PlaybackQueueItemInstance>(playerStatus.getPlaybackQueue().getItems()); List<PlaybackQueueItemInstance> modifiedOriginallyOrderedPlaybackQueue = new ArrayList<PlaybackQueueItemInstance>(playerStatus.getPlaybackQueue().getOriginallyOrderedItems()); int modifiedPlaybackQueuePos = playerStatus.getPlaybackQueuePos(); boolean affectsPlayback = false; for (PlaybackQueueItemReference itemReference : request.getItems()) { if (itemReference.getPlaybackQueuePos() != null) { PlaybackQueueItem item = playerStatus.getPlaybackQueue().getItems().get(itemReference.getPlaybackQueuePos()); if (item.getId().equals(itemReference.getId())) { if (itemReference.getPlaybackQueuePos() < playerStatus.getPlaybackQueuePos()) { modifiedPlaybackQueuePos } else if (itemReference.getPlaybackQueuePos().equals(playerStatus.getPlaybackQueuePos())) { affectsPlayback = true; } modifiedPlaybackQueue.remove(item); for (int i = 0; i < modifiedOriginallyOrderedPlaybackQueue.size(); i++) { // Intentionally using == instead of equals as we want the exact instance if (modifiedOriginallyOrderedPlaybackQueue.get(i) == item) { modifiedOriginallyOrderedPlaybackQueue.remove(i); } } } else { throw new IllegalArgumentException("Track identity and playback queue position doesn't match (trackId=" + itemReference.getId() + ", playbackQueuePos=" + itemReference.getPlaybackQueuePos() + ")"); } } else { int i = 0; for (Iterator<PlaybackQueueItemInstance> it = modifiedPlaybackQueue.iterator(); it.hasNext(); i++) { PlaybackQueueItem item = it.next(); if (item.getId().equals(itemReference.getId())) { if (i < modifiedPlaybackQueuePos) { modifiedPlaybackQueuePos } else if (i == modifiedPlaybackQueuePos) { affectsPlayback = true; } it.remove(); for (int j = 0; j < modifiedOriginallyOrderedPlaybackQueue.size(); j++) { // Intentionally using == instead of equals as we want the exact instance if (modifiedOriginallyOrderedPlaybackQueue.get(j) == item) { modifiedOriginallyOrderedPlaybackQueue.remove(j); } } } } } } playerStatus.getPlaybackQueue().setOriginallyOrderedItems(modifiedOriginallyOrderedPlaybackQueue); playerStatus.getPlaybackQueue().setItems(modifiedPlaybackQueue); if (modifiedPlaybackQueuePos >= modifiedPlaybackQueue.size()) { if (modifiedPlaybackQueuePos > 0) { modifiedPlaybackQueuePos } } if (!playerStatus.getPlaybackQueuePos().equals(modifiedPlaybackQueuePos)) { playerStatus.setPlaybackQueuePos(modifiedPlaybackQueuePos); if (!playerStatus.getPlaying()) { if (player != null) { player.sendPlayerStatusChangedNotification(); } } } // Make sure we make the player aware that it should change track if (playerStatus.getPlaying() && affectsPlayback && player != null) { if (modifiedPlaybackQueue.size() > 0) { player.play(); } else { playerStatus.setPlaybackQueuePos(null); playerStatus.setSeekPos(null); player.pause(); } } if (player != null) { player.sendPlaylistChangedNotification(); } return new PlaybackQueueModificationResponse(true, playerStatus.getPlaybackQueuePos()); } } public PlaybackQueueModificationResponse moveTracks(@JsonRpcParamStructure PlaybackQueueMoveTracksRequest request) { synchronized (syncObject) { Integer modifiedPlaybackQueuePos = playerStatus.getPlaybackQueuePos(); List<PlaybackQueueItemInstance> modifiedPlaylist = new ArrayList<PlaybackQueueItemInstance>(playerStatus.getPlaybackQueue().getItems()); Integer wantedPlaybackQueuePos = request.getPlaybackQueuePos() != null ? request.getPlaybackQueuePos() : playerStatus.getPlaybackQueue().getItems().size(); for (PlaybackQueueItemReference playbackQueueItemReference : request.getItems()) { if (playbackQueueItemReference.getPlaybackQueuePos() == null) { throw new IllegalArgumentException("moveTracks with items without playbackQueuePos not supported"); } if (playbackQueueItemReference.getId() == null) { throw new IllegalArgumentException("moveTracks with items without id not supported"); } // Move that doesn't affect playback queue position if (wantedPlaybackQueuePos <= modifiedPlaybackQueuePos && playbackQueueItemReference.getPlaybackQueuePos() < modifiedPlaybackQueuePos || wantedPlaybackQueuePos > modifiedPlaybackQueuePos && playbackQueueItemReference.getPlaybackQueuePos() > modifiedPlaybackQueuePos) { PlaybackQueueItemInstance item = modifiedPlaylist.remove(playbackQueueItemReference.getPlaybackQueuePos().intValue()); if (!item.getId().equals(playbackQueueItemReference.getId())) { throw new IllegalArgumentException("Playback queue position " + playbackQueueItemReference.getPlaybackQueuePos() + " does not match " + playbackQueueItemReference.getId()); } int offset = 0; if (wantedPlaybackQueuePos >= playbackQueueItemReference.getPlaybackQueuePos()) { offset = -1; } if (wantedPlaybackQueuePos + offset < modifiedPlaylist.size()) { modifiedPlaylist.add(wantedPlaybackQueuePos + offset, item); } else { modifiedPlaylist.add(item); } if (wantedPlaybackQueuePos < playbackQueueItemReference.getPlaybackQueuePos()) { wantedPlaybackQueuePos++; } // Move that increase playback queue position } else if (wantedPlaybackQueuePos <= modifiedPlaybackQueuePos && playbackQueueItemReference.getPlaybackQueuePos() > modifiedPlaybackQueuePos) { PlaybackQueueItemInstance item = modifiedPlaylist.remove(playbackQueueItemReference.getPlaybackQueuePos().intValue()); if (!item.getId().equals(playbackQueueItemReference.getId())) { throw new IllegalArgumentException("Playback queue position " + playbackQueueItemReference.getPlaybackQueuePos() + " does not match " + playbackQueueItemReference.getId()); } modifiedPlaylist.add(wantedPlaybackQueuePos, item); modifiedPlaybackQueuePos++; wantedPlaybackQueuePos++; // Move that decrease playback queue position } else if (wantedPlaybackQueuePos > modifiedPlaybackQueuePos && playbackQueueItemReference.getPlaybackQueuePos() < modifiedPlaybackQueuePos) { PlaybackQueueItemInstance item = modifiedPlaylist.remove(playbackQueueItemReference.getPlaybackQueuePos().intValue()); if (!item.getId().equals(playbackQueueItemReference.getId())) { throw new IllegalArgumentException("Playback queue position " + playbackQueueItemReference.getPlaybackQueuePos() + " does not match " + playbackQueueItemReference.getId()); } int offset = 0; if (wantedPlaybackQueuePos >= playbackQueueItemReference.getPlaybackQueuePos()) { offset = -1; } if (wantedPlaybackQueuePos + offset < modifiedPlaylist.size()) { modifiedPlaylist.add(wantedPlaybackQueuePos + offset, item); } else { modifiedPlaylist.add(item); } modifiedPlaybackQueuePos // Move of currently playing track } else if (playbackQueueItemReference.getPlaybackQueuePos().equals(modifiedPlaybackQueuePos)) { PlaybackQueueItemInstance item = modifiedPlaylist.remove(playbackQueueItemReference.getPlaybackQueuePos().intValue()); if (!item.getId().equals(playbackQueueItemReference.getId())) { throw new IllegalArgumentException("Playback queue position " + playbackQueueItemReference.getPlaybackQueuePos() + " does not match " + playbackQueueItemReference.getId()); } if (wantedPlaybackQueuePos < modifiedPlaylist.size() + 1) { if (wantedPlaybackQueuePos > playbackQueueItemReference.getPlaybackQueuePos()) { modifiedPlaylist.add(wantedPlaybackQueuePos - 1, item); modifiedPlaybackQueuePos = wantedPlaybackQueuePos - 1; } else { modifiedPlaylist.add(wantedPlaybackQueuePos, item); modifiedPlaybackQueuePos = wantedPlaybackQueuePos; } } else { modifiedPlaylist.add(item); modifiedPlaybackQueuePos = wantedPlaybackQueuePos - 1; } if (wantedPlaybackQueuePos < playbackQueueItemReference.getPlaybackQueuePos()) { wantedPlaybackQueuePos++; } } } if (!(playerStatus.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_SHUFFLE) || playerStatus.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_REPEAT_SHUFFLE))) { playerStatus.getPlaybackQueue().setOriginallyOrderedItems(new ArrayList<PlaybackQueueItemInstance>(modifiedPlaylist)); } playerStatus.getPlaybackQueue().setItems(modifiedPlaylist); playerStatus.getPlaybackQueue().updateTimestamp(); playerStatus.setPlaybackQueuePos(modifiedPlaybackQueuePos); if (player != null) { // playlist player.sendPlaylistChangedNotification(); // playbackQueuePos player.sendPlayerStatusChangedNotification(); } return new PlaybackQueueModificationResponse(true, modifiedPlaybackQueuePos); } } public PlaybackQueueModificationResponse setTracks(@JsonRpcParamStructure PlaybackQueueSetTracksRequest request) { synchronized (syncObject) { playerStatus.getPlaybackQueue().setId(request.getPlaylistId()); playerStatus.getPlaybackQueue().setName(request.getPlaylistName()); List<PlaybackQueueItemInstance> instances = createInstanceList(request.getItems()); playerStatus.getPlaybackQueue().setOriginallyOrderedItems(new ArrayList<PlaybackQueueItemInstance>(instances)); playerStatus.getPlaybackQueue().setItems(instances); Integer playbackQueuePos = request.getPlaybackQueuePos() != null ? request.getPlaybackQueuePos() : 0; if (request.getItems().size() > 0) { setTrack(playbackQueuePos); } else { playerStatus.setSeekPos(null); playerStatus.setPlaybackQueuePos(null); if (player != null && playerStatus.getPlaying()) { player.pause(); } } if (player != null) { player.sendPlaylistChangedNotification(); } return new PlaybackQueueModificationResponse(true, playerStatus.getPlaybackQueuePos()); } } @JsonRpcResult("playing") public Boolean play(@JsonRpcParam(name = "playing") Boolean play) { synchronized (syncObject) { if (playerStatus.getPlaybackQueuePos() != null && play != null) { if (!playerStatus.getPlaying() && play) { if (player == null || player.play()) { playerStatus.setPlaying(true); } } else if (playerStatus.getPlaying() && !play) { if (player == null || player.pause()) { playerStatus.setPlaying(false); } } } return playerStatus.getPlaying(); } } public SeekPosition getSeekPosition() { synchronized (syncObject) { SeekPosition response = new SeekPosition(); response.setPlaybackQueuePos(playerStatus.getPlaybackQueuePos()); if (player != null && playerStatus.getPlaybackQueuePos() != null && playerStatus.getPlaying()) { playerStatus.setSeekPos(player.getSeekPosition()); } response.setSeekPos(playerStatus.getSeekPos()); return response; } } public SeekPosition setSeekPosition(@JsonRpcParamStructure SeekPosition request) { synchronized (syncObject) { if (request.getPlaybackQueuePos() != null && playerStatus.getPlaybackQueue().getItems().size() > request.getPlaybackQueuePos()) { playerStatus.setPlaybackQueuePos(request.getPlaybackQueuePos()); Double seekPosition = request.getSeekPos() != null ? request.getSeekPos() : 0; //TODO: Handle logic regarding seek position and length of track playerStatus.setSeekPos(seekPosition); if (player != null) { player.setSeekPosition(seekPosition); } return getSeekPosition(); } else { throw new IllegalArgumentException("Invalid playback queue position specified"); } } } public TrackResponse getTrack(@JsonRpcParam(name = "playbackQueuePos", optional = true) Integer playbackQueuePos) { synchronized (syncObject) { TrackResponse response = new TrackResponse(); response.setPlaylistId(playerStatus.getPlaybackQueue().getId()); response.setPlaylistName(playerStatus.getPlaybackQueue().getName()); if (playbackQueuePos != null && playbackQueuePos < playerStatus.getPlaybackQueue().getItems().size()) { response.setPlaybackQueuePos(playbackQueuePos); response.setTrack(createPlaybackQueueItem(playerStatus.getPlaybackQueue().getItems().get(playbackQueuePos))); } else if (playbackQueuePos == null && playerStatus.getPlaybackQueuePos() != null) { response.setPlaybackQueuePos(playerStatus.getPlaybackQueuePos()); response.setTrack(createPlaybackQueueItem(playerStatus.getPlaybackQueue().getItems().get(playerStatus.getPlaybackQueuePos()))); } return response; } } @JsonRpcResult("playbackQueuePos") public Integer setTrack(@JsonRpcParam(name = "playbackQueuePos") Integer playbackQueuePos) { synchronized (syncObject) { if (playbackQueuePos != null && playbackQueuePos < playerStatus.getPlaybackQueue().getItems().size()) { playerStatus.setPlaybackQueuePos(playbackQueuePos); playerStatus.setSeekPos(0d); // Make sure we make the player aware that it should change track if (playerStatus.getPlaying() && player != null) { player.play(); } else { if (player != null) { player.sendPlayerStatusChangedNotification(); } } return playbackQueuePos; } else { throw new IllegalArgumentException("Invalid playback queue position specified"); } } } @JsonRpcResult("track") public PlaybackQueueItem setTrackMetadata(@JsonRpcParamStructure TrackMetadataRequest request) { synchronized (syncObject) { if (request.getPlaybackQueuePos() != null) { if (request.getPlaybackQueuePos() < playerStatus.getPlaybackQueue().getItems().size()) { PlaybackQueueItemInstance item = playerStatus.getPlaybackQueue().getItems().get(request.getPlaybackQueuePos()); if (request.getTrack().getId().equals(item.getId())) { if (request.getReplace()) { item.setType(request.getTrack().getType()); item.setImage(request.getTrack().getImage()); item.setText(request.getTrack().getText()); item.setItemAttributes(request.getTrack().getItemAttributes()); item.setStreamingRefs(request.getTrack().getStreamingRefs()); playerStatus.getPlaybackQueue().updateTimestamp(); } else { if (request.getTrack().getImage() != null) { item.setImage(request.getTrack().getImage()); playerStatus.getPlaybackQueue().updateTimestamp(); } if (request.getTrack().getText() != null) { item.setText(request.getTrack().getText()); playerStatus.getPlaybackQueue().updateTimestamp(); } if (request.getTrack().getType() != null) { item.setType(request.getTrack().getType()); playerStatus.getPlaybackQueue().updateTimestamp(); } if (request.getTrack().getStreamingRefs() != null) { item.setStreamingRefs(request.getTrack().getStreamingRefs()); playerStatus.getPlaybackQueue().updateTimestamp(); } //TODO: Implement copying of item attributes } if (playerStatus.getPlaybackQueuePos() != null && playerStatus.getPlaybackQueuePos().equals(request.getPlaybackQueuePos())) { playerStatus.updateTimestamp(); if (player != null) { player.sendPlayerStatusChangedNotification(); } } if (player != null) { player.sendPlaylistChangedNotification(); } return playerStatus.getPlaybackQueue().getItems().get(request.getPlaybackQueuePos()); } else { throw new RuntimeException("Specified track doesn't exist at the specified playback queue position"); } } else { throw new RuntimeException("Invalid playback queue position"); } } else { PlaybackQueueItem response = null; for (int playbackQueuePos = 0; playbackQueuePos < playerStatus.getPlaybackQueue().getItems().size(); playbackQueuePos++) { PlaybackQueueItemInstance item = playerStatus.getPlaybackQueue().getItems().get(playbackQueuePos); if (request.getTrack().getId().equals(item.getId())) { if (request.getReplace()) { item.setType(request.getTrack().getType()); item.setImage(request.getTrack().getImage()); item.setText(request.getTrack().getText()); item.setItemAttributes(request.getTrack().getItemAttributes()); item.setStreamingRefs(request.getTrack().getStreamingRefs()); playerStatus.getPlaybackQueue().updateTimestamp(); response = request.getTrack(); } else { if (request.getTrack().getImage() != null) { item.setImage(request.getTrack().getImage()); playerStatus.getPlaybackQueue().updateTimestamp(); } if (request.getTrack().getText() != null) { item.setText(request.getTrack().getText()); playerStatus.getPlaybackQueue().updateTimestamp(); } if (request.getTrack().getType() != null) { item.setType(request.getTrack().getType()); playerStatus.getPlaybackQueue().updateTimestamp(); } if (request.getTrack().getStreamingRefs() != null) { item.setStreamingRefs(request.getTrack().getStreamingRefs()); playerStatus.getPlaybackQueue().updateTimestamp(); } //TODO: Implement copying of item attributes response = item; } if (playerStatus.getPlaybackQueuePos() != null && playerStatus.getPlaybackQueuePos().equals(playbackQueuePos)) { playerStatus.updateTimestamp(); if (player != null) { player.sendPlayerStatusChangedNotification(); } } } } if (player != null) { player.sendPlaylistChangedNotification(); } return response; } } } public VolumeResponse getVolume() { synchronized (syncObject) { VolumeResponse response = new VolumeResponse(); if (player != null && !playerStatus.getMuted()) { response.setVolumeLevel(player.getVolume()); } else { response.setVolumeLevel(playerStatus.getVolumeLevel()); } response.setMuted(playerStatus.getMuted()); return response; } } public VolumeResponse setVolume(@JsonRpcParamStructure VolumeRequest request) { synchronized (syncObject) { Double volume = playerStatus.getVolumeLevel(); if (request.getVolumeLevel() != null) { volume = request.getVolumeLevel(); } else if (request.getRelativeVolumeLevel() != null) { volume += request.getRelativeVolumeLevel(); } if (volume < 0) { volume = 0d; } if (volume > 1) { volume = 1d; } playerStatus.setVolumeLevel(volume); if (player != null) { if ((request.getMuted() == null && !playerStatus.getMuted()) || (request.getMuted() != null && !request.getMuted())) { player.setVolume(volume); } } if (request.getMuted() != null) { playerStatus.setMuted(request.getMuted()); if (player != null && request.getMuted()) { player.setVolume(0.0); } } if (volumeNotificationTimer == null) { volumeNotificationTimer = new Timer(); volumeNotificationTimer.schedule(new TimerTask() { @Override public void run() { if (player != null) { player.sendPlayerStatusChangedNotification(); } volumeNotificationTimer = null; } }, 2000); } return getVolume(); } } public PlaybackQueueModeResponse setPlaybackQueueMode(@JsonRpcParamStructure PlaybackQueueModeRequest request) { synchronized (syncObject) { boolean shuffle = false; boolean shuffleWasTurnedOff = (playerStatus.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_SHUFFLE) || playerStatus.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_REPEAT_SHUFFLE)) && !(request.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_SHUFFLE) || request.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_REPEAT_SHUFFLE)); boolean shuffleWasTurnedOn = (request.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_SHUFFLE) && !playerStatus.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_REPEAT_SHUFFLE)) || (request.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_REPEAT_SHUFFLE) && !playerStatus.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_SHUFFLE)); if (shuffleWasTurnedOff) { Integer currentPos = playerStatus.getPlaybackQueuePos(); PlaybackQueueItemInstance currentTrack = null; if (currentPos != null && playerStatus.getPlaybackQueue().getItems().size() > currentPos) { currentTrack = playerStatus.getPlaybackQueue().getItems().get(currentPos); } playerStatus.getPlaybackQueue().setItems(new ArrayList<PlaybackQueueItemInstance>(playerStatus.getPlaybackQueue().getOriginallyOrderedItems())); if (player != null) { player.sendPlaylistChangedNotification(); } if (currentTrack != null) { int newPos = playerStatus.getPlaybackQueue().getItems().indexOf(currentTrack); if (newPos >= 0) { playerStatus.setPlaybackQueuePos(newPos); if (player != null) { player.sendPlayerStatusChangedNotification(); } } } } else if (shuffleWasTurnedOn) { shuffle = true; } playerStatus.setPlaybackQueueMode(request.getPlaybackQueueMode()); if (shuffle) { boolean needsEvents = internalShuffleTracks(); if (needsEvents && player != null) { player.sendPlaylistChangedNotification(); // playerStatusChanged should be sent here, because playbackPosition has changed. // we do it later anyways because of the playbackQueueModeChange } } // every change of playbackQueueMode needs a playerstatusChangedNotification if (player != null) { player.sendPlayerStatusChangedNotification(); } return new PlaybackQueueModeResponse(playerStatus.getPlaybackQueueMode()); } } public PlaybackQueueModificationResponse shuffleTracks() { synchronized (syncObject) { boolean needsEvents = internalShuffleTracks(); if (needsEvents && player != null) { player.sendPlaylistChangedNotification(); player.sendPlayerStatusChangedNotification(); } return new PlaybackQueueModificationResponse(true, playerStatus.getPlaybackQueuePos()); } } /** * shuffles all tracks without sending any notification. Tracks are not shuffled when there are no or only one item in the playbackQueue * * @return whether tracks have been shuffled at all and a notification needs to be sent to the player * caller has to make sure, that following notifications are sent: * playlistChangeNotification: because all tracks have changed their order * playerStatusChanged: because the playbackQueuePos will have changed */ private boolean internalShuffleTracks() { List<PlaybackQueueItemInstance> playbackQueueItems = playerStatus.getPlaybackQueue().getItems(); if (playbackQueueItems.size() > 1) { PlaybackQueueItemInstance currentItem = null; if (playerStatus.getPlaybackQueuePos() != null && playerStatus.getPlaybackQueuePos() < playbackQueueItems.size()) { currentItem = playbackQueueItems.remove(playerStatus.getPlaybackQueuePos().intValue()); } Collections.shuffle(playbackQueueItems); if (currentItem != null) { playbackQueueItems.add(0, currentItem); } if (!playerStatus.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_SHUFFLE) && !playerStatus.getPlaybackQueueMode().equals(PlaybackQueueMode.QUEUE_REPEAT_SHUFFLE)) { playerStatus.getPlaybackQueue().setOriginallyOrderedItems(new ArrayList<PlaybackQueueItemInstance>(playbackQueueItems)); } playerStatus.getPlaybackQueue().setItems(playbackQueueItems); playerStatus.setPlaybackQueuePos(0); return true; } return false; } public synchronized PlaybackQueueModificationResponse setDynamicPlaybackQueueParameters(@JsonRpcParamStructure DynamicPlaybackQueueParametersRequest request) { synchronized (syncObject) { //TODO: Implement return new PlaybackQueueModificationResponse(true, playerStatus.getPlaybackQueuePos()); } } }
// RMG - Reaction Mechanism Generator // RMG Team (rmg_dev@mit.edu) // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // 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. package jing.rxnSys; import java.io.*; import jing.rxnSys.ReactionSystem; import jing.rxn.*; import jing.chem.*; import java.util.*; import jing.mathTool.UncertainDouble; import jing.param.*; import jing.chemUtil.*; import jing.chemParser.*; //## package jing::rxnSys // jing\rxnSys\ReactionModelGenerator.java //## class ReactionModelGenerator public class ReactionModelGenerator { protected LinkedList timeStep; //## attribute timeStep protected ReactionModel reactionModel; //gmagoon 9/24/07 protected String workingDirectory; //## attribute workingDirectory // protected ReactionSystem reactionSystem; protected LinkedList reactionSystemList; //10/24/07 gmagoon: changed from reactionSystem to reactionSystemList protected int paraInfor;//svp protected boolean error;//svp protected boolean sensitivity;//svp protected LinkedList species;//svp // protected InitialStatus initialStatus;//svp protected LinkedList initialStatusList; //10/23/07 gmagoon: changed from initialStatus to initialStatusList protected double rtol;//svp protected static double atol; protected PrimaryKineticLibrary primaryKineticLibrary;//9/24/07 gmagoon protected ReactionLibrary ReactionLibrary; protected ReactionModelEnlarger reactionModelEnlarger;//9/24/07 gmagoon protected LinkedHashSet speciesSeed;//9/24/07 gmagoon; protected ReactionGenerator reactionGenerator;//9/24/07 gmagoon protected LibraryReactionGenerator lrg;// = new LibraryReactionGenerator();//9/24/07 gmagoon: moved from ReactionSystem.java;10/4/07 gmagoon: postponed initialization of lrg til later //10/23/07 gmagoon: added additional variables protected LinkedList tempList; protected LinkedList presList; protected LinkedList validList;//10/24/07 gmagoon: added //10/25/07 gmagoon: moved variables from modelGeneration() protected LinkedList initList = new LinkedList(); protected LinkedList beginList = new LinkedList(); protected LinkedList endList = new LinkedList(); protected LinkedList lastTList = new LinkedList(); protected LinkedList currentTList = new LinkedList(); protected LinkedList lastPList = new LinkedList(); protected LinkedList currentPList = new LinkedList(); protected LinkedList conditionChangedList = new LinkedList(); protected LinkedList reactionChangedList = new LinkedList(); protected int numConversions;//5/6/08 gmagoon: moved from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator() protected String equationOfState; // 24Jun2009 MRH: variable stores the first temperature encountered in the condition.txt file // This temperature is used to select the "best" kinetics from the rxn library protected static Temperature temp4BestKinetics; // Added by AJ on July 12, 2010 protected static boolean useDiffusion; protected static boolean useSolvation; protected SeedMechanism seedMechanism = null; protected PrimaryThermoLibrary primaryThermoLibrary; protected PrimaryTransportLibrary primaryTransportLibrary; protected PrimaryAbrahamLibrary primaryAbrahamLibrary; protected static SolventData solvent; protected SolventLibrary solventLibrary; protected static double viscosity; protected boolean readrestart = false; protected boolean writerestart = false; protected LinkedHashSet restartCoreSpcs = new LinkedHashSet(); protected LinkedHashSet restartEdgeSpcs = new LinkedHashSet(); protected LinkedHashSet restartCoreRxns = new LinkedHashSet(); protected LinkedHashSet restartEdgeRxns = new LinkedHashSet(); // Constructors private HashSet specs = new HashSet(); //public static native long getCpuTime(); //static {System.loadLibrary("cpuTime");} public static boolean rerunFame = false; protected static double tolerance;//can be interpreted as "coreTol" (vs. edgeTol) protected static double termTol; protected static double edgeTol; protected static int minSpeciesForPruning; protected static int maxEdgeSpeciesAfterPruning; public int limitingReactantID = 1; public int numberOfEquivalenceRatios = 0; //## operation ReactionModelGenerator() public ReactionModelGenerator() { workingDirectory = System.getProperty("RMG.workingDirectory"); } //## operation initializeReactionSystem() //10/24/07 gmagoon: changed name to initializeReactionSystems public void initializeReactionSystems() throws InvalidSymbolException, IOException { //#[ operation initializeReactionSystem() try { String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile"); if (initialConditionFile == null) { Logger.critical("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile"); System.exit(0); } //double sandeep = getCpuTime(); //System.out.println(getCpuTime()/1e9/60); FileReader in = new FileReader(initialConditionFile); BufferedReader reader = new BufferedReader(in); //TemperatureModel temperatureModel = null;//10/27/07 gmagoon: commented out //PressureModel pressureModel = null;//10/27/07 gmagoon: commented out // ReactionModelEnlarger reactionModelEnlarger = null;//10/9/07 gmagoon: commented out: unneeded now and causes scope problems FinishController finishController = null; //DynamicSimulator dynamicSimulator = null;//10/27/07 gmagoon: commented out and replaced with following line LinkedList dynamicSimulatorList = new LinkedList(); setPrimaryKineticLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary double [] conversionSet = new double[50]; String line = ChemParser.readMeaningfulLine(reader, true); /*if (line.startsWith("Restart")){ StringTokenizer st = new StringTokenizer(line); String token = st.nextToken(); token = st.nextToken(); if (token.equalsIgnoreCase("true")) { //Runtime.getRuntime().exec("cp Restart/allSpecies.txt Restart/allSpecies1.txt"); //Runtime.getRuntime().exec("echo >> allSpecies.txt"); restart = true; } else if (token.equalsIgnoreCase("false")) { Runtime.getRuntime().exec("rm Restart/allSpecies.txt"); restart = false; } else throw new InvalidSymbolException("UnIdentified Symbol "+token+" after Restart:"); } else throw new InvalidSymbolException("Can't find Restart!");*/ //line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("Database")){//svp line = ChemParser.readMeaningfulLine(reader, true); } else throw new InvalidSymbolException("Can't find database!"); // if (line.startsWith("PrimaryThermoLibrary")){//svp // line = ChemParser.readMeaningfulLine(reader); // else throw new InvalidSymbolException("Can't find primary thermo library!"); /* * Added by MRH on 15-Jun-2009 * Give user the option to change the maximum carbon, oxygen, * and/or radical number for all species. These lines will be * optional in the condition.txt file. Values are hard- * coded into RMG (in ChemGraph.java), but any user- * defined input will override these values. */ /* * Moved from before InitialStatus to before PrimaryThermoLibary * by MRH on 27-Oct-2009 * Overriding default values of maximum number of "X" per * chemgraph should come before RMG attempts to make any * chemgraph. The first instance RMG will attempt to make a * chemgraph is in reading the primary thermo library. */ line = readMaxAtomTypes(line,reader); // if (line.startsWith("MaxCarbonNumber")) { // StringTokenizer st = new StringTokenizer(line); // String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:" // int maxCNum = Integer.parseInt(st.nextToken()); // ChemGraph.setMaxCarbonNumber(maxCNum); // System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum); // line = ChemParser.readMeaningfulLine(reader); // if (line.startsWith("MaxOxygenNumber")) { // StringTokenizer st = new StringTokenizer(line); // String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:" // int maxONum = Integer.parseInt(st.nextToken()); // ChemGraph.setMaxOxygenNumber(maxONum); // System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum); // line = ChemParser.readMeaningfulLine(reader); // if (line.startsWith("MaxRadicalNumber")) { // StringTokenizer st = new StringTokenizer(line); // String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:" // int maxRadNum = Integer.parseInt(st.nextToken()); // ChemGraph.setMaxRadicalNumber(maxRadNum); // System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum); // line = ChemParser.readMeaningfulLine(reader); // if (line.startsWith("MaxSulfurNumber")) { // StringTokenizer st = new StringTokenizer(line); // String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:" // int maxSNum = Integer.parseInt(st.nextToken()); // ChemGraph.setMaxSulfurNumber(maxSNum); // System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum); // line = ChemParser.readMeaningfulLine(reader); // if (line.startsWith("MaxSiliconNumber")) { // StringTokenizer st = new StringTokenizer(line); // String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:" // int maxSiNum = Integer.parseInt(st.nextToken()); // ChemGraph.setMaxSiliconNumber(maxSiNum); // System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum); // line = ChemParser.readMeaningfulLine(reader); // if (line.startsWith("MaxHeavyAtom")) { // StringTokenizer st = new StringTokenizer(line); // String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:" // int maxHANum = Integer.parseInt(st.nextToken()); // ChemGraph.setMaxHeavyAtomNumber(maxHANum); // System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum); // line = ChemParser.readMeaningfulLine(reader); /* * Read in the Primary Thermo Library * MRH 7-Jul-2009 */ if (line.startsWith("PrimaryThermoLibrary:")) { /* * MRH 27Feb2010: * Changing the "read in Primary Thermo Library information" code * into it's own method. * * Other modules (e.g. PopulateReactions) will be utilizing the exact code. * Rather than copying and pasting code into other modules, just have * everything call this new method: readAndMakePTL */ readAndMakePTL(reader); } else throw new InvalidSymbolException("Error reading condition.txt file: " + "Could not locate PrimaryThermoLibrary field"); line = ChemParser.readMeaningfulLine(reader, true); /* * MRH 17-May-2010: * Added primary transport library field */ if (line.toLowerCase().startsWith("primarytransportlibrary")) { readAndMakePTransL(reader); } else throw new InvalidSymbolException("Error reading condition.txt file: " + "Could not locate PrimaryTransportLibrary field."); line = ChemParser.readMeaningfulLine(reader, true); // Extra forbidden structures may be specified after the Primary Thermo Library if (line.startsWith("ForbiddenStructures:")) { readExtraForbiddenStructures(reader); line = ChemParser.readMeaningfulLine(reader, true); } if (line.toLowerCase().startsWith("readrestart")) { StringTokenizer st = new StringTokenizer(line); String tempString = st.nextToken(); // "ReadRestart:" tempString = st.nextToken(); if (tempString.toLowerCase().equals("yes")) { readrestart = true; readRestartSpecies(); readRestartReactions(); } else readrestart = false; line = ChemParser.readMeaningfulLine(reader, true); } else throw new InvalidSymbolException("Cannot locate ReadRestart field"); if (line.toLowerCase().startsWith("writerestart")) { StringTokenizer st = new StringTokenizer(line); String tempString = st.nextToken(); // "WriteRestart:" tempString = st.nextToken(); if (tempString.toLowerCase().equals("yes")) writerestart = true; else writerestart = false; line = ChemParser.readMeaningfulLine(reader, true); } else throw new InvalidSymbolException("Cannot locate WriteRestart field"); // read temperature model //gmagoon 10/23/07: modified to handle multiple temperatures; note that this requires different formatting of units in condition.txt if (line.startsWith("TemperatureModel:")) { createTModel(line); // StringTokenizer st = new StringTokenizer(line); // String name = st.nextToken(); // String modelType = st.nextToken(); // //String t = st.nextToken(); // String unit = st.nextToken(); // unit = ChemParser.removeBrace(unit); // if (modelType.equals("Constant")) { // tempList = new LinkedList(); // //read first temperature // double t = Double.parseDouble(st.nextToken()); // tempList.add(new ConstantTM(t, unit)); // Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature // Global.lowTemperature = (Temperature)temp.clone(); // Global.highTemperature = (Temperature)temp.clone(); // //read remaining temperatures // while (st.hasMoreTokens()) { // t = Double.parseDouble(st.nextToken()); // tempList.add(new ConstantTM(t, unit)); // temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature // if(temp.getK() < Global.lowTemperature.getK()) // Global.lowTemperature = (Temperature)temp.clone(); // if(temp.getK() > Global.highTemperature.getK()) // Global.highTemperature = (Temperature)temp.clone(); // // Global.temperature = new Temperature(t,unit); //10/23/07 gmagoon: commenting out; further updates needed to get this to work //else if (modelType.equals("Curved")) { // String t = st.nextToken(); // // add reading curved temperature function here // temperatureModel = new CurvedTM(new LinkedList()); // else { // throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType); } else throw new InvalidSymbolException("condition.txt: can't find TemperatureModel!"); // read in pressure model line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("PressureModel:")) { createPModel(line); // StringTokenizer st = new StringTokenizer(line); // String name = st.nextToken(); // String modelType = st.nextToken(); // //String p = st.nextToken(); // String unit = st.nextToken(); // unit = ChemParser.removeBrace(unit); // if (modelType.equals("Constant")) { // presList = new LinkedList(); // //read first pressure // double p = Double.parseDouble(st.nextToken()); // Pressure pres = new Pressure(p, unit); // Global.lowPressure = (Pressure)pres.clone(); // Global.highPressure = (Pressure)pres.clone(); // presList.add(new ConstantPM(p, unit)); // //read remaining temperatures // while (st.hasMoreTokens()) { // p = Double.parseDouble(st.nextToken()); // presList.add(new ConstantPM(p, unit)); // pres = new Pressure(p, unit); // if(pres.getBar() < Global.lowPressure.getBar()) // Global.lowPressure = (Pressure)pres.clone(); // if(pres.getBar() > Global.lowPressure.getBar()) // Global.highPressure = (Pressure)pres.clone(); // //Global.pressure = new Pressure(p, unit); // //10/23/07 gmagoon: commenting out; further updates needed to get this to work // //else if (modelType.equals("Curved")) { // // // add reading curved pressure function here // // pressureModel = new CurvedPM(new LinkedList()); // else { // throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType); } else throw new InvalidSymbolException("condition.txt: can't find PressureModel!"); // after PressureModel comes an optional line EquationOfState // if "EquationOfState: Liquid" is found then initial concentrations are assumed to be correct // if it is ommited, then initial concentrations are normalised to ensure PV=NRT (ideal gas law) line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("EquationOfState")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String eosType = st.nextToken().toLowerCase(); if (eosType.equals("liquid")) { equationOfState="Liquid"; Logger.info("Equation of state: Liquid. Relying on concentrations in input file to get density correct; not checking PV=NRT"); } line = ChemParser.readMeaningfulLine(reader, true); } // Read in InChI generation if (line.startsWith("InChIGeneration:")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String inchiOnOff = st.nextToken().toLowerCase(); if (inchiOnOff.equals("on")) { Species.useInChI = true; } else if (inchiOnOff.equals("off")) { Species.useInChI = false; } else throw new InvalidSymbolException("condition.txt: Unknown InChIGeneration flag: " + inchiOnOff); line = ChemParser.readMeaningfulLine(reader, true); } // Read in Solvation effects if (line.startsWith("Solvation:")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String solvationOnOff = st.nextToken().toLowerCase(); if (solvationOnOff.equals("on")) { setUseSolvation(true); Species.useSolvation = true; readAndMakePAL(); String solventname = st.nextToken().toLowerCase(); readAndMakeSL(solventname); System.out.println(String.format( "Using solvation corrections to thermochemsitry with solvent properties of %s",solventname)); } else if (solvationOnOff.startsWith("off")) { setUseSolvation(false); Species.useSolvation = false; } else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff); line = ChemParser.readMeaningfulLine(reader, true); } // Read in Diffusion effects // If 'Diffusion' is 'on' then override the settings made by the solvation flag and sets solvation 'on' if (line.startsWith("Diffusion:")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String diffusionOnOff = st.nextToken().toLowerCase(); if (diffusionOnOff.equals("on")) { String viscosity_str = st.nextToken(); viscosity = Double.parseDouble(viscosity_str); setUseDiffusion(true); System.out.println(String.format( "Using diffusion corrections to kinetics with solvent viscosity of %.3g Pa.s.",viscosity)); } else if (diffusionOnOff.equals("off")) { setUseDiffusion(false); } else throw new InvalidSymbolException("condition.txt: Unknown diffusion flag: " + diffusionOnOff); line = ChemParser.readMeaningfulLine(reader,true);//read in reactants or thermo line } /* AJ 12JULY2010: * Right now we do not want RMG to throw an exception if it cannot find a diffusion flag */ //else throw new InvalidSymbolException("condition.txt: Cannot find diffusion flag."); // Should have already read in reactants or thermo line into variable 'line' // Read in optional QM thermo generation if (line.startsWith("ThermoMethod:")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String thermoMethod = st.nextToken().toLowerCase(); if (thermoMethod.equals("qm")) { ChemGraph.useQM = true; if(st.hasMoreTokens()){//override the default qmprogram ("both") if there are more; current options: "gaussian03" and "mopac" and of course, "both" QMTP.qmprogram = st.nextToken().toLowerCase(); } line=ChemParser.readMeaningfulLine(reader, true); if(line.startsWith("QMForCyclicsOnly:")){ StringTokenizer st2 = new StringTokenizer(line); String nameCyc = st2.nextToken(); String option = st2.nextToken().toLowerCase(); if (option.equals("on")) { ChemGraph.useQMonCyclicsOnly = true; } } else{ Logger.critical("condition.txt: Can't find 'QMForCyclicsOnly:' field"); System.exit(0); } line=ChemParser.readMeaningfulLine(reader, true); if(line.startsWith("MaxRadNumForQM:")){ StringTokenizer st3 = new StringTokenizer(line); String nameRadNum = st3.nextToken(); Global.maxRadNumForQM = Integer.parseInt(st3.nextToken()); } else{ Logger.critical("condition.txt: Can't find 'MaxRadNumForQM:' field"); System.exit(0); } }//otherwise, the flag useQM will remain false by default and the traditional group additivity approach will be used line = ChemParser.readMeaningfulLine(reader, true);//read in reactants } // // Read in Solvation effects // if (line.startsWith("Solvation:")) { // StringTokenizer st = new StringTokenizer(line); // String name = st.nextToken(); // String solvationOnOff = st.nextToken().toLowerCase(); // if (solvationOnOff.equals("on")) { // Species.useSolvation = true; // } else if (solvationOnOff.equals("off")) { // Species.useSolvation = false; // else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff); // else throw new InvalidSymbolException("condition.txt: Cannot find solvation flag."); // read in reactants //10/4/07 gmagoon: moved to initializeCoreEdgeReactionModel //LinkedHashSet p_speciesSeed = new LinkedHashSet();//gmagoon 10/4/07: changed to p_speciesSeed //setSpeciesSeed(p_speciesSeed);//gmagoon 10/4/07: added LinkedHashMap speciesSet = new LinkedHashMap(); /* * 7/Apr/2010: MRH * Neither of these variables are utilized */ // LinkedHashMap speciesStatus = new LinkedHashMap(); // int speciesnum = 1; //System.out.println(line); if (line.startsWith("InitialStatus")) { speciesSet = populateInitialStatusListWithReactiveSpecies(reader); // line = ChemParser.readMeaningfulLine(reader); // while (!line.equals("END")) { // StringTokenizer st = new StringTokenizer(line); // String index = st.nextToken(); // String name = null; // if (!index.startsWith("(")) name = index; // else name = st.nextToken(); // //if (restart) name += "("+speciesnum+")"; // // 24Jun2009: MRH // // Check if the species name begins with a number. // // If so, terminate the program and inform the user to choose // // a different name. This is implemented so that the chem.inp // // file generated will be valid when run in Chemkin // try { // int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1)); // System.out.println("\nA species name should not begin with a number." + // " Please rename species: " + name + "\n"); // System.exit(0); // } catch (NumberFormatException e) { // // We're good // speciesnum ++; // if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name); // String conc = st.nextToken(); // double concentration = Double.parseDouble(conc); // String unit = st.nextToken(); // unit = ChemParser.removeBrace(unit); // if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) { // concentration /= 1000; // unit = "mol/cm3"; // else if (unit.equals("mole/m3") || unit.equals("mol/m3")) { // concentration /= 1000000; // unit = "mol/cm3"; // else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) { // concentration /= 6.022e23; // else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) { // throw new InvalidUnitException("Species Concentration in condition.txt!"); // //GJB to allow "unreactive" species that only follow user-defined library reactions. // // They will not react according to RMG reaction families // boolean IsReactive = true; // boolean IsConstantConcentration = false; // while (st.hasMoreTokens()) { // String reactive = st.nextToken().trim(); // if (reactive.equalsIgnoreCase("unreactive")) // IsReactive = false; // if (reactive.equalsIgnoreCase("constantconcentration")) // IsConstantConcentration=true; // Graph g = ChemParser.readChemGraph(reader); // ChemGraph cg = null; // try { // cg = ChemGraph.make(g); // catch (ForbiddenStructureException e) { // System.out.println("Forbidden Structure:\n" + e.getMessage()); // throw new InvalidSymbolException("A species in the input file has a forbidden structure."); // //System.out.println(name); // Species species = Species.make(name,cg); // species.setReactivity(IsReactive); // GJB // species.setConstantConcentration(IsConstantConcentration); // speciesSet.put(name, species); // getSpeciesSeed().add(species); // double flux = 0; // int species_type = 1; // reacted species // SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux); // speciesStatus.put(species, ss); // line = ChemParser.readMeaningfulLine(reader); // ReactionTime initial = new ReactionTime(0,"S"); // //10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem // initialStatusList = new LinkedList(); // for (Iterator iter = tempList.iterator(); iter.hasNext(); ) { // TemperatureModel tm = (TemperatureModel)iter.next(); // for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){ // PressureModel pm = (PressureModel)iter2.next(); // // LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all) // Set ks = speciesStatus.keySet(); // LinkedHashMap speStat = new LinkedHashMap(); // for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?) // SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next()); // speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux())); // initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial))); } else throw new InvalidSymbolException("condition.txt: can't find InitialStatus!"); // read in inert gas concentration line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("InertGas:")) { populateInitialStatusListWithInertSpecies(reader); // line = ChemParser.readMeaningfulLine(reader); // while (!line.equals("END")) { // StringTokenizer st = new StringTokenizer(line); // String name = st.nextToken().trim(); // String conc = st.nextToken(); // double inertConc = Double.parseDouble(conc); // String unit = st.nextToken(); // unit = ChemParser.removeBrace(unit); // if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) { // inertConc /= 1000; // unit = "mol/cm3"; // else if (unit.equals("mole/m3") || unit.equals("mol/m3")) { // inertConc /= 1000000; // unit = "mol/cm3"; // else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) { // inertConc /= 6.022e23; // unit = "mol/cm3"; // else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) { // throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit); // //SystemSnapshot.putInertGas(name,inertConc); // for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc // ((InitialStatus)iter.next()).putInertGas(name,inertConc); // line = ChemParser.readMeaningfulLine(reader); } else throw new InvalidSymbolException("condition.txt: can't find Inert gas concentration!"); // read in spectroscopic data estimator line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("SpectroscopicDataEstimator:")) { setSpectroscopicDataMode(line); // StringTokenizer st = new StringTokenizer(line); // String name = st.nextToken(); // String sdeType = st.nextToken().toLowerCase(); // if (sdeType.equals("frequencygroups") || sdeType.equals("default")) { // SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS; // else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) { // SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY; // else if (sdeType.equals("off") || sdeType.equals("none")) { // SpectroscopicData.mode = SpectroscopicData.Mode.OFF; // else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType); } else throw new InvalidSymbolException("condition.txt: can't find SpectroscopicDataEstimator!"); // pressure dependence and related flags line = ChemParser.readMeaningfulLine(reader, true); if (line.toLowerCase().startsWith("pressuredependence:")) line = setPressureDependenceOptions(line,reader); else throw new InvalidSymbolException("condition.txt: can't find PressureDependence flag!"); if (readrestart) if (PDepNetwork.generateNetworks) readPDepNetworks(); // include species (optional) /* * * MRH 3-APR-2010: * This if statement is no longer necessary and was causing an error * when the PressureDependence field was set to "off" */ // if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") && // !PDepRateConstant.getMode().name().equals("PDEPARRHENIUS")) // line = ChemParser.readMeaningfulLine(reader); // read in finish controller if (line.startsWith("FinishController")) { line = ChemParser.readMeaningfulLine(reader, true); StringTokenizer st = new StringTokenizer(line); String index = st.nextToken(); String goal = st.nextToken(); String type = st.nextToken(); TerminationTester tt; if (type.startsWith("Conversion")) { LinkedList spc = new LinkedList(); while (st.hasMoreTokens()) { String name = st.nextToken(); Species spe = (Species)speciesSet.get(name); if (spe == null) throw new InvalidConversionException("Unknown reactant in 'Goal Conversion' field of input file : " + name); setLimitingReactantID(spe.getID()); String conv = st.nextToken(); double conversion; try { if (conv.endsWith("%")) { conversion = Double.parseDouble(conv.substring(0,conv.length()-1))/100; } else { conversion = Double.parseDouble(conv); } conversionSet[49] = conversion; } catch (NumberFormatException e) { throw new NumberFormatException("wrong number format for conversion in initial condition file!"); } SpeciesConversion sc = new SpeciesConversion(spe, conversion); spc.add(sc); } tt = new ConversionTT(spc); } else if (type.startsWith("ReactionTime")) { double time = Double.parseDouble(st.nextToken()); String unit = ChemParser.removeBrace(st.nextToken()); ReactionTime rt = new ReactionTime(time, unit); tt = new ReactionTimeTT(rt); } else { throw new InvalidSymbolException("condition.txt: Unknown FinishController = " + type); } line = ChemParser.readMeaningfulLine(reader, true); st = new StringTokenizer(line, ":"); String temp = st.nextToken(); String tol = st.nextToken(); try { if (tol.endsWith("%")) { tolerance = Double.parseDouble(tol.substring(0,tol.length()-1))/100; } else { tolerance = Double.parseDouble(tol); } } catch (NumberFormatException e) { throw new NumberFormatException("wrong number format for conversion in initial condition file!"); } ValidityTester vt = null; if (reactionModelEnlarger instanceof RateBasedRME) vt = new RateBasedVT(tolerance); else if (reactionModelEnlarger instanceof RateBasedPDepRME) vt = new RateBasedPDepVT(tolerance); else throw new InvalidReactionModelEnlargerException(); finishController = new FinishController(tt, vt); } else throw new InvalidSymbolException("condition.txt: can't find FinishController!"); // read in dynamic simulator line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("DynamicSimulator")) { StringTokenizer st = new StringTokenizer(line,":"); String temp = st.nextToken(); String simulator = st.nextToken().trim(); //read in non-negative option if it exists: syntax would be something like this: "DynamicSimulator: DASSL: non-negative" if (st.hasMoreTokens()){ if (st.nextToken().trim().toLowerCase().equals("non-negative")){ if(simulator.toLowerCase().equals("dassl")) JDAS.nonnegative = true; else{ System.err.println("Non-negative option is currently only supported for DASSL. Switch to DASSL solver or remove non-negative option."); System.exit(0); } } } numConversions = 0;//5/6/08 gmagoon: moved declaration from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator() //int numConversions = 0; boolean autoflag = false;//5/2/08 gmagoon: updating the following if/else-if block to consider input where we want to check model validity within the ODE solver at each time step; this will be indicated by the use of a string beginning with "AUTO" after the "TimeStep" or "Conversions" line // read in time step line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("TimeStep:") && finishController.terminationTester instanceof ReactionTimeTT) { st = new StringTokenizer(line); temp = st.nextToken(); while (st.hasMoreTokens()) { temp = st.nextToken(); if (temp.startsWith("AUTO")){//note potential opportunity for making case insensitive by using: temp.toUpperCase().startsWith("AUTO") autoflag=true; } else if (!autoflag){//use "else if" to make sure additional numbers are not read in case numbers are erroneously used following AUTO; note that there could still be a problem if numbers come before "AUTO" double tStep = Double.parseDouble(temp); String unit = "sec"; setTimeStep(new ReactionTime(tStep, unit)); } } ((ReactionTimeTT)finishController.terminationTester).setTimeSteps(timeStep); } else if (line.startsWith("Conversions:") && finishController.terminationTester instanceof ConversionTT){ st = new StringTokenizer(line); temp = st.nextToken(); int i=0; SpeciesConversion sc = (SpeciesConversion)((ConversionTT)finishController.terminationTester).speciesGoalConversionSet.get(0); Species convSpecies = sc.species; Iterator iter = ((InitialStatus)(initialStatusList.get(0))).getSpeciesStatus();//10/23/07 gmagoon: changed to use first element of initialStatusList, as subsequent operations should not be affected by which one is chosen double initialConc = 0; while (iter.hasNext()){ SpeciesStatus sps = (SpeciesStatus)iter.next(); if (sps.species.equals(convSpecies)) initialConc = sps.concentration; } while (st.hasMoreTokens()){ temp=st.nextToken(); if (temp.startsWith("AUTO")){ autoflag=true; } else if (!autoflag){ double conv = Double.parseDouble(temp); conversionSet[i] = (1-conv) * initialConc; i++; } } conversionSet[i] = (1 - conversionSet[49])* initialConc; numConversions = i+1; } else throw new InvalidSymbolException("condition.txt: can't find time step for dynamic simulator!"); if (temp.startsWith("AUTOPRUNE")){//for the AUTOPRUNE case, read in additional lines for termTol and edgeTol line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("TerminationTolerance:")) { st = new StringTokenizer(line); temp = st.nextToken(); termTol = Double.parseDouble(st.nextToken()); } else { Logger.critical("Cannot find TerminationTolerance in condition.txt"); System.exit(0); } line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("PruningTolerance:")) { st = new StringTokenizer(line); temp = st.nextToken(); edgeTol = Double.parseDouble(st.nextToken()); } else { Logger.critical("Cannot find PruningTolerance in condition.txt"); System.exit(0); } line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("MinSpeciesForPruning:")) { st = new StringTokenizer(line); temp = st.nextToken(); minSpeciesForPruning = Integer.parseInt(st.nextToken()); } else { Logger.critical("Cannot find MinSpeciesForPruning in condition.txt"); System.exit(0); } line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("MaxEdgeSpeciesAfterPruning:")) { st = new StringTokenizer(line); temp = st.nextToken(); maxEdgeSpeciesAfterPruning = Integer.parseInt(st.nextToken()); } else { Logger.critical("Cannot find MaxEdgeSpeciesAfterPruning in condition.txt"); System.exit(0); } //print header for pruning log (based on restart format) BufferedWriter bw = null; try { File f = new File("Pruning/edgeReactions.txt"); bw = new BufferedWriter(new FileWriter("Pruning/edgeReactions.txt", true)); String EaUnits = ArrheniusKinetics.getEaUnits(); bw.write("UnitsOfEa: " + EaUnits); bw.newLine(); } catch (FileNotFoundException ex) { Logger.logStackTrace(ex); } catch (IOException ex) { Logger.logStackTrace(ex); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { Logger.logStackTrace(ex); } } } else if (temp.startsWith("AUTO")){//in the non-autoprune case (i.e. original AUTO functionality), we set the new parameters to values that should reproduce original functionality termTol = tolerance; edgeTol = 0; minSpeciesForPruning = 999999;//arbitrary high number (actually, the value here should not matter, since pruning should not be done) maxEdgeSpeciesAfterPruning = 999999; } // read in atol line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("Atol:")) { st = new StringTokenizer(line); temp = st.nextToken(); atol = Double.parseDouble(st.nextToken()); } else throw new InvalidSymbolException("condition.txt: can't find Atol for dynamic simulator!"); // read in rtol line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("Rtol:")) { st = new StringTokenizer(line); temp = st.nextToken(); String rel_tol = st.nextToken(); if (rel_tol.endsWith("%")) rtol = Double.parseDouble(rel_tol.substring(0,rel_tol.length()-1)); else rtol = Double.parseDouble(rel_tol); } else throw new InvalidSymbolException("condition.txt: can't find Rtol for dynamic simulator!"); if (simulator.equals("DASPK")) { paraInfor = 0;//svp // read in SA line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("Error bars")) {//svp st = new StringTokenizer(line,":"); temp = st.nextToken(); String sa = st.nextToken().trim(); if (sa.compareToIgnoreCase("on")==0) { paraInfor = 1; error = true; } else if (sa.compareToIgnoreCase("off")==0) { paraInfor = 0; error = false; } else throw new InvalidSymbolException("condition.txt: can't find error on/off information!"); } else throw new InvalidSymbolException("condition.txt: can't find SA information!"); line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("Display sensitivity coefficients")){//svp st = new StringTokenizer(line,":"); temp = st.nextToken(); String sa = st.nextToken().trim(); if (sa.compareToIgnoreCase("on")==0){ paraInfor = 1; sensitivity = true; } else if (sa.compareToIgnoreCase("off")==0){ if (paraInfor != 1){ paraInfor = 0; } sensitivity = false; } else throw new InvalidSymbolException("condition.txt: can't find SA on/off information!"); //10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList //6/25/08 gmagoon: changed loop to use i index, and updated DASPK constructor to pass i (mirroring changes to DASSL //6/25/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null? for (int i = 0;i < initialStatusList.size();i++) { dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i,finishController.getValidityTester(), autoflag, termTol, tolerance)); } } species = new LinkedList(); line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("Display sensitivity information") ){ line = ChemParser.readMeaningfulLine(reader, true); Logger.info(line); while (!line.equals("END")){ st = new StringTokenizer(line); String name = st.nextToken(); if (name.toUpperCase().equals("ALL")) ReactionSystem.printAllSens = true; //gmagoon 12/22/09: if the line contains the word "all", turn on the flag to print out sensitivity information for everything species.add(name); line = ChemParser.readMeaningfulLine(reader, true); } } } else if (simulator.equals("DASSL")) { //10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList // for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) { // dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)iter.next())); //11/1/07 gmagoon: changed loop to use i index, and updated DASSL constructor to pass i //5/5/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null? for (int i = 0;i < initialStatusList.size();i++) { dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i, finishController.getValidityTester(), autoflag, termTol, tolerance)); } } else if (simulator.equals("Chemkin")) { line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("ReactorType")) { st = new StringTokenizer(line, ":"); temp = st.nextToken(); String reactorType = st.nextToken().trim(); //10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) { //dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)iter.next())); dynamicSimulatorList.add(new Chemkin(rtol, atol, reactorType));//11/4/07 gmagoon: fixing apparent cut/paste error } } } else throw new InvalidSymbolException("condition.txt: Unknown DynamicSimulator = " + simulator); //10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList; note: although conversionSet should actually be different for each T,P condition, it will be modified in isTPCconsistent within ReactionSystem for (Iterator iter = dynamicSimulatorList.iterator(); iter.hasNext(); ) { double [] cs = conversionSet.clone();//11/1/07 gmagoon: trying to make sure multiple instances of conversionSet are used ((DynamicSimulator)(iter.next())).addConversion(cs, numConversions); } } else throw new InvalidSymbolException("condition.txt: can't find DynamicSimulator!"); // read in reaction model enlarger /* Read in the Primary Kinetic Library * The user can specify as many PKLs, * including none, as they like. */ line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("PrimaryKineticLibrary:")) { readAndMakePKL(reader); } else throw new InvalidSymbolException("condition.txt: can't find PrimaryKineticLibrary"); // Reaction Library line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("ReactionLibrary:")) { readAndMakeReactionLibrary(reader); } else throw new InvalidSymbolException("condition.txt: can't find ReactionLibrary"); /* * Added by MRH 12-Jun-2009 * * The SeedMechanism acts almost exactly as the old * PrimaryKineticLibrary did. Whatever is in the SeedMechanism * will be placed in the core at the beginning of the simulation. * The user can specify as many seed mechanisms as they like, with * the priority (in the case of duplicates) given to the first * instance. There is no on/off flag. */ line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("SeedMechanism:")) { line = ChemParser.readMeaningfulLine(reader, true); while (!line.equals("END")) { String[] tempString = line.split("Name: "); String name = tempString[tempString.length-1].trim(); line = ChemParser.readMeaningfulLine(reader, true); tempString = line.split("Location: "); String location = tempString[tempString.length-1].trim(); line = ChemParser.readMeaningfulLine(reader, true); tempString = line.split("GenerateReactions: "); String generateStr = tempString[tempString.length-1].trim(); boolean generate = true; if (generateStr.equalsIgnoreCase("yes") || generateStr.equalsIgnoreCase("on") || generateStr.equalsIgnoreCase("true")){ generate = true; Logger.info("Will generate cross-reactions between species in seed mechanism " + name); } else if(generateStr.equalsIgnoreCase("no") || generateStr.equalsIgnoreCase("off") || generateStr.equalsIgnoreCase("false")) { generate = false; Logger.info("Will NOT initially generate cross-reactions between species in seed mechanism "+ name); Logger.info("This may have unintended consequences"); } else { System.err.println("Input file invalid"); System.err.println("Please include a 'GenerateReactions: yes/no' line for seed mechanism "+name); System.exit(0); } String path = System.getProperty("jing.rxn.ReactionLibrary.pathName"); path += "/" + location; if (getSeedMechanism() == null) setSeedMechanism(new SeedMechanism(name, path, generate, false)); else getSeedMechanism().appendSeedMechanism(name, path, generate, false); line = ChemParser.readMeaningfulLine(reader, true); } if (getSeedMechanism() != null) Logger.info("Seed Mechanisms in use: " + getSeedMechanism().getName()); else setSeedMechanism(null); } else throw new InvalidSymbolException("Error reading condition.txt file: " + "Could not locate SeedMechanism field"); line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("ChemkinUnits")) { line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("Verbose:")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); String OnOff = st.nextToken().toLowerCase(); if (OnOff.equals("off")) { ArrheniusKinetics.setVerbose(false); } else if (OnOff.equals("on")) { ArrheniusKinetics.setVerbose(true); } line = ChemParser.readMeaningfulLine(reader, true); } /* * MRH 3MAR2010: * Adding user option regarding chemkin file * * New field: If user would like the empty SMILES string * printed with each species in the thermochemistry portion * of the generated chem.inp file */ if (line.toUpperCase().startsWith("SMILES")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // Should be "SMILES:" String OnOff = st.nextToken().toLowerCase(); if (OnOff.equals("off")) { Chemkin.setSMILES(false); } else if (OnOff.equals("on")) { Chemkin.setSMILES(true); /* * MRH 9MAR2010: * MRH decided not to generate an InChI for every new species * during an RMG simulation (especially since it is not used * for anything). Instead, they will only be generated in the * post-processing, if the user asked for InChIs. */ //Species.useInChI = true; } line = ChemParser.readMeaningfulLine(reader, true); } if (line.startsWith("A")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // Should be "A:" String units = st.nextToken(); if (units.equals("moles") || units.equals("molecules")) ArrheniusKinetics.setAUnits(units); else { System.err.println("Units for A were not recognized: " + units); System.exit(0); } } else throw new InvalidSymbolException("Error reading condition.txt file: " + "Could not locate Chemkin units A field."); line = ChemParser.readMeaningfulLine(reader, true); if (line.startsWith("Ea")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // Should be "Ea:" String units = st.nextToken(); if (units.equals("kcal/mol") || units.equals("cal/mol") || units.equals("kJ/mol") || units.equals("J/mol") || units.equals("Kelvins")) ArrheniusKinetics.setEaUnits(units); else { System.err.println("Units for Ea were not recognized: " + units); System.exit(0); } } else throw new InvalidSymbolException("Error reading condition.txt file: " + "Could not locate Chemkin units Ea field."); } else throw new InvalidSymbolException("Error reading condition.txt file: " + "Could not locate ChemkinUnits field."); in.close(); // LinkedList temperatureArray = new LinkedList(); // LinkedList pressureArray = new LinkedList(); // Iterator iterIS = initialStatusList.iterator(); // for (Iterator iter = tempList.iterator(); iter.hasNext(); ) { // TemperatureModel tm = (TemperatureModel)iter.next(); // for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){ // PressureModel pm = (PressureModel)iter2.next(); // InitialStatus is = (InitialStatus)iterIS.next(); // temperatureArray.add(tm.getTemperature(is.getTime())); // pressureArray.add(pm.getPressure(is.getTime())); // PDepNetwork.setTemperatureArray(temperatureArray); // PDepNetwork.setPressureArray(pressureArray); //10/4/07 gmagoon: moved to modelGeneration() //ReactionGenerator p_reactionGenerator = new TemplateReactionGenerator();//10/4/07 gmagoon: changed to p_reactionGenerator from reactionGenerator // setReactionGenerator(p_reactionGenerator);//10/4/07 gmagoon: added /* * MRH 12-Jun-2009 * A TemplateReactionGenerator now requires a Temperature be passed to it. * This allows RMG to determine the "best" kinetic parameters to use * in the mechanism generation. For now, I choose to pass the first * temperature in the list of temperatures. RMG only outputs one mechanism, * even for multiple temperature/pressure systems, so we can only have one * set of kinetics. */ Temperature t = new Temperature(300,"K"); for (Iterator iter = tempList.iterator(); iter.hasNext();) { TemperatureModel tm = (TemperatureModel)iter.next(); t = tm.getTemperature(new ReactionTime(0,"sec")); setTemp4BestKinetics(t); break; } setReactionGenerator(new TemplateReactionGenerator()); //11/4/07 gmagoon: moved from modelGeneration; mysteriously, moving this later moves "Father" lines up in output at runtime, immediately after condition file (as in original code); previously, these Father lines were just before "Can't read primary kinetic library files!" lrg = new LibraryReactionGenerator(ReactionLibrary);//10/10/07 gmagoon: moved from modelGeneration (sequence lrg increases species id, and the different sequence was causing problems as main species id was 6 instead of 1); //10/31/07 gmagoon: restored this line from 10/10/07 backup: somehow it got lost along the way; 11/5/07 gmagoon: changed to use "lrg =" instead of setLibraryReactionGenerator //10/24/07 gmagoon: updated to use multiple reactionSystem variables reactionSystemList = new LinkedList(); // LinkedList temperatureArray = new LinkedList();//10/30/07 gmagoon: added temperatureArray variable for passing to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg; Iterator iter3 = initialStatusList.iterator(); Iterator iter4 = dynamicSimulatorList.iterator(); int i = 0;//10/30/07 gmagoon: added for (Iterator iter = tempList.iterator(); iter.hasNext(); ) { TemperatureModel tm = (TemperatureModel)iter.next(); //InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: fixing apparent bug by moving these inside inner "for loop" //DynamicSimulator ds = (DynamicSimulator)iter4.next(); for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){ PressureModel pm = (PressureModel)iter2.next(); for (int numConcList=0; numConcList<initialStatusList.size()/tempList.size()/presList.size(); ++numConcList) { // InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: moved from outer "for loop"" InitialStatus is = (InitialStatus)initialStatusList.get(i); DynamicSimulator ds = (DynamicSimulator)iter4.next(); // temperatureArray.add(tm.getTemperature(is.getTime()));//10/30/07 gmagoon: added; //10/31/07 added .getTemperature(is.getTime()); 11/6/07 gmagoon: moved before initialization of lrg; //11/1/07 gmagoon: trying to make a deep copy of terminationTester when it is instance of ConversionTT // TerminationTester termTestCopy; // if (finishController.getTerminationTester() instanceof ConversionTT){ // ConversionTT termTest = (ConversionTT)finishController.getTerminationTester(); // LinkedList spcCopy = (LinkedList)(termTest.getSpeciesGoalConversionSetList().clone()); // termTestCopy = new ConversionTT(spcCopy); // else{ // termTestCopy = finishController.getTerminationTester(); FinishController fc = new FinishController(finishController.getTerminationTester(), finishController.getValidityTester());//10/31/07 gmagoon: changed to create new finishController instance in each case (apparently, the finish controller becomes associated with reactionSystem in setFinishController within ReactionSystem); alteratively, could use clone, but might need to change FinishController to be "cloneable" // FinishController fc = new FinishController(termTestCopy, finishController.getValidityTester()); i++;//10/30/07 gmagoon: added Logger.info("Creating reaction system "+i); reactionSystemList.add(new ReactionSystem(tm, pm, reactionModelEnlarger, fc, ds, getPrimaryKineticLibrary(), getReactionGenerator(), getSpeciesSeed(), is, getReactionModel(),lrg, i, equationOfState)); Logger.info((initialStatusList.get(i-1)).toString() + "\n"); } } } // PDepNetwork.setTemperatureArray(temperatureArray);//10/30/07 gmagoon: passing temperatureArray to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg; } catch (IOException e) { System.err.println("Error reading reaction system initialization file."); throw new IOException("Input file error: " + e.getMessage()); } Logger.info(""); } public void setReactionModel(ReactionModel p_ReactionModel) { reactionModel = p_ReactionModel; } public void modelGeneration() { //long begin_t = System.currentTimeMillis(); try{ ChemGraph.readForbiddenStructure(); setSpeciesSeed(new LinkedHashSet());//10/4/07 gmagoon moved from initializeCoreEdgeReactionModel // setReactionGenerator(new TemplateReactionGenerator());//10/4/07 gmagoon: moved inside initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07 (although I have not investigated this change in detail); //11/4/07 gmagoon: moved inside initializeReactionSystems // setLibraryReactionGenerator(new LibraryReactionGenerator());//10/10/07 gmagoon: moved after initializeReactionSystem // initializeCoreEdgeReactionModel();//10/4/07 gmagoon moved from below to run initializeCoreEdgeReactionModel before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07 initializeReactionSystems(); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(0); } catch (InvalidSymbolException e) { System.err.println(e.getMessage()); System.exit(0); } //10/31/07 gmagoon: initialize validList (to false) before initializeCoreEdgeReactionModel is called validList = new LinkedList(); for (Integer i = 0; i<reactionSystemList.size();i++) { validList.add(false); } initializeCoreEdgeReactionModel();//10/4/07 gmagoon: moved before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07 //10/24/07 gmagoon: changed to use reactionSystemList // LinkedList initList = new LinkedList();//10/25/07 gmagoon: moved these variables to apply to entire class // LinkedList beginList = new LinkedList(); // LinkedList endList = new LinkedList(); // LinkedList lastTList = new LinkedList(); // LinkedList currentTList = new LinkedList(); // LinkedList lastPList = new LinkedList(); // LinkedList currentPList = new LinkedList(); // LinkedList conditionChangedList = new LinkedList(); // LinkedList reactionChangedList = new LinkedList(); //5/6/08 gmagoon: determine whether there are intermediate time/conversion steps, type of termination tester is based on characteristics of 1st reaction system (it is assumed that they are all identical in terms of type of termination tester) boolean intermediateSteps = true; ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0); if (rs0.finishController.terminationTester instanceof ReactionTimeTT){ if (timeStep == null){ intermediateSteps = false; } } else if (numConversions==1){ //if we get to this block, we presumably have a conversion terminationTester; this required moving numConversions to be attribute...alternative to using numConversions is to access one of the DynamicSimulators and determine conversion length intermediateSteps=false; } //10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) { ReactionSystem rs = (ReactionSystem)iter.next(); if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases if (!readrestart) rs.initializePDepNetwork(); } ReactionTime init = rs.getInitialReactionTime(); initList.add(init); ReactionTime begin = init; beginList.add(begin); ReactionTime end; if (rs.finishController.terminationTester instanceof ReactionTimeTT){ //5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified if (!(timeStep==null)){ end = (ReactionTime)timeStep.get(0); } else{ end= ((ReactionTimeTT)rs.finishController.terminationTester).finalTime; } //end = (ReactionTime)timeStep.get(0); endList.add(end); } else{ end = new ReactionTime(1e6,"sec"); endList.add(end); } // int iterationNumber = 1; lastTList.add(rs.getTemperature(init)); currentTList.add(rs.getTemperature(init)); lastPList.add(rs.getPressure(init)); currentPList.add(rs.getPressure(init)); conditionChangedList.add(false); reactionChangedList.add(false);//10/31/07 gmagoon: added //Chemkin.writeChemkinInputFile(reactionSystem.getReactionModel(),reactionSystem.getPresentStatus()); } int iterationNumber = 1; LinkedList terminatedList = new LinkedList();//10/24/07 gmagoon: this may not be necessary, as if one reactionSystem is terminated, I think all should be terminated //validList = new LinkedList();//10/31/07 gmagoon: moved before initializeCoreEdgeReactionModel //10/24/07 gmagoon: initialize allTerminated and allValid to true; these variables keep track of whether all the reactionSystem variables satisfy termination and validity, respectively boolean allTerminated = true; boolean allValid = true; // IF RESTART IS TURNED ON // Update the systemSnapshot for each ReactionSystem in the reactionSystemList if (readrestart) { for (Integer i=0; i<reactionSystemList.size(); i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); InitialStatus is = rs.getInitialStatus(); putRestartSpeciesInInitialStatus(is,i); rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature()); } } printModelSize(); Logger.info(String.format("Running time: %.3f min", + (System.currentTimeMillis()-Global.tAtInitialization)/1000./60.)); printMemoryUsed(); Logger.flush(); //10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); ReactionTime begin = (ReactionTime)beginList.get(i); ReactionTime end = (ReactionTime)endList.get(i); LinkedHashSet seedmechnonpdeprxns = extractSeedMechRxnsIfTheyExist(); endList.set(i,rs.solveReactionSystem(begin, end, true, true, true, iterationNumber-1,seedmechnonpdeprxns)); Chemkin.writeChemkinInputFile(rs, seedmechnonpdeprxns); boolean terminated = rs.isReactionTerminated(); terminatedList.add(terminated); if(!terminated) allTerminated = false; boolean valid = rs.isModelValid(); //validList.add(valid); validList.set(i, valid);//10/31/07 gmagoon: validList initialization moved before initializeCoreEdgeReactionModel if(!valid) allValid = false; reactionChangedList.set(i,false); } //9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey if (ChemGraph.useQM){ writeInChIs(getReactionModel()); } writeDictionary(getReactionModel()); //System.exit(0); StringBuilder print_info = Global.diagnosticInfo; print_info.append("\nMolecule \t Flux\t\tTime\t \t\t \t Core \t \t Edge \t \t memory\n"); print_info.append(" \t moleular \t characteristic \t findspecies \t moveUnreactedToReacted \t enlarger \t restart1 \t totalEnlarger \t resetSystem \t readSolverFile\t writeSolverFile \t justSolver \t SolverIterations \t solverSpeciesStatus \t Totalsolver \t gc \t restart+diagnosis \t chemkin thermo \t chemkin reactions \t validitytester \t Species \t Reactions\t Species\t Reactions \t memory used \t allSpecies \t TotalTime \t findRateConstant\t identifyReactedSites \t reactChemGraph \t makespecies\t CheckReverseReaction \t makeTemplateReaction \t getReactionfromStruc \t genReverseFromReac"); print_info.append("\t\t\t\t\t\t\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t"+Global.makeSpecies+"\n"); double solverMin = 0; double vTester = 0; /*if (!restart){ writeRestartFile(); writeCoreReactions(); writeAllReactions(); }*/ //System.exit(0); SpeciesDictionary dictionary = SpeciesDictionary.getInstance(); Logger.debug("Species dictionary size: "+dictionary.size()); //10/24/07: changed to use allTerminated and allValid // step 2: iteratively grow reaction system while (!allTerminated || !allValid) { while (!allValid) { //writeCoreSpecies(); double pt = System.currentTimeMillis(); // Grab all species from primary kinetics / reaction libraries // WE CANNOT PRUNE THESE SPECIES HashMap unprunableSpecies = new HashMap(); if (getPrimaryKineticLibrary() != null) { unprunableSpecies.putAll(getPrimaryKineticLibrary().speciesSet); } if (getReactionLibrary() != null) { unprunableSpecies.putAll(getReactionLibrary().getDictionary()); } //prune the reaction model (this will only do something in the AUTO case) pruneReactionModel(unprunableSpecies); garbageCollect(); //System.out.println("After pruning:"); //printModelSize(); // ENLARGE THE MODEL!!! (this is where the good stuff happens) enlargeReactionModel(); double totalEnlarger = (System.currentTimeMillis() - pt)/1000/60; //PDepNetwork.completeNetwork(reactionSystem.reactionModel.getSpeciesSet()); //10/24/07 gmagoon: changed to use reactionSystemList if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) { ReactionSystem rs = (ReactionSystem)iter.next(); rs.initializePDepNetwork(); } //reactionSystem.initializePDepNetwork(); } printModelSize(); Logger.info(String.format("Running time: %.3f min", + (System.currentTimeMillis()-Global.tAtInitialization)/1000./60.)); printMemoryUsed(); Logger.flush(); pt = System.currentTimeMillis(); //10/24/07 gmagoon: changed to use reactionSystemList for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) { ReactionSystem rs = (ReactionSystem)iter.next(); rs.resetSystemSnapshot(); } //reactionSystem.resetSystemSnapshot(); double resetSystem = (System.currentTimeMillis() - pt)/1000/60; //10/24/07 gmagoon: changed to use reactionSystemList for (Integer i = 0; i<reactionSystemList.size();i++) { //reactionChanged = true; ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); reactionChangedList.set(i,true); // begin = init; beginList.set(i, (ReactionTime)initList.get(i)); if (rs.finishController.terminationTester instanceof ReactionTimeTT){ //5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified if (!(timeStep==null)){ endList.set(i,(ReactionTime)timeStep.get(0)); } else{ endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime); } // endList.set(i, (ReactionTime)timeStep.get(0)); //end = (ReactionTime)timeStep.get(0); } else endList.set(i, new ReactionTime(1e6,"sec")); //end = new ReactionTime(1e6,"sec"); // iterationNumber = 1;//10/24/07 gmagoon: moved outside of loop currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i))); currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i))); conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i)))); //currentT = reactionSystem.getTemperature(begin); //currentP = reactionSystem.getPressure(begin); //conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP)); } iterationNumber = 1; double startTime = System.currentTimeMillis(); //10/24/07 gmagoon: changed to use reactionSystemList for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); boolean reactionChanged = (Boolean)reactionChangedList.get(i); boolean conditionChanged = (Boolean)conditionChangedList.get(i); ReactionTime begin = (ReactionTime)beginList.get(i); ReactionTime end = (ReactionTime)endList.get(i); LinkedHashSet seedmechnonpdeprxns = extractSeedMechRxnsIfTheyExist(); endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1,seedmechnonpdeprxns)); //end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1); } solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60; startTime = System.currentTimeMillis(); for (Integer i = 0; i<reactionSystemList.size();i++) { // we over-write the chemkin file each time, so only the LAST reaction system is saved // i.e. if you are using RATE for pdep, only the LAST pressure is used. ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); LinkedHashSet seedmechnonpdeprxns = extractSeedMechRxnsIfTheyExist(); Chemkin.writeChemkinInputFile(rs,seedmechnonpdeprxns); } //9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey if (ChemGraph.useQM){ writeInChIs(getReactionModel()); } writeDictionary(getReactionModel()); double chemkint = (System.currentTimeMillis()-startTime)/1000/60; if (writerestart) { /* * Rename current restart files: * In the event RMG fails while writing the restart files, * user won't lose any information */ String[] restartFiles = {"Restart/coreReactions.txt", "Restart/coreSpecies.txt", "Restart/edgeReactions.txt", "Restart/edgeSpecies.txt", "Restart/pdepnetworks.txt", "Restart/pdepreactions.txt"}; writeBackupRestartFiles(restartFiles); writeCoreSpecies(); writeCoreReactions(); writeEdgeSpecies(); writeEdgeReactions(); if (PDepNetwork.generateNetworks == true) writePDepNetworks(); /* * Remove backup restart files from Restart folder */ removeBackupRestartFiles(restartFiles); } //10/24/07 gmagoon: changed to use reactionSystemList Logger.info(""); for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); Logger.info(String.format("For reaction system: %d out of %d", i+1, reactionSystemList.size())); Logger.info(String.format("At this time: %10.4e s", ((ReactionTime)endList.get(i)).getTime())); Species spe = SpeciesDictionary.getSpeciesFromID(getLimitingReactantID()); double conv = rs.getPresentConversion(spe); Logger.info(String.format("Conversion of %s is: %-10.4g", spe.getFullName(), conv)); } Logger.info(""); startTime = System.currentTimeMillis(); double mU = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); Logger.info(""); double gc = (System.currentTimeMillis()-startTime)/1000./60.; startTime = System.currentTimeMillis(); //10/24/07 gmagoon: updating to use reactionSystemList allValid = true; for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); boolean valid = rs.isModelValid(); if(!valid) allValid = false; validList.set(i,valid); //valid = reactionSystem.isModelValid(); } vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60; startTime = System.currentTimeMillis(); writeDiagnosticInfo(); writeEnlargerInfo(); double restart2 = (System.currentTimeMillis()-startTime)/1000/60; int allSpecies, allReactions; allSpecies = SpeciesDictionary.getInstance().size(); print_info.append(totalEnlarger + "\t" + resetSystem + "\t" + Global.readSolverFile + "\t" + Global.writeSolverFile + "\t" + Global.solvertime + "\t" + Global.solverIterations + "\t" + Global.speciesStatusGenerator + "\t" + solverMin + "\t" + gc + "\t" + restart2 + "\t" + Global.chemkinThermo + '\t' + Global.chemkinReaction + "\t" + vTester + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t" + mU + "\t" + allSpecies + "\t" + (System.currentTimeMillis()-Global.tAtInitialization)/1000/60 + "\t"+ String.valueOf(Global.RT_findRateConstant)+"\t"+Global.RT_identifyReactedSites+"\t"+Global.RT_reactChemGraph+"\t"+Global.makeSpecies+"\t"+Global.checkReactionReverse+"\t"+Global.makeTR+ "\t" + Global.getReacFromStruc + "\t" + Global.generateReverse+"\n"); } //5/6/08 gmagoon: in order to handle cases where no intermediate time/conversion steps are used, only evaluate the next block of code when there are intermediate time/conversion steps double startTime = System.currentTimeMillis(); if(intermediateSteps){ for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); reactionChangedList.set(i, false); //reactionChanged = false; Temperature currentT = (Temperature)currentTList.get(i); Pressure currentP = (Pressure)currentPList.get(i); lastTList.set(i,(Temperature)currentT.clone()) ; lastPList.set(i,(Pressure)currentP.clone()); //lastT = (Temperature)currentT.clone(); //lastP = (Pressure)currentP.clone(); currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i))); currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i))); conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i)))); //currentP = reactionSystem.getPressure(begin); //conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP)); beginList.set(i,((SystemSnapshot)(rs.getSystemSnapshotEnd().next())).time); // begin=((SystemSnapshot)(reactionSystem.getSystemSnapshotEnd().next())).time; if (rs.finishController.terminationTester instanceof ReactionTimeTT){ if (iterationNumber < timeStep.size()){ endList.set(i,(ReactionTime)timeStep.get(iterationNumber)); //end = (ReactionTime)timeStep.get(iterationNumber); } else endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime); //end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime; } else endList.set(i,new ReactionTime(1e6,"sec")); //end = new ReactionTime(1e6,"sec"); } iterationNumber++; startTime = System.currentTimeMillis();//5/6/08 gmagoon: moved declaration outside of if statement so it can be accessed in subsequent vTester line; previous steps are probably so fast that I could eliminate this line without much effect on normal operation with intermediate steps //double startTime = System.currentTimeMillis(); //10/24/07 gmagoon: changed to use reactionSystemList for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); boolean reactionChanged = (Boolean)reactionChangedList.get(i); boolean conditionChanged = (Boolean)conditionChangedList.get(i); ReactionTime begin = (ReactionTime)beginList.get(i); ReactionTime end = (ReactionTime)endList.get(i); LinkedHashSet seedmechnonpdeprxns = extractSeedMechRxnsIfTheyExist(); endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1,seedmechnonpdeprxns)); // end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1); } solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60; startTime = System.currentTimeMillis(); //5/6/08 gmagoon: changed to separate validity and termination testing, and termination testing is done last...termination testing should be done even if there are no intermediate conversions; however, validity is guaranteed if there are no intermediate conversions based on previous conditional if statement allValid = true; for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); boolean valid = rs.isModelValid(); validList.set(i,valid); if(!valid) allValid = false; } }//5/6/08 gmagoon: end of block for intermediateSteps allTerminated = true; for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); boolean terminated = rs.isReactionTerminated(); terminatedList.set(i,terminated); if(!terminated){ allTerminated = false; Logger.error("Reaction System "+(i+1)+" has not reached its termination criterion"); if (rs.isModelValid()&& runKillableToPreventInfiniteLoop(intermediateSteps, iterationNumber)) { Logger.info("although it seems to be valid (complete), so it was not interrupted for being invalid."); Logger.info("This probably means there was an error with the ODE solver, and we risk entering an endless loop."); Logger.info("Stopping."); throw new Error(); } } } //10/24/07 gmagoon: changed to use reactionSystemList, allValid if (allValid) { Logger.info("Model generation completed!"); printModelSize(); } vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60;//5/6/08 gmagoon: for case where intermediateSteps = false, this will use startTime declared just before intermediateSteps loop, and will only include termination testing, but no validity testing } //System.out.println("Performing model reduction"); if (paraInfor != 0){ Logger.info("Model Generation performed. Now generating sensitivity data."); //10/24/07 gmagoon: updated to use reactionSystemList LinkedList dynamicSimulator2List = new LinkedList(); for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); //6/25/08 gmagoon: updated to pass index i //6/25/08 gmagoon: updated to pass (dummy) finishController and autoflag (set to false here); dynamicSimulator2List.add(new JDASPK(rtol, atol, paraInfor, (InitialStatus)initialStatusList.get(i),i)); //DynamicSimulator dynamicSimulator2 = new JDASPK(rtol, atol, paraInfor, initialStatus); ((DynamicSimulator)dynamicSimulator2List.get(i)).addConversion(((JDASPK)rs.dynamicSimulator).conversionSet, ((JDASPK)rs.dynamicSimulator).conversionSet.length); //dynamicSimulator2.addConversion(((JDASPK)reactionSystem.dynamicSimulator).conversionSet, ((JDASPK)reactionSystem.dynamicSimulator).conversionSet.length); rs.setDynamicSimulator((DynamicSimulator)dynamicSimulator2List.get(i)); //reactionSystem.setDynamicSimulator(dynamicSimulator2); int numSteps = rs.systemSnapshot.size() -1; rs.resetSystemSnapshot(); beginList.set(i, (ReactionTime)initList.get(i)); //begin = init; if (rs.finishController.terminationTester instanceof ReactionTimeTT){ endList.set(i,((ReactionTimeTT)rs.finishController.terminationTester).finalTime); //end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime; } else{ ReactionTime end = (ReactionTime)endList.get(i); endList.set(i, end.add(end)); //end = end.add(end); } terminatedList.set(i, false); //terminated = false; ReactionTime begin = (ReactionTime)beginList.get(i); ReactionTime end = (ReactionTime)endList.get(i); LinkedHashSet seedmechnonpdeprxns = extractSeedMechRxnsIfTheyExist(); rs.solveReactionSystemwithSEN(begin, end, true, false, false, seedmechnonpdeprxns); //reactionSystem.solveReactionSystemwithSEN(begin, end, true, false, false); } } // All of the reaction systems are the same, so just write the chemkin // file for the first reaction system ReactionSystem rs = (ReactionSystem)reactionSystemList.get(0); LinkedHashSet seedmechnonpdeprxns = extractSeedMechRxnsIfTheyExist(); Chemkin.writeChemkinInputFile(getReactionModel(),rs.getPresentStatus(),seedmechnonpdeprxns); //9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey if (ChemGraph.useQM){ writeInChIs(getReactionModel()); } writeDictionary(getReactionModel()); } //9/1/09 gmagoon: this function writes a "dictionary" with Chemkin name, RMG name, (modified) InChI, and InChIKey //this is based off of writeChemkinFile in ChemkinInputFile.java private void writeInChIs(ReactionModel p_reactionModel) { StringBuilder result=new StringBuilder(); for (Iterator iter = ((CoreEdgeReactionModel)p_reactionModel).core.getSpecies(); iter.hasNext(); ) { Species species = (Species) iter.next(); result.append(species.getChemkinName() + "\t"+species.getName() + "\t" + species.getChemGraph().getModifiedInChIAnew() + "\t" + species.getChemGraph().getModifiedInChIKeyAnew()+ "\n"); } String file = "inchiDictionary.txt"; try { FileWriter fw = new FileWriter(file); fw.write(result.toString()); fw.close(); } catch (Exception e) { Logger.critical("Error in writing InChI file inchiDictionary.txt!"); Logger.critical(e.getMessage()); System.exit(0); } } //9/14/09 gmagoon: function to write dictionary, based on code copied from RMG.java private void writeDictionary(ReactionModel rm){ CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm; //Write core species to RMG_Dictionary.txt String coreSpecies =""; Iterator iter = cerm.getSpecies(); if (Species.useInChI) { while (iter.hasNext()){ int i=1; Species spe = (Species) iter.next(); coreSpecies = coreSpecies + spe.getChemkinName() + " " + spe.getInChI() + "\n"+spe.getChemGraph().toString(i)+"\n\n"; } } else { while (iter.hasNext()){ int i=1; Species spe = (Species) iter.next(); coreSpecies = coreSpecies + spe.getChemkinName() + "\n"+spe.getChemGraph().toString(i)+"\n\n"; } } try{ File rmgDictionary = new File("RMG_Dictionary.txt"); FileWriter fw = new FileWriter(rmgDictionary); fw.write(coreSpecies); fw.close(); } catch (IOException e) { Logger.critical("Could not write RMG_Dictionary.txt"); System.exit(0); } // If we have solvation on, then every time we write the dictionary, also write the solvation properties if (Species.useSolvation) { writeSolvationProperties(rm); } } private void writeSolvationProperties(ReactionModel rm){ //Write core species to RMG_Solvation_Properties.txt CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm; StringBuilder result = new StringBuilder(); result.append("ChemkinName\tChemicalFormula\tMolecularWeight\tRadius\tDiffusivity\tAbrahamS\tAbrahamB\tAbrahamE\tAbrahamL\tAbrahamA\tAbrahamV\tChemkinName\n\n"); Iterator iter = cerm.getSpecies(); while (iter.hasNext()){ Species spe = (Species)iter.next(); result.append(spe.getChemkinName() + "\t"); result.append(spe.getChemGraph().getChemicalFormula()+ "\t"); result.append(spe.getMolecularWeight() + "\t"); result.append(spe.getChemGraph().getRadius()+ "\t"); result.append(spe.getChemGraph().getDiffusivity()+ "\t"); result.append(spe.getChemGraph().getAbramData().toString()+ "\t"); result.append(spe.getChemkinName() + "\n"); } try{ File rmgSolvationProperties = new File("RMG_Solvation_Properties.txt"); FileWriter fw = new FileWriter(rmgSolvationProperties); fw.write(result.toString() ); fw.close(); } catch (IOException e) { Logger.critical("Could not write RMG_Solvation_Properties.txt"); System.exit(0); } } /* * MRH 23MAR2010: * Commenting out deprecated parseRestartFiles method */ // private void parseRestartFiles() { // parseAllSpecies(); // parseCoreSpecies(); // parseEdgeSpecies(); // parseAllReactions(); // parseCoreReactions(); /* * MRH 23MAR2010: * Commenting out deprecated parseEdgeReactions method */ // private void parseEdgeReactions() { // SpeciesDictionary dictionary = SpeciesDictionary.getInstance(); // //HasMap speciesMap = dictionary.dictionary; // try{ // File coreReactions = new File("Restart/edgeReactions.txt"); // FileReader fr = new FileReader(coreReactions); // BufferedReader reader = new BufferedReader(fr); // String line = ChemParser.readMeaningfulLine(reader); // boolean found = false; // LinkedHashSet reactionSet = new LinkedHashSet(); // while (line != null){ // Reaction reaction = ChemParser.parseEdgeArrheniusReaction(dictionary,line,1,1); // boolean added = reactionSet.add(reaction); // if (!added){ // if (reaction.hasResonanceIsomerAsReactant()){ // //Structure reactionStructure = reaction.getStructure(); // found = getResonanceStructure(reaction,"reactants", reactionSet); // if (reaction.hasResonanceIsomerAsProduct() && !found){ // //Structure reactionStructure = reaction.getStructure(); // found = getResonanceStructure(reaction,"products", reactionSet); // if (!found){ // System.out.println("Cannot add reaction "+line+" to the Reaction Edge. All resonance isomers have already been added"); // System.exit(0); // else found = false; // //Reaction reverse = reaction.getReverseReaction(); // //if (reverse != null) reactionSet.add(reverse); // line = ChemParser.readMeaningfulLine(reader); // ((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet); // catch (IOException e){ // System.out.println("Could not read the corespecies restart file"); // System.exit(0); /* * MRH 23MAR2010: * Commenting out deprecated parseAllSpecies method */ // public void parseCoreReactions() { // SpeciesDictionary dictionary = SpeciesDictionary.getInstance(); // int i=1; // //HasMap speciesMap = dictionary.dictionary; // try{ // File coreReactions = new File("Restart/coreReactions.txt"); // FileReader fr = new FileReader(coreReactions); // BufferedReader reader = new BufferedReader(fr); // String line = ChemParser.readMeaningfulLine(reader); // boolean found = false; // LinkedHashSet reactionSet = new LinkedHashSet(); // while (line != null){ // Reaction reaction = ChemParser.parseCoreArrheniusReaction(dictionary,line,1,1);//,((CoreEdgeReactionModel)reactionSystem.reactionModel)); // boolean added = reactionSet.add(reaction); // if (!added){ // if (reaction.hasResonanceIsomerAsReactant()){ // //Structure reactionStructure = reaction.getStructure(); // found = getResonanceStructure(reaction,"reactants", reactionSet); // if (reaction.hasResonanceIsomerAsProduct() && !found){ // //Structure reactionStructure = reaction.getStructure(); // found = getResonanceStructure(reaction,"products", reactionSet); // if (!found){ // System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added"); // //System.exit(0); // else found = false; // Reaction reverse = reaction.getReverseReaction(); // if (reverse != null) { // reactionSet.add(reverse); // //System.out.println(2 + "\t " + line); // //else System.out.println(1 + "\t" + line); // line = ChemParser.readMeaningfulLine(reader); // i=i+1; // ((CoreEdgeReactionModel)getReactionModel()).addReactedReactionSet(reactionSet); // catch (IOException e){ // System.out.println("Could not read the coreReactions restart file"); // System.exit(0); /* * MRH 23MAR2010: * Commenting out deprecated parseAllSpecies method */ // private void parseAllReactions() { // SpeciesDictionary dictionary = SpeciesDictionary.getInstance(); // int i=1; // //HasMap speciesMap = dictionary.dictionary; // try{ // File allReactions = new File("Restart/allReactions.txt"); // FileReader fr = new FileReader(allReactions); // BufferedReader reader = new BufferedReader(fr); // String line = ChemParser.readMeaningfulLine(reader); // boolean found = false; // LinkedHashSet reactionSet = new LinkedHashSet(); // OuterLoop: // while (line != null){ // Reaction reaction = ChemParser.parseArrheniusReaction(dictionary,line,1,1,((CoreEdgeReactionModel)getReactionModel())); // if (((CoreEdgeReactionModel)getReactionModel()).categorizeReaction(reaction)==-1){ // boolean added = reactionSet.add(reaction); // if (!added){ // found = false; // if (reaction.hasResonanceIsomerAsReactant()){ // //Structure reactionStructure = reaction.getStructure(); // found = getResonanceStructure(reaction,"reactants", reactionSet); // if (reaction.hasResonanceIsomerAsProduct() && !found){ // //Structure reactionStructure = reaction.getStructure(); // found = getResonanceStructure(reaction,"products", reactionSet); // if (!found){ // Iterator iter = reactionSet.iterator(); // while (iter.hasNext()){ // Reaction reacTemp = (Reaction)iter.next(); // if (reacTemp.equals(reaction)){ // reactionSet.remove(reacTemp); // reactionSet.add(reaction); // break; // //System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added"); // //System.exit(0); // //else found = false; // /*Reaction reverse = reaction.getReverseReaction(); // if (reverse != null && ((CoreEdgeReactionModel)reactionSystem.reactionModel).isReactedReaction(reaction)) { // reactionSet.add(reverse); // //System.out.println(2 + "\t " + line); // }*/ // //else System.out.println(1 + "\t" + line); // i=i+1; // line = ChemParser.readMeaningfulLine(reader); // ((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet); // catch (IOException e){ // System.out.println("Could not read the corespecies restart file"); // System.exit(0); private boolean getResonanceStructure(Reaction p_Reaction, String rOrP, LinkedHashSet reactionSet) { Structure reactionStructure = p_Reaction.getStructure(); //Structure tempreactionStructure = new Structure(reactionStructure.getReactantList(),reactionStructure.getProductList()); boolean found = false; if (rOrP.equals("reactants")){ Iterator originalreactants = reactionStructure.getReactants(); HashSet tempHashSet = new HashSet(); while(originalreactants.hasNext()){ tempHashSet.add(originalreactants.next()); } Iterator reactants = tempHashSet.iterator(); while(reactants.hasNext() && !found){ ChemGraph reactant = (ChemGraph)reactants.next(); if (reactant.getSpecies().hasResonanceIsomers()){ Iterator chemGraphIterator = reactant.getSpecies().getResonanceIsomers(); ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next(); while(chemGraphIterator.hasNext() && !found){ newChemGraph = (ChemGraph)chemGraphIterator.next(); reactionStructure.removeReactants(reactant); reactionStructure.addReactants(newChemGraph); reactant = newChemGraph; if (reactionSet.add(p_Reaction)){ found = true; } } } } } else{ Iterator originalproducts = reactionStructure.getProducts(); HashSet tempHashSet = new HashSet(); while(originalproducts.hasNext()){ tempHashSet.add(originalproducts.next()); } Iterator products = tempHashSet.iterator(); while(products.hasNext() && !found){ ChemGraph product = (ChemGraph)products.next(); if (product.getSpecies().hasResonanceIsomers()){ Iterator chemGraphIterator = product.getSpecies().getResonanceIsomers(); ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next(); while(chemGraphIterator.hasNext() && !found){ newChemGraph = (ChemGraph)chemGraphIterator.next(); reactionStructure.removeProducts(product); reactionStructure.addProducts(newChemGraph); product = newChemGraph; if (reactionSet.add(p_Reaction)){ found = true; } } } } } return found; } public void parseCoreSpecies() { // String restartFileContent =""; //int speciesCount = 0; //boolean added; SpeciesDictionary dictionary = SpeciesDictionary.getInstance(); try{ File coreSpecies = new File ("Restart/coreSpecies.txt"); FileReader fr = new FileReader(coreSpecies); BufferedReader reader = new BufferedReader(fr); String line = ChemParser.readMeaningfulLine(reader, true); //HashSet speciesSet = new HashSet(); // if (reactionSystem == null){//10/24/07 gmagoon: commenting out since contents of if was already commented out anyway // //ReactionSystem reactionSystem = new ReactionSystem(); setReactionModel(new CoreEdgeReactionModel());//10/4/07 gmagoon:changed to setReactionModel while (line!=null) { StringTokenizer st = new StringTokenizer(line); String index = st.nextToken(); int ID = Integer.parseInt(index); Species spe = dictionary.getSpeciesFromID(ID); if (spe == null) Logger.warning("There was no species with ID "+ID +" in the species dictionary"); ((CoreEdgeReactionModel)getReactionModel()).addReactedSpecies(spe); line = ChemParser.readMeaningfulLine(reader, true); } } catch (IOException e){ Logger.critical("Could not read the corespecies restart file"); System.exit(0); } } public static void garbageCollect(){ System.gc(); } public static void printMemoryUsed(){ garbageCollect(); Runtime rT = Runtime.getRuntime(); double uM, tM, fM; tM = rT.totalMemory() / 1.0e6; fM = rT.freeMemory() / 1.0e6; uM = tM - fM; Logger.debug("After garbage collection:"); Logger.info(String.format("Memory used: %.2f MB / %.2f MB (%.2f%%)", uM, tM, uM / tM * 100.)); } /* * MRH 23MAR2010: * Commenting out deprecated parseAllSpecies method */ // public LinkedHashSet parseAllSpecies() { // // String restartFileContent =""; // int speciesCount = 0; // LinkedHashSet speciesSet = new LinkedHashSet(); // boolean added; // try{ // long initialTime = System.currentTimeMillis(); // File coreSpecies = new File ("allSpecies.txt"); // BufferedReader reader = new BufferedReader(new FileReader(coreSpecies)); // String line = ChemParser.readMeaningfulLine(reader); // int i=0; // while (line!=null) { // StringTokenizer st = new StringTokenizer(line); // String index = st.nextToken(); // String name = null; // if (!index.startsWith("(")) name = index; // else name = st.nextToken().trim(); // int ID = getID(name); // name = getName(name); // Graph g = ChemParser.readChemGraph(reader); // ChemGraph cg = null; // try { // cg = ChemGraph.make(g); // catch (ForbiddenStructureException e) { // System.out.println("Forbidden Structure:\n" + e.getMessage()); // System.exit(0); // Species species; // if (ID == 0) // species = Species.make(name,cg); // else // species = Species.make(name,cg,ID); // speciesSet.add(species); // double flux = 0; // int species_type = 1; // line = ChemParser.readMeaningfulLine(reader); // System.out.println(line); // catch (IOException e){ // System.out.println("Could not read the allSpecies restart file"); // System.exit(0); // return speciesSet; private String getName(String name) { //int id; String number = ""; int index=0; if (!name.endsWith(")")) return name; else { char [] nameChars = name.toCharArray(); String temp = String.copyValueOf(nameChars); int i=name.length()-2; //char test = "("; while (i>0){ if (name.charAt(i)== '(') { index=i; i=0; } else i = i-1; } } number = name.substring(0,index); return number; } private int getID(String name) { int id; String number = ""; if (!name.endsWith(")")) return 0; else { char [] nameChars = name.toCharArray(); int i=name.length()-2; //char test = "("; while (i>0){ if (name.charAt(i)== '(') i=0; else{ number = name.charAt(i)+number; i = i-1; } } } id = Integer.parseInt(number); return id; } /* * MRH 23MAR2010: * Commenting out deprecated parseAllSpecies method */ // private void parseEdgeSpecies() { // // String restartFileContent =""; // SpeciesDictionary dictionary = SpeciesDictionary.getInstance(); // try{ // File edgeSpecies = new File ("Restart/edgeSpecies.txt"); // FileReader fr = new FileReader(edgeSpecies); // BufferedReader reader = new BufferedReader(fr); // String line = ChemParser.readMeaningfulLine(reader); // //HashSet speciesSet = new HashSet(); // while (line!=null) { // StringTokenizer st = new StringTokenizer(line); // String index = st.nextToken(); // int ID = Integer.parseInt(index); // Species spe = dictionary.getSpeciesFromID(ID); // if (spe == null) // System.out.println("There was no species with ID "+ID +" in the species dictionary"); // //reactionSystem.reactionModel = new CoreEdgeReactionModel(); // ((CoreEdgeReactionModel)getReactionModel()).addUnreactedSpecies(spe); // line = ChemParser.readMeaningfulLine(reader); // catch (IOException e){ // System.out.println("Could not read the edgepecies restart file"); // System.exit(0); /*private int calculateAllReactionsinReactionTemplate() { int totalnum = 0; TemplateReactionGenerator trg = (TemplateReactionGenerator)reactionSystem.reactionGenerator; Iterator iter = trg.getReactionTemplateLibrary().getReactionTemplate(); while (iter.hasNext()){ ReactionTemplate rt = (ReactionTemplate)iter.next(); totalnum += rt.getNumberOfReactions(); } return totalnum; }*/ private void writeEnlargerInfo() { try { File diagnosis = new File("enlarger.xls"); FileWriter fw = new FileWriter(diagnosis); fw.write(Global.enlargerInfo.toString()); fw.close(); } catch (IOException e) { Logger.critical("Cannot write enlarger file"); System.exit(0); } } private void writeDiagnosticInfo() { try { File diagnosis = new File("diagnosis.xls"); FileWriter fw = new FileWriter(diagnosis); fw.write(Global.diagnosticInfo.toString()); fw.close(); } catch (IOException e) { Logger.critical("Cannot write diagnosis file"); System.exit(0); } } //10/25/07 gmagoon: I don't think this is used, but I will update to use reactionSystem and reactionTime as parameter to access temperature; commented-out usage of writeRestartFile will need to be modified //Is still incomplete. public void writeRestartFile(ReactionSystem p_rs, ReactionTime p_time ) { //writeCoreSpecies(p_rs); //writeCoreReactions(p_rs, p_time); //writeEdgeSpecies(); //writeAllReactions(p_rs, p_time); //writeEdgeReactions(p_rs, p_time); //String restartFileName; //String restartFileContent=""; } /* * MRH 25MAR2010 * This method is no longer used */ /*Only write the forward reactions in the model core. The reverse reactions are generated from the forward reactions.*/ //10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature // private void writeEdgeReactions(ReactionSystem p_rs, ReactionTime p_time) { // StringBuilder restartFileContent =new StringBuilder(); // int reactionCount = 1; // try{ // File coreSpecies = new File ("Restart/edgeReactions.txt"); // FileWriter fw = new FileWriter(coreSpecies); // for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){ // Reaction reaction = (Reaction) iter.next(); // //if (reaction.getDirection()==1){ // //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n"; // restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n"); // reactionCount = reactionCount + 1; // //restartFileContent += "\nEND"; // fw.write(restartFileContent.toString()); // fw.close(); // catch (IOException e){ // System.out.println("Could not write the restart edgereactions file"); // System.exit(0); /* * MRH 25MAR2010: * This method is no longer used */ //10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature // private void writeAllReactions(ReactionSystem p_rs, ReactionTime p_time) { // StringBuilder restartFileContent = new StringBuilder(); // int reactionCount = 1; // try{ // File allReactions = new File ("Restart/allReactions.txt"); // FileWriter fw = new FileWriter(allReactions); // for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){ // Reaction reaction = (Reaction) iter.next(); // //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n"; // restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n"); // for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){ // Reaction reaction = (Reaction) iter.next(); // //if (reaction.getDirection()==1){ // //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n"; // restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n"); // //restartFileContent += "\nEND"; // fw.write(restartFileContent.toString()); // fw.close(); // catch (IOException e){ // System.out.println("Could not write the restart edgereactions file"); // System.exit(0); private void writeEdgeSpecies() { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("Restart/edgeSpecies.txt")); for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().iterator();iter.hasNext();){ Species species = (Species) iter.next(); bw.write(species.getFullName()); bw.newLine(); int dummyInt = 0; bw.write(species.getChemGraph().toString(dummyInt)); bw.newLine(); } } catch (FileNotFoundException ex) { Logger.logStackTrace(ex); } catch (IOException ex) { Logger.logStackTrace(ex); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { Logger.logStackTrace(ex); } } } private void writePrunedEdgeSpecies(Species species) { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("Pruning/edgeSpecies.txt", true)); bw.write(species.getChemkinName()); bw.newLine(); int dummyInt = 0; bw.write(species.getChemGraph().toString(dummyInt)); bw.newLine(); } catch (FileNotFoundException ex) { Logger.logStackTrace(ex); } catch (IOException ex) { Logger.logStackTrace(ex); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { Logger.logStackTrace(ex); } } } /* * MRH 25MAR2010: * This method is no longer used */ //10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature // private void writeCoreReactions(ReactionSystem p_rs, ReactionTime p_time) { // StringBuilder restartFileContent = new StringBuilder(); // int reactionCount = 0; // try{ // File coreSpecies = new File ("Restart/coreReactions.txt"); // FileWriter fw = new FileWriter(coreSpecies); // for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){ // Reaction reaction = (Reaction) iter.next(); // if (reaction.getDirection()==1){ // //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n"; // restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n"); // reactionCount = reactionCount + 1; // //restartFileContent += "\nEND"; // fw.write(restartFileContent.toString()); // fw.close(); // catch (IOException e){ // System.out.println("Could not write the restart corereactions file"); // System.exit(0); private void writeCoreSpecies() { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("Restart/coreSpecies.txt")); for(Iterator iter=getReactionModel().getSpecies();iter.hasNext();){ Species species = (Species) iter.next(); bw.write(species.getFullName()); bw.newLine(); int dummyInt = 0; bw.write(species.getChemGraph().toString(dummyInt)); bw.newLine(); } } catch (FileNotFoundException ex) { Logger.logStackTrace(ex); } catch (IOException ex) { Logger.logStackTrace(ex); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { Logger.logStackTrace(ex); } } } private void writeCoreReactions() { BufferedWriter bw_rxns = null; BufferedWriter bw_pdeprxns = null; try { bw_rxns = new BufferedWriter(new FileWriter("Restart/coreReactions.txt")); bw_pdeprxns = new BufferedWriter(new FileWriter("Restart/pdepreactions.txt")); String EaUnits = ArrheniusKinetics.getEaUnits(); String AUnits = ArrheniusKinetics.getAUnits(); bw_rxns.write("UnitsOfEa: " + EaUnits); bw_rxns.newLine(); bw_pdeprxns.write("Unit:\nA: mol/cm3/s\nE: " + EaUnits + "\n\nReactions:"); bw_pdeprxns.newLine(); CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel(); LinkedHashSet allcoreRxns = cerm.core.reaction; for(Iterator iter=allcoreRxns.iterator(); iter.hasNext();){ Reaction reaction = (Reaction) iter.next(); if (reaction.isForward()) { if (reaction instanceof TROEReaction) { TROEReaction troeRxn = (TROEReaction) reaction; bw_pdeprxns.write(troeRxn.toRestartString(new Temperature(298,"K"))); bw_pdeprxns.newLine(); } else if (reaction instanceof LindemannReaction) { LindemannReaction lindeRxn = (LindemannReaction) reaction; bw_pdeprxns.write(lindeRxn.toRestartString(new Temperature(298,"K"))); bw_pdeprxns.newLine(); } else if (reaction instanceof ThirdBodyReaction) { ThirdBodyReaction tbRxn = (ThirdBodyReaction) reaction; bw_pdeprxns.write(tbRxn.toRestartString(new Temperature(298,"K"))); bw_pdeprxns.newLine(); } else { //bw.write(reaction.toChemkinString(new Temperature(298,"K"))); bw_rxns.write(reaction.toRestartString(new Temperature(298,"K"),false)); bw_rxns.newLine(); } } } } catch (FileNotFoundException ex) { Logger.logStackTrace(ex); } catch (IOException ex) { Logger.logStackTrace(ex); } finally { try { if (bw_rxns != null) { bw_rxns.flush(); bw_rxns.close(); } if (bw_pdeprxns != null) { bw_pdeprxns.flush(); bw_pdeprxns.close(); } } catch (IOException ex) { Logger.logStackTrace(ex); } } } private void writeEdgeReactions() { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("Restart/edgeReactions.txt")); String EaUnits = ArrheniusKinetics.getEaUnits(); bw.write("UnitsOfEa: " + EaUnits); bw.newLine(); CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel(); LinkedHashSet alledgeRxns = cerm.edge.reaction; for(Iterator iter=alledgeRxns.iterator(); iter.hasNext();){ Reaction reaction = (Reaction) iter.next(); if (reaction.isForward()) { //bw.write(reaction.toChemkinString(new Temperature(298,"K"))); bw.write(reaction.toRestartString(new Temperature(298,"K"),false)); bw.newLine(); } else if (reaction.getReverseReaction().isForward()) { //bw.write(reaction.getReverseReaction().toChemkinString(new Temperature(298,"K"))); bw.write(reaction.getReverseReaction().toRestartString(new Temperature(298,"K"),false)); bw.newLine(); } else Logger.warning("Could not determine forward direction for following rxn: " + reaction.toString()); } } catch (FileNotFoundException ex) { Logger.logStackTrace(ex); } catch (IOException ex) { Logger.logStackTrace(ex); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { Logger.logStackTrace(ex); } } } //gmagoon 4/5/10: based on Mike's writeEdgeReactions private void writePrunedEdgeReaction(Reaction reaction) { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("Pruning/edgeReactions.txt", true)); if (reaction.isForward()) { bw.write(reaction.toChemkinString(new Temperature(298,"K"))); // bw.write(reaction.toRestartString(new Temperature(298,"K"))); bw.newLine(); } else if (reaction.getReverseReaction().isForward()) { bw.write(reaction.getReverseReaction().toChemkinString(new Temperature(298,"K"))); //bw.write(reaction.getReverseReaction().toRestartString(new Temperature(298,"K"))); bw.newLine(); } else Logger.warning("Could not determine forward direction for following rxn: " + reaction.toString()); } catch (FileNotFoundException ex) { Logger.logStackTrace(ex); } catch (IOException ex) { Logger.logStackTrace(ex); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { Logger.logStackTrace(ex); } } } private void writePDepNetworks() { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("Restart/pdepnetworks.txt")); int numFameTemps = PDepRateConstant.getTemperatures().length; int numFamePress = PDepRateConstant.getPressures().length; int numChebyTemps = ChebyshevPolynomials.getNT(); int numChebyPress = ChebyshevPolynomials.getNP(); int numPlog = PDepArrheniusKinetics.getNumPressures(); String EaUnits = ArrheniusKinetics.getEaUnits(); bw.write("UnitsOfEa: " + EaUnits); bw.newLine(); bw.write("NumberOfFameTemps: " + numFameTemps); bw.newLine(); bw.write("NumberOfFamePress: " + numFamePress); bw.newLine(); bw.write("NumberOfChebyTemps: " + numChebyTemps); bw.newLine(); bw.write("NumberOfChebyPress: " + numChebyPress); bw.newLine(); bw.write("NumberOfPLogs: " + numPlog); bw.newLine(); bw.newLine(); LinkedList allNets = PDepNetwork.getNetworks(); for(Iterator iter=allNets.iterator(); iter.hasNext();){ PDepNetwork pdepnet = (PDepNetwork) iter.next(); bw.write("PDepNetwork #" + pdepnet.getID()); bw.newLine(); // Write netReactionList LinkedList netRxns = pdepnet.getNetReactions(); bw.write("netReactionList:"); bw.newLine(); for (Iterator iter2=netRxns.iterator(); iter2.hasNext();) { PDepReaction currentPDepRxn = (PDepReaction)iter2.next(); bw.write(currentPDepRxn.toString()); bw.newLine(); bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps, numFamePress,numChebyTemps,numChebyPress,numPlog)); } // Write nonincludedReactionList LinkedList nonIncludeRxns = pdepnet.getNonincludedReactions(); bw.write("nonIncludedReactionList:"); bw.newLine(); for (Iterator iter2=nonIncludeRxns.iterator(); iter2.hasNext();) { PDepReaction currentPDepRxn = (PDepReaction)iter2.next(); bw.write(currentPDepRxn.toString()); bw.newLine(); bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps, numFamePress,numChebyTemps,numChebyPress,numPlog)); PDepReaction currentPDepReverseRxn = currentPDepRxn.getReverseReaction(); // Not all nonIncludedReactions are reversible // (MRH FEB-16-2011) ... and not all reverse reactions // have pressure-dependent rate coefficients (apparently) if (currentPDepReverseRxn != null && currentPDepReverseRxn.getPDepRate() != null) { bw.write(currentPDepReverseRxn.toString()); bw.newLine(); bw.write(writeRatesAndParameters(currentPDepReverseRxn,numFameTemps, numFamePress,numChebyTemps,numChebyPress,numPlog)); } } // Write pathReactionList LinkedList pathRxns = pdepnet.getPathReactions(); bw.write("pathReactionList:"); bw.newLine(); for (Iterator iter2=pathRxns.iterator(); iter2.hasNext();) { PDepReaction currentPDepRxn = (PDepReaction)iter2.next(); bw.write(currentPDepRxn.getDirection() + "\t" + currentPDepRxn.toRestartString(new Temperature(298,"K"))); bw.newLine(); } bw.newLine(); bw.newLine(); } } catch (FileNotFoundException ex) { Logger.logStackTrace(ex); } catch (IOException ex) { Logger.logStackTrace(ex); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { Logger.logStackTrace(ex); } } } public String writeRatesAndParameters(PDepReaction pdeprxn, int numFameTemps, int numFamePress, int numChebyTemps, int numChebyPress, int numPlog) { StringBuilder sb = new StringBuilder(); // Write the rate coefficients double[][] rateConstants = pdeprxn.getPDepRate().getRateConstants(); for (int i=0; i<numFameTemps; i++) { for (int j=0; j<numFamePress; j++) { sb.append(rateConstants[i][j] + "\t"); } sb.append("\n"); } sb.append("\n"); // If chebyshev polynomials are present, write them if (numChebyTemps != 0) { ChebyshevPolynomials chebyPolys = pdeprxn.getPDepRate().getChebyshev(); for (int i=0; i<numChebyTemps; i++) { for (int j=0; j<numChebyPress; j++) { sb.append(chebyPolys.getAlpha(i,j) + "\t"); } sb.append("\n"); } sb.append("\n"); } // If plog parameters are present, write them else if (numPlog != 0) { PDepArrheniusKinetics kinetics = pdeprxn.getPDepRate().getPDepArrheniusKinetics(); for (int i=0; i<numPlog; i++) { double Hrxn = pdeprxn.calculateHrxn(new Temperature(298,"K")); sb.append(kinetics.pressures[i].getPa() + "\t" + kinetics.getKinetics(i).toChemkinString(Hrxn,new Temperature(298,"K"),false) + "\n"); } sb.append("\n"); } return sb.toString(); } public LinkedList getTimeStep() { return timeStep; } public static boolean getUseDiffusion() { return useDiffusion; } public static boolean getUseSolvation() { return useSolvation; } public void setUseDiffusion(Boolean p_boolean) { useDiffusion = p_boolean; } public void setUseSolvation(Boolean p_boolean) { useSolvation = p_boolean; } public void setTimeStep(ReactionTime p_timeStep) { if (timeStep == null) timeStep = new LinkedList(); timeStep.add(p_timeStep); } public String getWorkingDirectory() { return workingDirectory; } public void setWorkingDirectory(String p_workingDirectory) { workingDirectory = p_workingDirectory; } //svp public boolean getError(){ return error; } //svp public boolean getSensitivity(){ return sensitivity; } public LinkedList getSpeciesList() { return species; } //gmagoon 10/24/07: commented out getReactionSystem and setReactionSystem // public ReactionSystem getReactionSystem() { // return reactionSystem; //11/2/07 gmagoon: adding accessor method for reactionSystemList public LinkedList getReactionSystemList(){ return reactionSystemList; } //added by gmagoon 9/24/07 // public void setReactionSystem(ReactionSystem p_ReactionSystem) { // reactionSystem = p_ReactionSystem; //copied from ReactionSystem.java by gmagoon 9/24/07 public ReactionModel getReactionModel() { return reactionModel; } public void readRestartSpecies() { Logger.info("Reading in species from Restart folder"); // Read in core species -- NOTE code is almost duplicated in Read in edge species (second part of procedure) try { FileReader in = new FileReader("Restart/coreSpecies.txt"); BufferedReader reader = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(reader, true); while (line != null) { // The first line of a new species is the user-defined name String totalSpeciesName = line; String[] splitString1 = totalSpeciesName.split("[(]"); String[] splitString2 = splitString1[splitString1.length-1].split("[)]"); // The remaining lines are the graph Graph g = ChemParser.readChemGraph(reader); // Make the ChemGraph, assuming it does not contain a forbidden structure ChemGraph cg = null; try { cg = ChemGraph.make(g); } catch (ForbiddenStructureException e) { Logger.critical("Error reading graph: Graph contains a forbidden structure.\n" + g.toString()); System.exit(0); } // Make the species int intLocation = totalSpeciesName.indexOf("(" + splitString2[0] + ")"); Species species = Species.make(totalSpeciesName.substring(0,intLocation),cg,Integer.parseInt(splitString2[0])); // Add the new species to the set of species restartCoreSpcs.add(species); /*int species_type = 1; // reacted species for (int i=0; i<numRxnSystems; i++) { SpeciesStatus ss = new SpeciesStatus(species,species_type,y[i],yprime[i]); speciesStatus[i].put(species, ss); }*/ line = ChemParser.readMeaningfulLine(reader, true); } } catch (FileNotFoundException e) { Logger.logStackTrace(e); } catch (IOException e) { Logger.logStackTrace(e); } // Read in edge species try { FileReader in = new FileReader("Restart/edgeSpecies.txt"); BufferedReader reader = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(reader, true); while (line != null) { // The first line of a new species is the user-defined name String totalSpeciesName = line; String[] splitString1 = totalSpeciesName.split("[(]"); String[] splitString2 = splitString1[splitString1.length-1].split("[)]"); // Change JDM to reflect MRH 2-11-2010 // The remaining lines are the graph Graph g = ChemParser.readChemGraph(reader); // Make the ChemGraph, assuming it does not contain a forbidden structure ChemGraph cg = null; try { cg = ChemGraph.make(g); } catch (ForbiddenStructureException e) { Logger.critical("Error reading graph: Graph contains a forbidden structure.\n" + g.toString()); System.exit(0); } // Rewrite the species name ... with the exception of the ( String speciesName = splitString1[0]; for (int numTokens=1; numTokens<splitString1.length-1; ++numTokens) { speciesName += "(" + splitString1[numTokens]; } // Make the species Species species = Species.make(speciesName,cg,Integer.parseInt(splitString2[0])); // Add the new species to the set of species restartEdgeSpcs.add(species); line = ChemParser.readMeaningfulLine(reader, true); } } catch (FileNotFoundException e) { Logger.logStackTrace(e); } catch (IOException e) { Logger.logStackTrace(e); } } public void readRestartReactions() { // Grab the IDs from the core species int[] coreSpcsIds = new int[restartCoreSpcs.size()]; int i = 0; for (Iterator iter = restartCoreSpcs.iterator(); iter.hasNext();) { Species spcs = (Species)iter.next(); coreSpcsIds[i] = spcs.getID(); ++i; } Logger.info("Reading reactions from Restart folder"); // Read in core reactions try { FileReader in = new FileReader("Restart/coreReactions.txt"); BufferedReader reader = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(reader, true); // Determine units of Ea StringTokenizer st = new StringTokenizer(line); String tempString = st.nextToken(); String EaUnits = st.nextToken(); line = ChemParser.readMeaningfulLine(reader, true); while (line != null) { if (!line.trim().equals("DUP")) { Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"core",EaUnits); Iterator rxnIter = restartCoreRxns.iterator(); boolean foundRxn = false; while (rxnIter.hasNext()) { Reaction old = (Reaction)rxnIter.next(); if (old.equals(r)) { old.addAdditionalKinetics(r.getKinetics()[0],1); foundRxn = true; break; } } if (!foundRxn) { if (r.hasReverseReaction()) r.generateReverseReaction(); restartCoreRxns.add(r); } } line = ChemParser.readMeaningfulLine(reader, true); } } catch (FileNotFoundException e) { Logger.logStackTrace(e); } catch (IOException e) { Logger.logStackTrace(e); } /* * Read in the pdepreactions.txt file: * This file contains third-body, lindemann, and troe reactions * A RMG mechanism would only have these reactions if a user specified * them in a Seed Mechanism, meaning they are core species & * reactions. * Place these reactions in a new Seed Mechanism, using the * coreSpecies.txt file as the species.txt file. */ try { String path = System.getProperty("user.dir") + "/Restart"; if (getSeedMechanism() == null) setSeedMechanism(new SeedMechanism("Restart", path, false, true)); else getSeedMechanism().appendSeedMechanism("Restart", path, false, true); } catch (IOException e1) { Logger.logStackTrace(e1); } restartCoreRxns.addAll(getSeedMechanism().getReactionSet()); // Read in edge reactions try { FileReader in = new FileReader("Restart/edgeReactions.txt"); BufferedReader reader = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(reader, true); // Determine units of Ea StringTokenizer st = new StringTokenizer(line); String tempString = st.nextToken(); String EaUnits = st.nextToken(); line = ChemParser.readMeaningfulLine(reader, true); while (line != null) { if (!line.trim().equals("DUP")) { Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"edge",EaUnits); Iterator rxnIter = restartEdgeRxns.iterator(); boolean foundRxn = false; while (rxnIter.hasNext()) { Reaction old = (Reaction)rxnIter.next(); if (old.equals(r)) { old.addAdditionalKinetics(r.getKinetics()[0],1); foundRxn = true; break; } } if (!foundRxn) { r.generateReverseReaction(); restartEdgeRxns.add(r); } } line = ChemParser.readMeaningfulLine(reader, true); } } catch (FileNotFoundException e) { Logger.logStackTrace(e); } catch (IOException e) { Logger.logStackTrace(e); } } public LinkedHashMap getRestartSpeciesStatus(int i) { LinkedHashMap speciesStatus = new LinkedHashMap(); try { FileReader in = new FileReader("Restart/coreSpecies.txt"); BufferedReader reader = new BufferedReader(in); Integer numRxnSystems = Integer.parseInt(ChemParser.readMeaningfulLine(reader, true)); String line = ChemParser.readMeaningfulLine(reader, true); while (line != null) { // The first line of a new species is the user-defined name String totalSpeciesName = line; String[] splitString1 = totalSpeciesName.split("[(]"); String[] splitString2 = splitString1[1].split("[)]"); double y = 0.0; double yprime = 0.0; for (int j=0; j<numRxnSystems; j++) { StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true)); if (j == i) { y = Double.parseDouble(st.nextToken()); yprime = Double.parseDouble(st.nextToken()); } } // The remaining lines are the graph Graph g = ChemParser.readChemGraph(reader); // Make the ChemGraph, assuming it does not contain a forbidden structure ChemGraph cg = null; try { cg = ChemGraph.make(g); } catch (ForbiddenStructureException e) { Logger.critical("Error reading graph: Graph contains a forbidden structure.\n" + g.toString()); System.exit(0); } // Make the species Species species = Species.make(splitString1[0],cg); // Add the new species to the set of species //restartCoreSpcs.add(species); int species_type = 1; // reacted species SpeciesStatus ss = new SpeciesStatus(species,species_type,y,yprime); speciesStatus.put(species, ss); line = ChemParser.readMeaningfulLine(reader, true); } } catch (FileNotFoundException e) { Logger.logStackTrace(e); } catch (IOException e) { Logger.logStackTrace(e); } return speciesStatus; } public void putRestartSpeciesInInitialStatus(InitialStatus is, int i) { try { FileReader in = new FileReader("Restart/coreSpecies.txt"); BufferedReader reader = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(reader, true); while (line != null) { // The first line of a new species is the user-defined name String totalSpeciesName = line; String[] splitString1 = totalSpeciesName.split("[(]"); String[] splitString2 = splitString1[1].split("[)]"); // The remaining lines are the graph Graph g = ChemParser.readChemGraph(reader); // Make the ChemGraph, assuming it does not contain a forbidden structure ChemGraph cg = null; try { cg = ChemGraph.make(g); } catch (ForbiddenStructureException e) { Logger.critical("Error reading graph: Graph contains a forbidden structure.\n" + g.toString()); System.exit(0); } // Make the species Species species = Species.make(splitString1[0],cg); // Add the new species to the set of species //restartCoreSpcs.add(species); if (is.getSpeciesStatus(species) == null) { SpeciesStatus ss = new SpeciesStatus(species,1,0.0,0.0); is.putSpeciesStatus(ss); } line = ChemParser.readMeaningfulLine(reader, true); } } catch (FileNotFoundException e) { Logger.logStackTrace(e); } catch (IOException e) { Logger.logStackTrace(e); } } public void readPDepNetworks() { LinkedList allNetworks = PDepNetwork.getNetworks(); try { FileReader in = new FileReader("Restart/pdepnetworks.txt"); BufferedReader reader = new BufferedReader(in); StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true)); String tempString = st.nextToken(); String EaUnits = st.nextToken(); st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true)); tempString = st.nextToken(); int numFameTs = Integer.parseInt(st.nextToken()); st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true)); tempString = st.nextToken(); int numFamePs = Integer.parseInt(st.nextToken()); st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true)); tempString = st.nextToken(); int numChebyTs = Integer.parseInt(st.nextToken()); st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true)); tempString = st.nextToken(); int numChebyPs = Integer.parseInt(st.nextToken()); st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true)); tempString = st.nextToken(); int numPlogs = Integer.parseInt(st.nextToken()); double[][] rateCoefficients = new double[numFameTs][numFamePs]; double[][] chebyPolys = new double[numChebyTs][numChebyPs]; Kinetics[] plogKinetics = new Kinetics[numPlogs]; String line = ChemParser.readMeaningfulLine(reader, true); // line should be "PDepNetwork while (line != null) { line = ChemParser.readMeaningfulLine(reader, true); // line should now be "netReactionList:" PDepNetwork newNetwork = new PDepNetwork(); LinkedList netRxns = newNetwork.getNetReactions(); LinkedList nonincludeRxns = newNetwork.getNonincludedReactions(); line = ChemParser.readMeaningfulLine(reader, true); // line is either data or "nonIncludedReactionList" // If line is "nonincludedreactionlist", we need to skip over this while loop if (!line.toLowerCase().startsWith("nonincludedreactionlist")) { while (!line.toLowerCase().startsWith("nonincludedreactionlist")) { // Read in the forward rxn String[] reactsANDprods = line.split("\\ /* * Determine if netReaction is reversible or irreversible */ boolean reactionIsReversible = true; if (reactsANDprods.length == 2) reactionIsReversible = false; else reactsANDprods = line.split("\\<=>"); PDepIsomer Reactants = parseIsomerFromRestartFile(reactsANDprods[0].trim()); PDepIsomer Products = parseIsomerFromRestartFile(reactsANDprods[1].trim()); newNetwork.addIsomer(Reactants); newNetwork.addIsomer(Products); rateCoefficients = parseRateCoeffsFromRestartFile(numFameTs,numFamePs,reader); PDepRateConstant pdepk = parsePDepRateConstantFromRestartFile(reader,numChebyTs,numChebyPs,rateCoefficients,numPlogs,EaUnits); PDepReaction forward = new PDepReaction(Reactants, Products, pdepk); // Read in the reverse reaction if (reactionIsReversible) { PDepReaction reverse = new PDepReaction(Products, Reactants, new PDepRateConstant()); reverse.setPDepRateConstant(null); reverse.setReverseReaction(forward); forward.setReverseReaction(reverse); } else { PDepReaction reverse = null; forward.setReverseReaction(reverse); } netRxns.add(forward); line = ChemParser.readMeaningfulLine(reader, true); } } // This loop ends once line == "nonIncludedReactionList" line = ChemParser.readMeaningfulLine(reader, true); // line is either data or "pathReactionList" if (!line.toLowerCase().startsWith("pathreactionList")) { while (!line.toLowerCase().startsWith("pathreactionlist")) { // Read in the forward rxn String[] reactsANDprods = line.split("\\ /* * Determine if nonIncludedReaction is reversible or irreversible */ boolean reactionIsReversible = true; if (reactsANDprods.length == 2) reactionIsReversible = false; else reactsANDprods = line.split("\\<=>"); PDepIsomer Reactants = parseIsomerFromRestartFile(reactsANDprods[0].trim()); PDepIsomer Products = parseIsomerFromRestartFile(reactsANDprods[1].trim()); newNetwork.addIsomer(Reactants); newNetwork.addIsomer(Products); rateCoefficients = parseRateCoeffsFromRestartFile(numFameTs,numFamePs,reader); PDepRateConstant pdepk = parsePDepRateConstantFromRestartFile(reader,numChebyTs,numChebyPs,rateCoefficients,numPlogs,EaUnits); PDepReaction forward = new PDepReaction(Reactants, Products, pdepk); // Read in the reverse reaction if (reactionIsReversible) { PDepReaction reverse = new PDepReaction(Products, Reactants, new PDepRateConstant()); reverse.setPDepRateConstant(null); reverse.setReverseReaction(forward); forward.setReverseReaction(reverse); } else { PDepReaction reverse = null; forward.setReverseReaction(reverse); } nonincludeRxns.add(forward); line = ChemParser.readMeaningfulLine(reader, true); } } // This loop ends once line == "pathReactionList" line = ChemParser.readMeaningfulLine(reader, true); // line is either data or "PDepNetwork #_" or null (end of file) while (line != null && !line.toLowerCase().startsWith("pdepnetwork")) { st = new StringTokenizer(line); int direction = Integer.parseInt(st.nextToken()); // First token is the rxn structure: A+B=C+D // Note: Up to 3 reactants/products allowed // : Either "=" or "=>" will separate reactants and products String structure = st.nextToken(); // Separate the reactants from the products boolean generateReverse = false; String[] reactsANDprods = structure.split("\\=>"); if (reactsANDprods.length == 1) { reactsANDprods = structure.split("[=]"); generateReverse = true; } SpeciesDictionary sd = SpeciesDictionary.getInstance(); LinkedList r = ChemParser.parseReactionSpecies(sd, reactsANDprods[0]); LinkedList p = ChemParser.parseReactionSpecies(sd, reactsANDprods[1]); Structure s = new Structure(r,p); s.setDirection(direction); // Next three tokens are the modified Arrhenius parameters double rxn_A = Double.parseDouble(st.nextToken()); double rxn_n = Double.parseDouble(st.nextToken()); double rxn_E = Double.parseDouble(st.nextToken()); if (EaUnits.equals("cal/mol")) rxn_E = rxn_E / 1000; else if (EaUnits.equals("J/mol")) rxn_E = rxn_E / 4.184 / 1000; else if (EaUnits.equals("kJ/mol")) rxn_E = rxn_E / 4.184; else if (EaUnits.equals("Kelvins")) rxn_E = rxn_E * 1.987; UncertainDouble uA = new UncertainDouble(rxn_A,0.0,"A"); UncertainDouble un = new UncertainDouble(rxn_n,0.0,"A"); UncertainDouble uE = new UncertainDouble(rxn_E,0.0,"A"); // The remaining tokens are comments String comments = ""; if (st.hasMoreTokens()) { String beginningOfComments = st.nextToken(); int startIndex = line.indexOf(beginningOfComments); comments = line.substring(startIndex); } if (comments.startsWith("!")) comments = comments.substring(1); // while (st.hasMoreTokens()) { // comments += st.nextToken(); ArrheniusKinetics[] k = new ArrheniusKinetics[1]; k[0] = new ArrheniusKinetics(uA,un,uE,"",1,"",comments); Reaction pathRxn = new Reaction(); // if (direction == 1) // pathRxn = Reaction.makeReaction(s,k,generateReverse); // else // pathRxn = Reaction.makeReaction(s.generateReverseStructure(),k,generateReverse); pathRxn = Reaction.makeReaction(s,k,generateReverse); PDepIsomer Reactants = new PDepIsomer(r); PDepIsomer Products = new PDepIsomer(p); PDepReaction pdeppathrxn = new PDepReaction(Reactants,Products,pathRxn); newNetwork.addReaction(pdeppathrxn,true); newNetwork.addIsomer(Reactants); newNetwork.addIsomer(Products); line = ChemParser.readMeaningfulLine(reader, true); } newNetwork.setAltered(false); PDepNetwork.getNetworks().add(newNetwork); } } catch (FileNotFoundException e) { Logger.logStackTrace(e); } catch (IOException e) { Logger.logStackTrace(e); } } public PDepIsomer parseIsomerFromRestartFile(String p_string) { SpeciesDictionary sd = SpeciesDictionary.getInstance(); PDepIsomer isomer = null; if (p_string.contains("+")) { String[] indivReacts = p_string.split("[+]"); String name = indivReacts[0].trim(); Species spc1 = sd.getSpeciesFromNameID(name); if (spc1 == null) { spc1 = getSpeciesBySPCName(name,sd); } name = indivReacts[1].trim(); String[] nameANDincluded = name.split("\\(included ="); Species spc2 = sd.getSpeciesFromNameID(nameANDincluded[0].trim()); if (spc2 == null) { spc2 = getSpeciesBySPCName(name,sd); } boolean isIncluded = Boolean.parseBoolean(nameANDincluded[1].substring(0,nameANDincluded[1].length()-1)); isomer = new PDepIsomer(spc1,spc2,isIncluded); } else { String name = p_string.trim(); /* * Separate the (included =boolean) portion of the string * from the name of the Isomer */ String[] nameANDincluded = name.split("\\(included ="); Species spc = sd.getSpeciesFromNameID(nameANDincluded[0].trim()); if (spc == null) { spc = getSpeciesBySPCName(name,sd); } boolean isIncluded = Boolean.parseBoolean(nameANDincluded[1].substring(0,nameANDincluded[1].length()-1)); isomer = new PDepIsomer(spc,isIncluded); } return isomer; } public double[][] parseRateCoeffsFromRestartFile(int numFameTs, int numFamePs, BufferedReader reader) { double[][] rateCoefficients = new double[numFameTs][numFamePs]; for (int i=0; i<numFameTs; i++) { StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true)); for (int j=0; j<numFamePs; j++) { rateCoefficients[i][j] = Double.parseDouble(st.nextToken()); } } return rateCoefficients; } public PDepRateConstant parsePDepRateConstantFromRestartFile(BufferedReader reader, int numChebyTs, int numChebyPs, double[][] rateCoefficients, int numPlogs, String EaUnits) { PDepRateConstant pdepk = null; if (numChebyTs > 0) { double chebyPolys[][] = new double[numChebyTs][numChebyPs]; for (int i=0; i<numChebyTs; i++) { StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true)); for (int j=0; j<numChebyPs; j++) { chebyPolys[i][j] = Double.parseDouble(st.nextToken()); } } ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs, ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(), numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(), chebyPolys); pdepk = new PDepRateConstant(rateCoefficients,chebyshev); } else if (numPlogs > 0) { PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(numPlogs); for (int i=0; i<numPlogs; i++) { StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true)); Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa"); UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A"); UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A"); double Ea = Double.parseDouble(st.nextToken()); if (EaUnits.equals("cal/mol")) Ea = Ea / 1000; else if (EaUnits.equals("J/mol")) Ea = Ea / 4.184 / 1000; else if (EaUnits.equals("kJ/mol")) Ea = Ea / 4.184; else if (EaUnits.equals("Kelvins")) Ea = Ea * 1.987; UncertainDouble dE = new UncertainDouble(Ea,0.0,"A"); ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", ""); pdepAK.setKinetics(i, p, k); pdepk = new PDepRateConstant(rateCoefficients,pdepAK); } } return pdepk; } /** * MRH 14Jan2010 * * getSpeciesBySPCName * * Input: String name - Name of species, normally chemical formula followed * by "J"s for radicals, and then (#) * SpeciesDictionary sd * * This method was originally written as a complement to the method readPDepNetworks. * jdmo found a bug with the readrestart option. The bug was that the method was * attempting to add a null species to the Isomer list. The null species resulted * from searching the SpeciesDictionary by chemkinName (e.g. C4H8OJJ(48)), when the * chemkinName present in the dictionary was SPC(48). * */ public Species getSpeciesBySPCName(String name, SpeciesDictionary sd) { String[] nameFromNumber = name.split("\\("); String newName = "SPC(" + nameFromNumber[1]; return sd.getSpeciesFromChemkinName(newName); } /** * MRH 12-Jun-2009 * * Function initializes the model's core and edge. * The initial core species always consists of the species contained * in the condition.txt file. If seed mechanisms exist, those species * (and the reactions given in the seed mechanism) are also added to * the core. * The initial edge species/reactions are determined by reacting the core * species by one full iteration. */ public void initializeCoreEdgeModel() { LinkedHashSet allInitialCoreSpecies = new LinkedHashSet(); LinkedHashSet allInitialCoreRxns = new LinkedHashSet(); if (readrestart) { allInitialCoreSpecies.addAll(restartCoreSpcs); allInitialCoreRxns.addAll(restartCoreRxns); } // Add the species from the condition.txt (input) file allInitialCoreSpecies.addAll(getSpeciesSeed()); // Add the species from the seed mechanisms, if they exist if (hasSeedMechanisms()) { allInitialCoreSpecies.addAll(getSeedMechanism().getSpeciesSet()); allInitialCoreRxns.addAll(getSeedMechanism().getReactionSet()); } CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(allInitialCoreSpecies, allInitialCoreRxns); if (readrestart) { cerm.addUnreactedSpeciesSet(restartEdgeSpcs); cerm.addUnreactedReactionSet(restartEdgeRxns); } setReactionModel(cerm); PDepNetwork.reactionModel = getReactionModel(); PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0); // Determine initial set of reactions and edge species using only the // species enumerated in the input file and the seed mechanisms as the core if (!readrestart) { LinkedHashSet reactionSet_withdup; LinkedHashSet reactionSet; // If Seed Mechanism is present and Generate Reaction is set on if (hasSeedMechanisms() && getSeedMechanism().shouldGenerateReactions()) { reactionSet_withdup = getLibraryReactionGenerator().react(allInitialCoreSpecies); reactionSet_withdup.addAll(getReactionGenerator().react(allInitialCoreSpecies)); // Removing Duplicates instances of reaction if present reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup); } else { reactionSet_withdup = new LinkedHashSet(); LinkedHashSet tempnewReactionSet = getLibraryReactionGenerator().react(allInitialCoreSpecies); if(tempnewReactionSet.isEmpty()){ Logger.info("No reactions found from Reaction Library"); } else { Logger.info("Reactions found from Reaction Library:"); Logger.info(tempnewReactionSet.toString()); // Adds Reactions Found in Library Reaction Generator to Reaction Set reactionSet_withdup.addAll(tempnewReactionSet); } // Generates Reaction from the Reaction Generator and adds them to Reaction Set for (Iterator iter = speciesSeed.iterator(); iter.hasNext(); ) { Species spec = (Species) iter.next(); reactionSet_withdup.addAll(getReactionGenerator().react(allInitialCoreSpecies, spec,"All")); } reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup); } // Set initial core-edge reaction model based on above results if (reactionModelEnlarger instanceof RateBasedRME) { Iterator iter = reactionSet.iterator(); while (iter.hasNext()){ Reaction r = (Reaction)iter.next(); cerm.addReaction(r); } } else { // Only keep the reactions involving bimolecular reactants and bimolecular products Iterator iter = reactionSet.iterator(); while (iter.hasNext()){ Reaction r = (Reaction)iter.next(); if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){ cerm.addReaction(r); } else { cerm.categorizeReaction(r.getStructure()); PDepNetwork.addReactionToNetworks(r); } } } } /* * 22-SEPT-2010 * ELSE: * If reading in restart files, at the very least, we should react * all species present in the input file (speciesSeed) with all of * the coreSpecies. Before, when the following else statement was * not present, we would completely skip this step. Thus, RMG would * come to the first ODE solve, integrate to a very large time, and * conclude that the model was both valid and terminated, thereby * not adding any new reactions to the core regardless of the * conditions stated in the input file. * EXAMPLE: * A user runs RMG for iso-octane with Restart turned on. The * simulation converges and now the user would like to add a small * amount of 1-butanol to the input file, while reading in from the * Restart files. What should happen, at the very least, is 1-butanol * reacts with the other species present in the input file and with * the already-known coreSpecies. This will, at a minimum, add these * reactions to the core. Whether the model remains validated and * terminated depends on the conditions stated in the input file. * MRH (mrharper@mit.edu) */ else { LinkedHashSet reactionSet_withdup; LinkedHashSet reactionSet; /* * If the user has specified a Seed Mechanism, and that the cross reactions * should be generated, generate those here * NOTE: Since the coreSpecies from the Restart files are treated as a Seed * Mechanism, MRH is inclined to comment out the following lines. Depending * on how large the Seed Mechanism and/or Restart files are, RMG could get * "stuck" cross-reacting hundreds of species against each other. */ // if (hasSeedMechanisms() && getSeedMechanism().shouldGenerateReactions()) { // reactionSet_withdup = getLibraryReactionGenerator().react(getSeedMechanism().getSpeciesSet()); // reactionSet_withdup.addAll(getReactionGenerator().react(getSeedMechanism().getSpeciesSet())); // reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup); /* * If not, react the species present in the input file against any * reaction libraries, and then against all RMG-defined reaction * families */ // else { reactionSet_withdup = new LinkedHashSet(); LinkedHashSet tempnewReactionSet = getLibraryReactionGenerator().react(speciesSeed); if (!tempnewReactionSet.isEmpty()) { Logger.info("Reaction Set Found from Reaction Library "+tempnewReactionSet); } // Adds Reactions Found in Library Reaction Generator to Reaction Set reactionSet_withdup.addAll(tempnewReactionSet); // Generates Reaction from the Reaction Generator and adds them to Reaction Set for (Iterator iter = speciesSeed.iterator(); iter.hasNext(); ) { Species spec = (Species) iter.next(); reactionSet_withdup.addAll(getReactionGenerator().react(allInitialCoreSpecies,spec,"All")); } reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup); // Set initial core-edge reaction model based on above results if (reactionModelEnlarger instanceof RateBasedRME) { Iterator iter = reactionSet.iterator(); while (iter.hasNext()){ Reaction r = (Reaction)iter.next(); cerm.addReaction(r); } } else { // Only keep the reactions involving bimolecular reactants and bimolecular products Iterator iter = reactionSet.iterator(); while (iter.hasNext()){ Reaction r = (Reaction)iter.next(); if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){ cerm.addReaction(r); } else { cerm.categorizeReaction(r.getStructure()); PDepNetwork.addReactionToNetworks(r); } } } } for (Integer i = 0; i < reactionSystemList.size(); i++) { ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i); rs.setReactionModel(getReactionModel()); } // We cannot return a system with no core reactions, so if this is a case we must add to the core while (getReactionModel().isEmpty() && !PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) { for (Integer i = 0; i < reactionSystemList.size(); i++) { ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i); if (reactionModelEnlarger instanceof RateBasedPDepRME) rs.initializePDepNetwork(); rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature()); } enlargeReactionModel(); } for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); rs.setReactionModel(getReactionModel()); } return; } //9/24/07 gmagoon: moved from ReactionSystem.java public void initializeCoreEdgeModelWithPKL() { initializeCoreEdgeModelWithoutPKL(); CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel(); LinkedHashSet primarySpeciesSet = getPrimaryKineticLibrary().getSpeciesSet(); //10/14/07 gmagoon: changed to use getPrimaryReactionLibrary LinkedHashSet primaryKineticSet = getPrimaryKineticLibrary().getReactionSet(); cerm.addReactedSpeciesSet(primarySpeciesSet); cerm.addPrimaryKineticSet(primaryKineticSet); LinkedHashSet newReactions = getReactionGenerator().react(cerm.getReactedSpeciesSet()); if (reactionModelEnlarger instanceof RateBasedRME) cerm.addReactionSet(newReactions); else { Iterator iter = newReactions.iterator(); while (iter.hasNext()){ Reaction r = (Reaction)iter.next(); if (r.getReactantNumber() == 2 && r.getProductNumber() == 2){ cerm.addReaction(r); } } } return; // } //9/24/07 gmagoon: moved from ReactionSystem.java protected void initializeCoreEdgeModelWithoutPKL() { CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(new LinkedHashSet(getSpeciesSeed())); setReactionModel(cerm); PDepNetwork.reactionModel = getReactionModel(); PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0); // Determine initial set of reactions and edge species using only the // species enumerated in the input file as the core LinkedHashSet reactionSet = getReactionGenerator().react(getSpeciesSeed()); reactionSet.addAll(getLibraryReactionGenerator().react(getSpeciesSeed())); // Set initial core-edge reaction model based on above results if (reactionModelEnlarger instanceof RateBasedRME) { // Only keep the reactions involving bimolecular reactants and bimolecular products Iterator iter = reactionSet.iterator(); while (iter.hasNext()){ Reaction r = (Reaction)iter.next(); cerm.addReaction(r); } } else { // Only keep the reactions involving bimolecular reactants and bimolecular products Iterator iter = reactionSet.iterator(); while (iter.hasNext()){ Reaction r = (Reaction)iter.next(); if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){ cerm.addReaction(r); } else { cerm.categorizeReaction(r.getStructure()); PDepNetwork.addReactionToNetworks(r); } } } //10/9/07 gmagoon: copy reactionModel to reactionSystem; there may still be scope problems, particularly in above elseif statement //10/24/07 gmagoon: want to copy same reaction model to all reactionSystem variables; should probably also make similar modifications elsewhere; may or may not need to copy in ...WithPRL function for (Integer i = 0; i < reactionSystemList.size(); i++) { ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i); rs.setReactionModel(getReactionModel()); } //reactionSystem.setReactionModel(getReactionModel()); // We cannot return a system with no core reactions, so if this is a case we must add to the core while (getReactionModel().isEmpty()&&!PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) { for (Integer i = 0; i < reactionSystemList.size(); i++) { ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i); if (reactionModelEnlarger instanceof RateBasedPDepRME) rs.initializePDepNetwork(); rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature()); } enlargeReactionModel(); } for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); rs.setReactionModel(getReactionModel()); } return; // } //## operation initializeCoreEdgeReactionModel() //9/24/07 gmagoon: moved from ReactionSystem.java public void initializeCoreEdgeReactionModel() { Logger.info("Initializing core-edge reaction model"); initializeCoreEdgeModel(); } //9/24/07 gmagoon: copied from ReactionSystem.java public ReactionGenerator getReactionGenerator() { return reactionGenerator; } //10/4/07 gmagoon: moved from ReactionSystem.java public void setReactionGenerator(ReactionGenerator p_ReactionGenerator) { reactionGenerator = p_ReactionGenerator; } //9/25/07 gmagoon: moved from ReactionSystem.java //10/24/07 gmagoon: changed to use reactionSystemList //## operation enlargeReactionModel() public void enlargeReactionModel() { //#[ operation enlargeReactionModel() if (reactionModelEnlarger == null) throw new NullPointerException("ReactionModelEnlarger"); Logger.info(""); Logger.info("Enlarging reaction model"); reactionModelEnlarger.enlargeReactionModel(reactionSystemList, reactionModel, validList); return; // } public void pruneReactionModel(HashMap unprunableSpecies) { Runtime runtime = Runtime.getRuntime(); HashMap prunableSpeciesMap = new HashMap(); //check whether all the reaction systems reached target conversion/time boolean allReachedTarget = true; for (Integer i = 0; i < reactionSystemList.size(); i++) { JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator(); if (!ds.targetReached) allReachedTarget = false; } JDAS ds0 = (JDAS)((ReactionSystem) reactionSystemList.get(0)).getDynamicSimulator(); //get the first reactionSystem dynamic simulator //prune the reaction model if AUTO is being used, and all reaction systems have reached target time/conversion, and edgeTol is non-zero (and positive, obviously), and if there are a sufficient number of species in the reaction model (edge + core) if ( JDAS.autoflag && allReachedTarget && edgeTol>0 && (((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber()+reactionModel.getSpeciesNumber())>= minSpeciesForPruning){ int numberToBePruned = ((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber() - maxEdgeSpeciesAfterPruning; //System.out.println("PDep Pruning DEBUG:\nThe number of species in the model's edge, before pruning: " + ((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber()); //System.out.println("PDep Pruning DEBUG:\nRMG thinks the following number of species" + // " needs to be pruned: " + numberToBePruned); Iterator iter = JDAS.edgeID.keySet().iterator();//determine the maximum edge flux ratio for each edge species while(iter.hasNext()){ Species spe = (Species)iter.next(); Integer id = (Integer)JDAS.edgeID.get(spe); double maxmaxRatio = ds0.maxEdgeFluxRatio[id-1]; boolean prunable = ds0.prunableSpecies[id-1]; //go through the rest of the reaction systems to see if there are higher max flux ratios for (Integer i = 1; i < reactionSystemList.size(); i++) { JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator(); if(ds.maxEdgeFluxRatio[id-1] > maxmaxRatio) maxmaxRatio = ds.maxEdgeFluxRatio[id-1]; if(!ds.prunableSpecies[id-1]) prunable = false;// probably redundant: if the conc. is zero in one system, it should be zero in all systems, but it is included for completeness } //if the species is "prunable" (i.e. it doesn't have any reactions producing it with zero flux), add it to the prunableSpeciesMap if( prunable){ prunableSpeciesMap.put(spe, maxmaxRatio); } } //repeat with the edgeLeakID; if a species appears in both lists, it will be prunable only if it is prunable in both cases, and the sum of maximum edgeFlux + maximum edgeLeakFlux (for each reaction system) will be considered; this will be a conservative overestimate of maximum (edgeFlux+edgeLeakFlux) iter = JDAS.edgeLeakID.keySet().iterator(); while(iter.hasNext()){ Species spe = (Species)iter.next(); Integer id = (Integer)JDAS.edgeLeakID.get(spe); //check whether the same species is in edgeID if(JDAS.edgeID.containsKey(spe)){//the species exists in edgeID if(prunableSpeciesMap.containsKey(spe)){//the species was determined to be "prunable" based on edgeID Integer idEdge=(Integer)JDAS.edgeID.get(spe); double maxmaxRatio = ds0.maxEdgeFluxRatio[id-1]+ds0.maxEdgeFluxRatio[idEdge-1]; boolean prunable = ds0.prunableSpecies[id-1]; //go through the rest of the reaction systems to see if there are higher max flux ratios for (Integer i = 1; i < reactionSystemList.size(); i++) { JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator(); if(ds.maxEdgeFluxRatio[id-1]+ds.maxEdgeFluxRatio[idEdge-1] > maxmaxRatio) maxmaxRatio = ds.maxEdgeFluxRatio[id-1]+ds.maxEdgeFluxRatio[idEdge-1]; if(!ds.prunableSpecies[id-1]) prunable = false;// probably redundant: if the conc. is zero in one system, it should be zero in all systems, but it is included for completeness } if( prunable){//if the species is "prunable" (i.e. it doesn't have any reactions producing it with zero flux), replace with the newly determined maxmaxRatio prunableSpeciesMap.remove(spe); prunableSpeciesMap.put(spe, maxmaxRatio); } else{//otherwise, the species is not prunable in both edgeID and edgeLeakID and should be removed from the prunable species map prunableSpeciesMap.remove(spe); } } } else{//the species is new double maxmaxRatio = ds0.maxEdgeFluxRatio[id-1]; boolean prunable = ds0.prunableSpecies[id-1]; //go through the rest of the reaction systems to see if there are higher max flux ratios for (Integer i = 1; i < reactionSystemList.size(); i++) { JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator(); if(ds.maxEdgeFluxRatio[id-1] > maxmaxRatio) maxmaxRatio = ds.maxEdgeFluxRatio[id-1]; if(!ds.prunableSpecies[id-1]) prunable = false;// probably redundant: if the conc. is zero in one system, it should be zero in all systems, but it is included for completeness } //if the species is "prunable" (i.e. it doesn't have any reactions producing it with zero flux), add it to the prunableSpeciesMap if( prunable){ prunableSpeciesMap.put(spe, maxmaxRatio); } } } // at this point prunableSpeciesMap includes ALL prunable species, no matter how large their flux //System.out.println("PDep Pruning DEBUG:\nRMG has marked the following number of species" + // " as prunable, before checking against explored (included) species: " + prunableSpeciesMap.size()); // Pressure dependence only: Species that are included in any // PDepNetwork are not eligible for pruning, so they must be removed // from the map of prunable species if (reactionModelEnlarger instanceof RateBasedPDepRME) { LinkedList speciesToRemove = new LinkedList(); for (iter = prunableSpeciesMap.keySet().iterator(); iter.hasNext(); ) { Species spec = (Species) iter.next(); if (PDepNetwork.isSpeciesIncludedInAnyNetwork(spec)) speciesToRemove.add(spec); } for (iter = speciesToRemove.iterator(); iter.hasNext(); ) { prunableSpeciesMap.remove(iter.next()); } } //System.out.println("PDep Pruning DEBUG:\nRMG now reduced the number of prunable species," + // " after checking against explored (included) species, to: " + prunableSpeciesMap.size()); // sort the prunableSpecies by maxmaxRatio // i.e. sort the map by values List prunableSpeciesList = new LinkedList(prunableSpeciesMap.entrySet()); Collections.sort(prunableSpeciesList, new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o1)).getValue()) .compareTo(((Map.Entry) (o2)).getValue()); } }); List speciesToPrune = new LinkedList(); int belowThreshold = 0; int lowMaxFlux = 0; for (Iterator it = prunableSpeciesList.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry)it.next(); Species spe = (Species)entry.getKey(); double maxmaxRatio = (Double)entry.getValue(); if (maxmaxRatio < edgeTol) { Logger.info("Edge species "+spe.getChemkinName() +" has a maximum flux ratio ("+maxmaxRatio+") lower than edge inclusion threshhold and will be pruned."); speciesToPrune.add(spe); ++belowThreshold; } else if ( numberToBePruned - speciesToPrune.size() > 0 ) { Logger.info("Edge species "+spe.getChemkinName() +" has a low maximum flux ratio ("+maxmaxRatio+") and will be pruned to reduce the edge size to the maximum ("+maxEdgeSpeciesAfterPruning+")."); speciesToPrune.add(spe); ++lowMaxFlux; } else break; // no more to be pruned } //System.out.println("PDep Pruning DEBUG:\nRMG has marked the following number of species" + // " to be pruned due to max flux ratio lower than threshold: " + belowThreshold); //System.out.println("PDep Pruning DEBUG:\nRMG has marked the following number of species" + // " to be pruned due to low max flux ratio : " + lowMaxFlux); runtime.gc(); double memoryUsedBeforePruning = (runtime.totalMemory() - runtime.freeMemory()) / 1.0e6; //now, speciesToPrune has been filled with species that should be pruned from the edge Logger.info("Pruning..."); //prune species from the edge //remove species from the edge and from the species dictionary and from edgeID iter = speciesToPrune.iterator(); while(iter.hasNext()){ Species spe = (Species)iter.next(); writePrunedEdgeSpecies(spe); ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().remove(spe); //SpeciesDictionary.getInstance().getSpeciesSet().remove(spe); if (!unprunableSpecies.containsValue(spe)) SpeciesDictionary.getInstance().remove(spe); else Logger.info("Pruning Message: Not removing the following species " + "from the SpeciesDictionary\nas it is present in a Primary Kinetic / Reaction" + " Library\nThe species will still be removed from the Edge of the " + "Reaction Mechanism\n" + spe.toString()); JDAS.edgeID.remove(spe); } //remove reactions from the edge involving pruned species iter = ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator(); HashSet toRemove = new HashSet(); while(iter.hasNext()){ Reaction reaction = (Reaction)iter.next(); if (reactionPrunableQ(reaction, speciesToPrune)) toRemove.add(reaction); } iter = toRemove.iterator(); while(iter.hasNext()){ Reaction reaction = (Reaction)iter.next(); writePrunedEdgeReaction(reaction); Reaction reverse = reaction.getReverseReaction(); ((CoreEdgeReactionModel)reactionModel).removeFromUnreactedReactionSet(reaction); ((CoreEdgeReactionModel)reactionModel).removeFromUnreactedReactionSet(reverse); reaction.prune(); if (reverse != null) reverse.prune(); } //remove reactions from PDepNetworks in PDep cases if (reactionModelEnlarger instanceof RateBasedPDepRME) { iter = PDepNetwork.getNetworks().iterator(); HashSet pdnToRemove = new HashSet(); HashSet toRemovePath; HashSet toRemoveNet; HashSet toRemoveNonincluded; HashSet toRemoveIsomer; while (iter.hasNext()){ PDepNetwork pdn = (PDepNetwork)iter.next(); //identify path reactions to remove Iterator rIter = pdn.getPathReactions().iterator(); toRemovePath = new HashSet(); while(rIter.hasNext()){ Reaction reaction = (Reaction)rIter.next(); if (reactionPrunableQ(reaction, speciesToPrune)) toRemovePath.add(reaction); } //identify net reactions to remove rIter = pdn.getNetReactions().iterator(); toRemoveNet = new HashSet(); while(rIter.hasNext()){ Reaction reaction = (Reaction)rIter.next(); if (reactionPrunableQ(reaction, speciesToPrune)) toRemoveNet.add(reaction); } //identify nonincluded reactions to remove rIter = pdn.getNonincludedReactions().iterator(); toRemoveNonincluded = new HashSet(); while(rIter.hasNext()){ Reaction reaction = (Reaction)rIter.next(); if (reactionPrunableQ(reaction, speciesToPrune)) toRemoveNonincluded.add(reaction); } //identify isomers to remove Iterator iIter = pdn.getIsomers().iterator(); toRemoveIsomer = new HashSet(); while(iIter.hasNext()){ PDepIsomer pdi = (PDepIsomer)iIter.next(); Iterator isIter = pdi.getSpeciesListIterator(); while(isIter.hasNext()){ Species spe = (Species)isIter.next(); if (speciesToPrune.contains(spe)&&!toRemove.contains(pdi)) toRemoveIsomer.add(pdi); } if(pdi.getSpeciesList().size()==0 && !toRemove.contains(pdi)) toRemoveIsomer.add(pdi);//if the pdi doesn't contain any species, schedule it for removal } //remove path reactions Iterator iterRem = toRemovePath.iterator(); while(iterRem.hasNext()){ Reaction reaction = (Reaction)iterRem.next(); Reaction reverse = reaction.getReverseReaction(); pdn.removeFromPathReactionList((PDepReaction)reaction); pdn.removeFromPathReactionList((PDepReaction)reverse); // reaction and reverse are PDepReaction not TemplateReaction and don't what template they came from, if any. // so we have to go through them all and check. Iterator<ReactionTemplate> iterRT = ReactionTemplateLibrary.getINSTANCE().getReactionTemplate(); while (iterRT.hasNext()){ ReactionTemplate rt = (ReactionTemplate)iterRT.next(); if (rt.getReactionFromStructure(reaction.getStructure()) != null) { rt.removeFromReactionDictionaryByStructure(reaction.getStructure()); } if ((reverse != null) && (rt.getReactionFromStructure(reverse.getStructure()) != null)) { rt.removeFromReactionDictionaryByStructure(reverse.getStructure()); } } reaction.prune(); if (reverse != null) reverse.prune(); } //remove net reactions iterRem = toRemoveNet.iterator(); while(iterRem.hasNext()){ Reaction reaction = (Reaction)iterRem.next(); Reaction reverse = reaction.getReverseReaction(); pdn.removeFromNetReactionList((PDepReaction)reaction); pdn.removeFromNetReactionList((PDepReaction)reverse); reaction.prune(); if (reverse != null) reverse.prune(); } //remove nonincluded reactions iterRem = toRemoveNonincluded.iterator(); while(iterRem.hasNext()){ Reaction reaction = (Reaction)iterRem.next(); Reaction reverse = reaction.getReverseReaction(); pdn.removeFromNonincludedReactionList((PDepReaction)reaction); pdn.removeFromNonincludedReactionList((PDepReaction)reverse); reaction.prune(); if (reverse != null) reverse.prune(); } //remove isomers iterRem = toRemoveIsomer.iterator(); while(iterRem.hasNext()){ PDepIsomer pdi = (PDepIsomer)iterRem.next(); pdn.removeFromIsomerList(pdi); } //remove the entire network if the network has no path or net reactions if(pdn.getPathReactions().size()==0&&pdn.getNetReactions().size()==0) pdnToRemove.add(pdn); } iter = pdnToRemove.iterator(); while (iter.hasNext()){ PDepNetwork pdn = (PDepNetwork)iter.next(); PDepNetwork.getNetworks().remove(pdn); } } runtime.gc(); double memoryUsedAfterPruning = (runtime.totalMemory() - runtime.freeMemory()) / 1.0e6; Logger.info(String.format("Number of species pruned: %d", speciesToPrune.size())); Logger.info(String.format("Memory used before pruning: %10.2f MB", memoryUsedBeforePruning)); Logger.info(String.format("Memory used after pruning: %10.2f MB", memoryUsedAfterPruning)); if (memoryUsedAfterPruning < memoryUsedBeforePruning) Logger.info(String.format("Memory recovered by pruning: %10.2f MB", memoryUsedBeforePruning - memoryUsedAfterPruning)); else if (speciesToPrune.size() > 100) // There were a significant number of species pruned, but we didn't recover any memory Logger.warning("No memory recovered due to pruning!"); } //System.out.println("PDep Pruning DEBUG:\nThe number of species in the model's edge, after pruning: " + ((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber()); return; } //determines whether a reaction can be removed; returns true ; cf. categorizeReaction() in CoreEdgeReactionModel //returns true if the reaction involves reactants or products that are in p_prunableSpecies; otherwise returns false public boolean reactionPrunableQ(Reaction p_reaction, Collection p_prunableSpecies){ Iterator iter = p_reaction.getReactants(); while (iter.hasNext()) { Species spe = (Species)iter.next(); if (p_prunableSpecies.contains(spe)) return true; } iter = p_reaction.getProducts(); while (iter.hasNext()) { Species spe = (Species)iter.next(); if (p_prunableSpecies.contains(spe)) return true; } return false; } public boolean hasPrimaryKineticLibrary() { if (primaryKineticLibrary == null) return false; return (primaryKineticLibrary.size() > 0); } public boolean hasSeedMechanisms() { if (getSeedMechanism() == null) return false; return (seedMechanism.size() > 0); } //9/25/07 gmagoon: moved from ReactionSystem.java public PrimaryKineticLibrary getPrimaryKineticLibrary() { return primaryKineticLibrary; } //9/25/07 gmagoon: moved from ReactionSystem.java public void setPrimaryKineticLibrary(PrimaryKineticLibrary p_PrimaryKineticLibrary) { primaryKineticLibrary = p_PrimaryKineticLibrary; } public ReactionLibrary getReactionLibrary() { return ReactionLibrary; } public void setReactionLibrary(ReactionLibrary p_ReactionLibrary) { ReactionLibrary = p_ReactionLibrary; } //10/4/07 gmagoon: added public LinkedHashSet getSpeciesSeed() { return speciesSeed; } //10/4/07 gmagoon: added public void setSpeciesSeed(LinkedHashSet p_speciesSeed) { speciesSeed = p_speciesSeed; } //10/4/07 gmagoon: added public LibraryReactionGenerator getLibraryReactionGenerator() { return lrg; } //10/4/07 gmagoon: added public void setLibraryReactionGenerator(LibraryReactionGenerator p_lrg) { lrg = p_lrg; } public static Temperature getTemp4BestKinetics() { return temp4BestKinetics; } public static void setTemp4BestKinetics(Temperature firstSysTemp) { temp4BestKinetics = firstSysTemp; } public SeedMechanism getSeedMechanism() { return seedMechanism; } public void setSeedMechanism(SeedMechanism p_seedMechanism) { seedMechanism = p_seedMechanism; } public PrimaryThermoLibrary getPrimaryThermoLibrary() { return primaryThermoLibrary; } public void setPrimaryThermoLibrary(PrimaryThermoLibrary p_primaryThermoLibrary) { primaryThermoLibrary = p_primaryThermoLibrary; } public static double getAtol(){ return atol; } public boolean runKillableToPreventInfiniteLoop(boolean intermediateSteps, int iterationNumber) { ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0); if (!intermediateSteps)//if there are no intermediate steps (for example when using AUTO method), return true; return true; //if there are intermediate steps, the run is killable if the iteration number exceeds the number of time steps / conversions else if (rs0.finishController.terminationTester instanceof ReactionTimeTT){ if (iterationNumber - 1 > timeStep.size()){ //-1 correction needed since when this is called, iteration number has been incremented return true; } } else //the case where intermediate conversions are specified if (iterationNumber - 1 > numConversions){ //see above; it is possible there is an off-by-one error here, so further testing will be needed return true; } return false; //return false if none of the above criteria are met } public void readAndMakePKL(BufferedReader reader) throws IOException { int Ilib = 0; String line = ChemParser.readMeaningfulLine(reader, true); while (!line.equals("END")) { String[] tempString = line.split("Name: "); String name = tempString[tempString.length-1].trim(); line = ChemParser.readMeaningfulLine(reader, true); tempString = line.split("Location: "); String location = tempString[tempString.length-1].trim(); String path = System.getProperty("jing.rxn.ReactionLibrary.pathName"); path += "/" + location; if (Ilib==0) { setPrimaryKineticLibrary(new PrimaryKineticLibrary(name, path)); Ilib++; } else { getPrimaryKineticLibrary().appendPrimaryKineticLibrary(name, path); Ilib++; } line = ChemParser.readMeaningfulLine(reader, true); } if (Ilib==0) { setPrimaryKineticLibrary(null); } else Logger.info("Primary Kinetic Libraries in use: " + getPrimaryKineticLibrary().getName()); } public void readAndMakeReactionLibrary(BufferedReader reader) throws IOException { int Ilib = 0; String line = ChemParser.readMeaningfulLine(reader, true); while (!line.equals("END")) { String[] tempString = line.split("Name: "); String name = tempString[tempString.length-1].trim(); line = ChemParser.readMeaningfulLine(reader, true); tempString = line.split("Location: "); String location = tempString[tempString.length-1].trim(); String path = System.getProperty("jing.rxn.ReactionLibrary.pathName"); path += "/" + location; if (Ilib==0) { setReactionLibrary(new ReactionLibrary(name, path)); Ilib++; } else { getReactionLibrary().appendReactionLibrary(name, path); Ilib++; } line = ChemParser.readMeaningfulLine(reader, true); } if (Ilib==0) { setReactionLibrary(null); } else Logger.info("Reaction Libraries in use: " + getReactionLibrary().getName()); } public void readAndMakePTL(BufferedReader reader) { int numPTLs = 0; String line = ChemParser.readMeaningfulLine(reader, true); while (!line.equals("END")) { String[] tempString = line.split("Name: "); String name = tempString[tempString.length-1].trim(); line = ChemParser.readMeaningfulLine(reader, true); tempString = line.split("Location: "); String path = tempString[tempString.length-1].trim(); if (numPTLs==0) { setPrimaryThermoLibrary(new PrimaryThermoLibrary(name,path)); ++numPTLs; } else { getPrimaryThermoLibrary().appendPrimaryThermoLibrary(name,path); ++numPTLs; } line = ChemParser.readMeaningfulLine(reader, true); } if (numPTLs == 0) setPrimaryThermoLibrary(null); } public void readExtraForbiddenStructures(BufferedReader reader) throws IOException { Logger.info("Reading extra forbidden structures from input file."); String line = ChemParser.readMeaningfulLine(reader, true); while (!line.equals("END")) { StringTokenizer token = new StringTokenizer(line); String fgname = token.nextToken(); Graph fgGraph = null; try { fgGraph = ChemParser.readFGGraph(reader); } catch (InvalidGraphFormatException e) { Logger.error("Invalid functional group in "+fgname); throw new InvalidFunctionalGroupException(fgname + ": " + e.getMessage()); } if (fgGraph == null) throw new InvalidFunctionalGroupException(fgname); FunctionalGroup fg = FunctionalGroup.makeForbiddenStructureFG(fgname, fgGraph); ChemGraph.addForbiddenStructure(fg); line = ChemParser.readMeaningfulLine(reader, true); Logger.debug(" Forbidden structure: "+fgname); } } public void setSpectroscopicDataMode(String line) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String sdeType = st.nextToken().toLowerCase(); if (sdeType.equals("frequencygroups") || sdeType.equals("default")) { SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS; } else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) { SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY; } else if (sdeType.equals("off") || sdeType.equals("none")) { SpectroscopicData.mode = SpectroscopicData.Mode.OFF; } else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType); } /** * Sets the pressure dependence options to on or off. If on, checks for * more options and sets them as well. * @param line The current line in the condition file; should start with "PressureDependence:" * @param reader The reader currently being used to parse the condition file */ public String setPressureDependenceOptions(String line, BufferedReader reader) throws InvalidSymbolException { // Determine pressure dependence mode StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); // Should be "PressureDependence:" String pDepType = st.nextToken(); if (pDepType.toLowerCase().equals("off")) { // No pressure dependence reactionModelEnlarger = new RateBasedRME(); PDepNetwork.generateNetworks = false; /* * If the Spectroscopic Data Estimator field is set to "Frequency Groups," * terminate the RMG job and inform the user to either: * a) Set the Spectroscopic Data Estimator field to "off," OR * b) Select a pressure-dependent model * * Before, RMG would read in "Frequency Groups" with no pressure-dependence * and carry on. However, the calculated frequencies would not be stored / * reported (plus increase the runtime), so no point in calculating them. */ if (SpectroscopicData.mode != SpectroscopicData.mode.OFF) { System.err.println("Terminating RMG simulation: User requested frequency estimation, " + "yet no pressure-dependence.\nSUGGESTION: Set the " + "SpectroscopicDataEstimator field in the input file to 'off'."); System.exit(0); } line = ChemParser.readMeaningfulLine(reader, true); } else if (pDepType.toLowerCase().equals("modifiedstrongcollision") || pDepType.toLowerCase().equals("reservoirstate") || pDepType.toLowerCase().equals("chemdis")) { reactionModelEnlarger = new RateBasedPDepRME(); PDepNetwork.generateNetworks = true; // Set pressure dependence method if (pDepType.toLowerCase().equals("reservoirstate")) ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.RESERVOIRSTATE)); else if (pDepType.toLowerCase().equals("modifiedstrongcollision")) ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.STRONGCOLLISION)); //else if (pDepType.toLowerCase().equals("chemdis")) // ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new Chemdis()); else throw new InvalidSymbolException("condition.txt: Unknown PressureDependence mode = " + pDepType); RateBasedPDepRME pdepModelEnlarger = (RateBasedPDepRME) reactionModelEnlarger; // Turn on spectroscopic data estimation if not already on if (pdepModelEnlarger.getPDepKineticsEstimator() instanceof FastMasterEqn && SpectroscopicData.mode == SpectroscopicData.Mode.OFF) { Logger.warning("Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups."); SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS; } else if (pdepModelEnlarger.getPDepKineticsEstimator() instanceof Chemdis && SpectroscopicData.mode != SpectroscopicData.Mode.THREEFREQUENCY) { Logger.warning("Switching SpectroscopicDataEstimator to three-frequency model."); SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY; } // Next line must be PDepKineticsModel line = ChemParser.readMeaningfulLine(reader, true); if (line.toLowerCase().startsWith("pdepkineticsmodel:")) { st = new StringTokenizer(line); name = st.nextToken(); String pDepKinType = st.nextToken(); if (pDepKinType.toLowerCase().equals("chebyshev")) { PDepRateConstant.setMode(PDepRateConstant.Mode.CHEBYSHEV); // Default is to cubic order for basis functions FastMasterEqn.setNumTBasisFuncs(4); FastMasterEqn.setNumPBasisFuncs(4); } else if (pDepKinType.toLowerCase().equals("pdeparrhenius")) PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS); else if (pDepKinType.toLowerCase().equals("rate")) PDepRateConstant.setMode(PDepRateConstant.Mode.RATE); else throw new InvalidSymbolException("condition.txt: Unknown PDepKineticsModel = " + pDepKinType); // For Chebyshev polynomials, optionally specify the number of // temperature and pressure basis functions // Such a line would read, e.g.: "PDepKineticsModel: Chebyshev 4 4" if (st.hasMoreTokens() && PDepRateConstant.getMode() == PDepRateConstant.Mode.CHEBYSHEV) { try { int numTBasisFuncs = Integer.parseInt(st.nextToken()); int numPBasisFuncs = Integer.parseInt(st.nextToken()); FastMasterEqn.setNumTBasisFuncs(numTBasisFuncs); FastMasterEqn.setNumPBasisFuncs(numPBasisFuncs); } catch (NoSuchElementException e) { throw new InvalidSymbolException("condition.txt: Missing number of pressure basis functions for Chebyshev polynomials."); } } } else throw new InvalidSymbolException("condition.txt: Missing PDepKineticsModel after PressureDependence line."); // Determine temperatures and pressures to use // These can be specified automatically using TRange and PRange or // manually using Temperatures and Pressures Temperature[] temperatures = null; Pressure[] pressures = null; String Tunits = "K"; Temperature Tmin = new Temperature(300.0, "K"); Temperature Tmax = new Temperature(2000.0, "K"); int Tnumber = 8; String Punits = "bar"; Pressure Pmin = new Pressure(0.01, "bar"); Pressure Pmax = new Pressure(100.0, "bar"); int Pnumber = 5; // Read next line of input line = ChemParser.readMeaningfulLine(reader, true); boolean done = !(line.toLowerCase().startsWith("trange:") || line.toLowerCase().startsWith("prange:") || line.toLowerCase().startsWith("temperatures:") || line.toLowerCase().startsWith("pressures:")); // Parse lines containing pressure dependence options // Possible options are "TRange:", "PRange:", "Temperatures:", and "Pressures:" // You must specify either TRange or Temperatures and either PRange or Pressures // The order does not matter while (!done) { st = new StringTokenizer(line); name = st.nextToken(); if (line.toLowerCase().startsWith("trange:")) { Tunits = ChemParser.removeBrace(st.nextToken()); Tmin = new Temperature(Double.parseDouble(st.nextToken()), Tunits); Tmax = new Temperature(Double.parseDouble(st.nextToken()), Tunits); Tnumber = Integer.parseInt(st.nextToken()); } else if (line.toLowerCase().startsWith("prange:")) { Punits = ChemParser.removeBrace(st.nextToken()); Pmin = new Pressure(Double.parseDouble(st.nextToken()), Punits); Pmax = new Pressure(Double.parseDouble(st.nextToken()), Punits); Pnumber = Integer.parseInt(st.nextToken()); } else if (line.toLowerCase().startsWith("temperatures:")) { Tnumber = Integer.parseInt(st.nextToken()); Tunits = ChemParser.removeBrace(st.nextToken()); temperatures = new Temperature[Tnumber]; for (int i = 0; i < Tnumber; i++) { temperatures[i] = new Temperature(Double.parseDouble(st.nextToken()), Tunits); } Tmin = temperatures[0]; Tmax = temperatures[Tnumber-1]; } else if (line.toLowerCase().startsWith("pressures:")) { Pnumber = Integer.parseInt(st.nextToken()); Punits = ChemParser.removeBrace(st.nextToken()); pressures = new Pressure[Pnumber]; for (int i = 0; i < Pnumber; i++) { pressures[i] = new Pressure(Double.parseDouble(st.nextToken()), Punits); } Pmin = pressures[0]; Pmax = pressures[Pnumber-1]; } // Read next line of input line = ChemParser.readMeaningfulLine(reader, true); done = !(line.toLowerCase().startsWith("trange:") || line.toLowerCase().startsWith("prange:") || line.toLowerCase().startsWith("temperatures:") || line.toLowerCase().startsWith("pressures:")); } // Set temperatures and pressures (if not already set manually) if (temperatures == null) { temperatures = new Temperature[Tnumber]; if (PDepRateConstant.getMode() == PDepRateConstant.Mode.CHEBYSHEV) { // Use the Gauss-Chebyshev points // The formula for the Gauss-Chebyshev points was taken from // the Chemkin theory manual for (int i = 1; i <= Tnumber; i++) { double T = -Math.cos((2 * i - 1) * Math.PI / (2 * Tnumber)); T = 2.0 / ((1.0/Tmax.getK() - 1.0/Tmin.getK()) * T + 1.0/Tmax.getK() + 1.0/Tmin.getK()); temperatures[i-1] = new Temperature(T, "K"); } } else { // Distribute equally on a 1/T basis double slope = (1.0/Tmax.getK() - 1.0/Tmin.getK()) / (Tnumber - 1); for (int i = 0; i < Tnumber; i++) { double T = 1.0/(slope * i + 1.0/Tmin.getK()); temperatures[i] = new Temperature(T, "K"); } } } if (pressures == null) { pressures = new Pressure[Pnumber]; if (PDepRateConstant.getMode() == PDepRateConstant.Mode.CHEBYSHEV) { // Use the Gauss-Chebyshev points // The formula for the Gauss-Chebyshev points was taken from // the Chemkin theory manual for (int i = 1; i <= Pnumber; i++) { double P = -Math.cos((2 * i - 1) * Math.PI / (2 * Pnumber)); P = Math.pow(10, 0.5 * ((Math.log10(Pmax.getBar()) - Math.log10(Pmin.getBar())) * P + Math.log10(Pmax.getBar()) + Math.log10(Pmin.getBar()))); pressures[i-1] = new Pressure(P, "bar"); } } else { // Distribute equally on a log P basis double slope = (Math.log10(Pmax.getBar()) - Math.log10(Pmin.getBar())) / (Pnumber - 1); for (int i = 0; i < Pnumber; i++) { double P = Math.pow(10, slope * i + Math.log10(Pmin.getBar())); pressures[i] = new Pressure(P, "bar"); } } } FastMasterEqn.setTemperatures(temperatures); PDepRateConstant.setTemperatures(temperatures); PDepRateConstant.setTMin(Tmin); PDepRateConstant.setTMax(Tmax); ChebyshevPolynomials.setTlow(Tmin); ChebyshevPolynomials.setTup(Tmax); FastMasterEqn.setPressures(pressures); PDepRateConstant.setPressures(pressures); PDepRateConstant.setPMin(Pmin); PDepRateConstant.setPMax(Pmax); ChebyshevPolynomials.setPlow(Pmin); ChebyshevPolynomials.setPup(Pmax); /* * New option for input file: DecreaseGrainSize * User now has the option to re-run fame with additional grains * (smaller grain size) when the p-dep rate exceeds the * high-P-limit rate. * Default value: off */ if (line.toLowerCase().startsWith("decreasegrainsize")) { st = new StringTokenizer(line); String tempString = st.nextToken(); // "DecreaseGrainSize:" tempString = st.nextToken().trim().toLowerCase(); if (tempString.equals("on") || tempString.equals("yes") || tempString.equals("true")) { rerunFame = true; } else rerunFame = false; line = ChemParser.readMeaningfulLine(reader, true); } } else { throw new InvalidSymbolException("condition.txt: Unknown PressureDependence = " + pDepType); } return line; } public void createTModel(String line) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String modelType = st.nextToken(); String unit = st.nextToken(); unit = ChemParser.removeBrace(unit); if (modelType.equals("Constant")) { tempList = new LinkedList(); //read first temperature double t = Double.parseDouble(st.nextToken()); tempList.add(new ConstantTM(t, unit)); Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature Global.lowTemperature = (Temperature)temp.clone(); Global.highTemperature = (Temperature)temp.clone(); //read remaining temperatures while (st.hasMoreTokens()) { t = Double.parseDouble(st.nextToken()); tempList.add(new ConstantTM(t, unit)); temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature if(temp.getK() < Global.lowTemperature.getK()) Global.lowTemperature = (Temperature)temp.clone(); if(temp.getK() > Global.highTemperature.getK()) Global.highTemperature = (Temperature)temp.clone(); } } else { throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType); } } public void createPModel(String line) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String modelType = st.nextToken(); String unit = st.nextToken(); unit = ChemParser.removeBrace(unit); if (modelType.equals("Constant")) { presList = new LinkedList(); //read first pressure double p = Double.parseDouble(st.nextToken()); Pressure pres = new Pressure(p, unit); Global.lowPressure = (Pressure)pres.clone(); Global.highPressure = (Pressure)pres.clone(); presList.add(new ConstantPM(p, unit)); //read remaining temperatures while (st.hasMoreTokens()) { p = Double.parseDouble(st.nextToken()); presList.add(new ConstantPM(p, unit)); pres = new Pressure(p, unit); if(pres.getBar() < Global.lowPressure.getBar()) Global.lowPressure = (Pressure)pres.clone(); if(pres.getBar() > Global.lowPressure.getBar()) Global.highPressure = (Pressure)pres.clone(); } } else { throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType); } } public LinkedHashMap populateInitialStatusListWithReactiveSpecies(BufferedReader reader) throws IOException { LinkedHashMap speciesSet = new LinkedHashMap(); LinkedHashMap speciesStatus = new LinkedHashMap(); LinkedHashMap speciesFromInputFileSet = new LinkedHashMap(); int numSpeciesStatus = 0; String line = ChemParser.readMeaningfulLine(reader, true); while (!line.equals("END")) { StringTokenizer st = new StringTokenizer(line); String index = st.nextToken(); String name = null; if (!index.startsWith("(")) name = index; else name = st.nextToken(); //if (restart) name += "("+speciesnum+")"; // 24Jun2009: MRH // Check if the species name begins with a number. // If so, terminate the program and inform the user to choose // a different name. This is implemented so that the chem.inp // file generated will be valid when run in Chemkin try { int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1)); Logger.critical("\nA species name should not begin with a number." + " Please rename species: " + name + "\n"); System.exit(0); } catch (NumberFormatException e) { // We're good } if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name); // The next token will be the concentration units String unit = st.nextToken(); unit = ChemParser.removeBrace(unit); // Read in the graph (and make the species) before we parse all of the concentrations // Will store each SpeciesStatus (NXM where N is the # of species and M is the # of // concentrations) in a LinkedHashMap, with a (int) counter as the unique key Graph g = ChemParser.readChemGraph(reader); ChemGraph cg = null; try { cg = ChemGraph.make(g); } catch (ForbiddenStructureException e) { Logger.error("Forbidden Structure:\n" + e.getMessage()); throw new InvalidSymbolException("A species in the input file has a forbidden structure."); } //System.out.println(name); // Check to see if chemgraph already appears in the input file addChemGraphToListIfNotPresent_ElseTerminate(speciesFromInputFileSet,cg,name); Species species = Species.make(name,cg); int numConcentrations = 0; // The number of concentrations read-in for each species // The remaining tokens are either: // The desired concentrations // The flag "unreactive" // The flag "constantconcentration" //GJB to allow "unreactive" species that only follow user-defined library reactions. // They will not react according to RMG reaction families boolean IsReactive = true; boolean IsConstantConcentration = false; double concentration = 0.0; while (st.hasMoreTokens()) { String reactive = st.nextToken().trim(); if (reactive.equalsIgnoreCase("unreactive")) IsReactive = false; else if (reactive.equalsIgnoreCase("constantconcentration")) IsConstantConcentration=true; else { try { concentration = Double.parseDouble(reactive); } catch (NumberFormatException e) { System.out.println(String.format("Unable to read concentration value '%s'. Check syntax of input line '%s'.",reactive,line)); throw e; } if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) { concentration /= 1000; unit = "mol/cm3"; } else if (unit.equals("mole/m3") || unit.equals("mol/m3")) { concentration /= 1000000; unit = "mol/cm3"; } else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) { concentration /= 6.022e23; } else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) { System.out.println(String.format("Unable to read concentration units '%s'. Check syntax of input line '%s'.",unit,line)); throw new InvalidUnitException("Species Concentration in condition.txt!"); } SpeciesStatus ss = new SpeciesStatus(species,1,concentration,0.0); speciesStatus.put(numSpeciesStatus, ss); ++numSpeciesStatus; ++numConcentrations; } } // Check if the number of concentrations read in is consistent with all previous // concentration counts. The first time this function is called, the variable // numberOfEquivalenceRatios will be initialized. boolean goodToGo = areTheNumberOfConcentrationsConsistent(numConcentrations); if (!goodToGo) { Logger.critical("\n\nThe number of concentrations (" + numConcentrations + ") supplied for species " + species.getName() + "\nis not consistent with the number of concentrations (" + numberOfEquivalenceRatios + ") " + "supplied for all previously read-in species \n\n" + "Terminating RMG simulation."); System.exit(0); } // Make a SpeciesStatus and store it in the LinkedHashMap // double flux = 0; // int species_type = 1; // reacted species species.setReactivity(IsReactive); // GJB species.setConstantConcentration(IsConstantConcentration); speciesSet.put(name, species); getSpeciesSeed().add(species); line = ChemParser.readMeaningfulLine(reader, true); } ReactionTime initial = new ReactionTime(0,"S"); //10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem initialStatusList = new LinkedList(); for (Iterator iter = tempList.iterator(); iter.hasNext(); ) { TemperatureModel tm = (TemperatureModel)iter.next(); for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){ PressureModel pm = (PressureModel)iter2.next(); // LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all) // Set ks = speciesStatus.keySet(); // for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?) int reactionSystemCounter = 0; for (int totalConcs=0; totalConcs<numSpeciesStatus/speciesSet.size(); ++totalConcs) { LinkedHashMap speStat = new LinkedHashMap(); for (int totalSpecs=0; totalSpecs<speciesSet.size(); ++totalSpecs) { SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(totalConcs+totalSpecs*numSpeciesStatus/speciesSet.size()); String blah = ssCopy.getSpecies().getName(); speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux())); } initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial))); } } } return speciesSet; } public void populateInitialStatusListWithInertSpecies(BufferedReader reader) { String line = ChemParser.readMeaningfulLine(reader, true); while (!line.equals("END")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken().trim(); // The next token is the units of concentration String unit = st.nextToken(); unit = ChemParser.removeBrace(unit); // The remaining tokens are concentrations double inertConc = 0.0; int counter = 0; int numberOfConcentrations = 0; while (st.hasMoreTokens()) { String conc = st.nextToken(); inertConc = Double.parseDouble(conc); if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) { inertConc /= 1000; unit = "mol/cm3"; } else if (unit.equals("mole/m3") || unit.equals("mol/m3")) { inertConc /= 1000000; unit = "mol/cm3"; } else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) { inertConc /= 6.022e23; unit = "mol/cm3"; } else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) { throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit); } //SystemSnapshot.putInertGas(name,inertConc); // for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc // ((InitialStatus)iter.next()).putInertGas(name,inertConc); int numberOfDiffTP = tempList.size() * presList.size(); for (int isIndex=counter; isIndex<initialStatusList.size(); isIndex+=initialStatusList.size()/numberOfDiffTP) { InitialStatus is = ((InitialStatus)initialStatusList.get(isIndex)); ((InitialStatus)initialStatusList.get(isIndex)).putInertGas(name,inertConc); } ++counter; ++numberOfConcentrations; } // Check if the number of concentrations read in is consistent with all previous // concentration counts. The first time this function is called, the variable // numberOfEquivalenceRatios will be initialized. boolean goodToGo = areTheNumberOfConcentrationsConsistent(numberOfConcentrations); if (!goodToGo) { Logger.critical("\n\nThe number of concentrations (" + numberOfConcentrations + ") supplied for species " + name + "\nis not consistent with the number of concentrations (" + numberOfEquivalenceRatios + ") " + "supplied for all previously read-in species \n\n" + "Terminating RMG simulation."); System.exit(0); } line = ChemParser.readMeaningfulLine(reader, true); } } public String readMaxAtomTypes(String line, BufferedReader reader) { if (line.startsWith("MaxCarbonNumber")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:" int maxCNum = Integer.parseInt(st.nextToken()); ChemGraph.setMaxCarbonNumber(maxCNum); Logger.info("Note: Overriding default MAX_CARBON_NUM with user-defined value: " + maxCNum); line = ChemParser.readMeaningfulLine(reader, true); } if (line.startsWith("MaxOxygenNumber")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:" int maxONum = Integer.parseInt(st.nextToken()); ChemGraph.setMaxOxygenNumber(maxONum); Logger.info("Note: Overriding default MAX_OXYGEN_NUM with user-defined value: " + maxONum); line = ChemParser.readMeaningfulLine(reader, true); } if (line.startsWith("MaxRadicalNumber")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:" int maxRadNum = Integer.parseInt(st.nextToken()); ChemGraph.setMaxRadicalNumber(maxRadNum); Logger.info("Note: Overriding default MAX_RADICAL_NUM with user-defined value: " + maxRadNum); line = ChemParser.readMeaningfulLine(reader, true); } if (line.startsWith("MaxSulfurNumber")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:" int maxSNum = Integer.parseInt(st.nextToken()); ChemGraph.setMaxSulfurNumber(maxSNum); Logger.info("Note: Overriding default MAX_SULFUR_NUM with user-defined value: " + maxSNum); line = ChemParser.readMeaningfulLine(reader, true); } if (line.startsWith("MaxSiliconNumber")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:" int maxSiNum = Integer.parseInt(st.nextToken()); ChemGraph.setMaxSiliconNumber(maxSiNum); Logger.info("Note: Overriding default MAX_SILICON_NUM with user-defined value: " + maxSiNum); line = ChemParser.readMeaningfulLine(reader, true); } if (line.startsWith("MaxHeavyAtom")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:" int maxHANum = Integer.parseInt(st.nextToken()); ChemGraph.setMaxHeavyAtomNumber(maxHANum); Logger.info("Note: Overriding default MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum); line = ChemParser.readMeaningfulLine(reader, true); } if (line.startsWith("MaxCycleNumber")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // This should hold "MaxCycleNumberPerSpecies:" int maxCycleNum = Integer.parseInt(st.nextToken()); ChemGraph.setMaxCycleNumber(maxCycleNum); Logger.info("Note: Overriding default MAX_CYCLE_NUM with user-defined value: " + maxCycleNum); line = ChemParser.readMeaningfulLine(reader, true); } return line; } public ReactionModelEnlarger getReactionModelEnlarger() { return reactionModelEnlarger; } public LinkedList getTempList() { return tempList; } public LinkedList getPressList() { return presList; } public LinkedList getInitialStatusList() { return initialStatusList; } public void writeBackupRestartFiles(String[] listOfFiles) { for (int i=0; i<listOfFiles.length; i++) { File temporaryRestartFile = new File(listOfFiles[i]); if (temporaryRestartFile.exists()) temporaryRestartFile.renameTo(new File(listOfFiles[i]+"~")); } } public void removeBackupRestartFiles(String[] listOfFiles) { for (int i=0; i<listOfFiles.length; i++) { File temporaryRestartFile = new File(listOfFiles[i]+"~"); temporaryRestartFile.delete(); } } public static boolean rerunFameWithAdditionalGrains() { return rerunFame; } public void setLimitingReactantID(int id) { limitingReactantID = id; } public int getLimitingReactantID() { return limitingReactantID; } public void readAndMakePTransL(BufferedReader reader) { int numPTLs = 0; String line = ChemParser.readMeaningfulLine(reader, true); while (!line.equals("END")) { String[] tempString = line.split("Name: "); String name = tempString[tempString.length-1].trim(); line = ChemParser.readMeaningfulLine(reader, true); tempString = line.split("Location: "); String path = tempString[tempString.length-1].trim(); if (numPTLs==0) { setPrimaryTransportLibrary(new PrimaryTransportLibrary(name,path)); ++numPTLs; } else { getPrimaryTransportLibrary().appendPrimaryTransportLibrary(name,path); ++numPTLs; } line = ChemParser.readMeaningfulLine(reader, true); } if (numPTLs == 0) setPrimaryTransportLibrary(null); } //Added by Amrit Jalan on December 21, 2010 public void readAndMakePAL() { String name = "primaryAbrahamLibrary"; String path = "primaryAbrahamLibrary"; setPrimaryAbrahamLibrary(new PrimaryAbrahamLibrary(name,path)); getPrimaryAbrahamLibrary().appendPrimaryAbrahamLibrary(name,path); } public void readAndMakeSL(String solventname) { String name = "SolventLibrary"; String path = "SolventLibrary"; setSolventLibrary(new SolventLibrary(name,path)); // the constructor with (name,path) reads in the library at construction time. SolventData solvent = getSolventLibrary().getSolventData(solventname); setSolvent(solvent); } public PrimaryTransportLibrary getPrimaryTransportLibrary() { return primaryTransportLibrary; } public void setPrimaryTransportLibrary(PrimaryTransportLibrary p_primaryTransportLibrary) { primaryTransportLibrary = p_primaryTransportLibrary; } public PrimaryAbrahamLibrary getPrimaryAbrahamLibrary() { return primaryAbrahamLibrary; } public static SolventData getSolvent() { return solvent; } public static double getViscosity() { return viscosity; } public SolventLibrary getSolventLibrary() { return solventLibrary; } public void setPrimaryAbrahamLibrary(PrimaryAbrahamLibrary p_primaryAbrahamLibrary) { primaryAbrahamLibrary = p_primaryAbrahamLibrary; } public void setSolventLibrary(SolventLibrary p_solventLibrary) { solventLibrary = p_solventLibrary; } public void setSolvent(SolventData p_solvent) { solvent = p_solvent; } /** * Print the current numbers of core and edge species and reactions to the * console. */ public void printModelSize() { CoreEdgeReactionModel cerm = (CoreEdgeReactionModel) getReactionModel(); int numberOfCoreSpecies = cerm.getReactedSpeciesSet().size(); int numberOfEdgeSpecies = cerm.getUnreactedSpeciesSet().size(); int numberOfCoreReactions = 0; int numberOfEdgeReactions = 0; double count = 0.0; for (Iterator iter = cerm.getReactedReactionSet().iterator(); iter.hasNext(); ) { Reaction rxn = (Reaction) iter.next(); // The model core stores reactions in both directions // To avoid double-counting we must count each of these as 1/2 if (rxn.hasReverseReaction()) count += 0.5; else count += 1; } numberOfCoreReactions = (int) Math.round(count); count = 0.0; for (Iterator iter = cerm.getUnreactedReactionSet().iterator(); iter.hasNext(); ) { Reaction rxn = (Reaction) iter.next(); // The model edge stores reactions in only one direction, so each // edge reaction counts as 1 count += 1; } numberOfEdgeReactions = (int) Math.round(count); if (reactionModelEnlarger instanceof RateBasedPDepRME) { numberOfCoreReactions += PDepNetwork.getNumCoreReactions(cerm); numberOfEdgeReactions += PDepNetwork.getNumEdgeReactions(cerm); } Logger.info(""); Logger.info("The model core has " + Integer.toString(numberOfCoreReactions) + " reactions and "+ Integer.toString(numberOfCoreSpecies) + " species."); Logger.info("The model edge has " + Integer.toString(numberOfEdgeReactions) + " reactions and "+ Integer.toString(numberOfEdgeSpecies) + " species."); // If pressure dependence is on, print some information about the networks if (reactionModelEnlarger instanceof RateBasedPDepRME) { int numberOfNetworks = PDepNetwork.getNetworks().size(); int numberOfPathReactions = PDepNetwork.getNumPathReactions(cerm); int numberOfNetReactions = PDepNetwork.getNumNetReactions(cerm); Logger.info("There are " + Integer.toString(numberOfNetworks) + " partial pressure-dependent networks containing " + Integer.toString(numberOfPathReactions) + " path and " + Integer.toString(numberOfNetReactions) + " net reactions."); } } public boolean areTheNumberOfConcentrationsConsistent(int number) { if (numberOfEquivalenceRatios == 0) numberOfEquivalenceRatios = number; else { if (number == numberOfEquivalenceRatios) return true; else return false; } return true; } public LinkedHashSet extractSeedMechRxnsIfTheyExist() { LinkedHashSet seedmechnonpdeprxns = new LinkedHashSet(); if (seedMechanism != null) seedmechnonpdeprxns = seedMechanism.getReactionSet(); return seedmechnonpdeprxns; } public static void addChemGraphToListIfNotPresent_ElseTerminate(LinkedHashMap speciesMap, ChemGraph cg, String name) { if (speciesMap.containsKey(cg)) { Logger.error("The same ChemGraph appears multiple times in the user-specified input file\n" + "Species " + name + " has the same ChemGraph as " + (speciesMap.get(cg))); System.exit(0); } else speciesMap.put(cg, name); } }
package net.winstone.core; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.winstone.core.listener.Listener; import net.winstone.core.listener.RequestHandlerThread; import net.winstone.util.StringUtils; import org.slf4j.LoggerFactory; /** * Holds the object pooling code for Winstone. Presently this is only responses * and requests, but may increase. * * @author <a href="mailto:rick_knowles@hotmail.com">Rick Knowles</a> * @version $Id: ObjectPool.java,v 1.9 2006/11/18 14:56:59 rickknowles Exp $ */ public class ObjectPool { protected static org.slf4j.Logger logger = LoggerFactory.getLogger(ObjectPool.class); /** * FLUSH PERIOD 60 second. */ private static final long FLUSH_PERIOD = 60000L; /** * Default startup request handler in pool (5). */ private final static transient int STARTUP_REQUEST_HANDLERS_IN_POOL = 5; /** * Maximum idle request handler in pool (50). */ private final static transient int MAX_IDLE_REQUEST_HANDLERS_IN_POOL = 50; /** * Maximum request handler in pool (1000). */ private final static transient int MAX_REQUEST_HANDLERS_IN_POOL = 1000; /** * Retry period (1 second). */ private final static transient long RETRY_PERIOD = 1000; /** * Start requests in pool (10). */ private final static transient int START_REQUESTS_IN_POOL = 10; /** * Max requests in pool (1000). */ private final static transient int MAX_REQUESTS_IN_POOL = 1000; /** * Start responses in pool (10). */ private final static transient int START_RESPONSES_IN_POOL = 10; /** * Maximum responses in pool (1000). */ private final static transient int MAX_RESPONSES_IN_POOL = 1000; private final List<RequestHandlerThread> unusedRequestHandlerThreads; private final List<RequestHandlerThread> usedRequestHandlerThreads; private final List<WinstoneRequest> unusedRequestPool; private final List<WinstoneResponse> unusedResponsePool; private final Object requestHandlerSemaphore = Boolean.TRUE; private final Object requestPoolSemaphore = Boolean.TRUE; private final Object responsePoolSemaphore = Boolean.TRUE; private int threadIndex = 0; private final boolean simulateModUniqueId; private final boolean saveSessions; private Thread thread; int startupRequest = ObjectPool.STARTUP_REQUEST_HANDLERS_IN_POOL; int maxRequestHandlesInPool = ObjectPool.MAX_REQUEST_HANDLERS_IN_POOL; int maxIdleRequestHandlesInPool = ObjectPool.MAX_IDLE_REQUEST_HANDLERS_IN_POOL; /** * max number of parameters allowed. */ private static int MAXPARAMALLOWED = WinstoneConstant.DEFAULT_MAXIMUM_PARAMETER_ALLOWED; /** * Constructs an instance of the object pool, including handlers, requests * and responses */ public ObjectPool(final Map<String, String> args) throws IOException { super(); // load simulateModUniqueId simulateModUniqueId = StringUtils.booleanArg(args, "simulateModUniqueId", Boolean.FALSE); // load maxParamAllowed int maxParamAllowed = StringUtils.intArg(args, "maxParamAllowed", WinstoneConstant.DEFAULT_MAXIMUM_PARAMETER_ALLOWED); if (maxParamAllowed < 1) { logger.error("MaxParamAllowed should be greather than 1. Set to default value {}", WinstoneConstant.DEFAULT_MAXIMUM_PARAMETER_ALLOWED); maxParamAllowed = WinstoneConstant.DEFAULT_MAXIMUM_PARAMETER_ALLOWED; } ObjectPool.MAXPARAMALLOWED = maxParamAllowed; // load saveSessions saveSessions = WebAppConfiguration.useSavedSessions(args); // Build the initial pool of handler threads unusedRequestHandlerThreads = new ArrayList<RequestHandlerThread>(); usedRequestHandlerThreads = new ArrayList<RequestHandlerThread>(); // Build the request/response pools unusedRequestPool = new ArrayList<WinstoneRequest>(); unusedResponsePool = new ArrayList<WinstoneResponse>(); // Get handler pool options startupRequest = StringUtils.intArg(args, "handlerCountStartup", ObjectPool.STARTUP_REQUEST_HANDLERS_IN_POOL); maxRequestHandlesInPool = StringUtils.intArg(args, "handlerCountMax", ObjectPool.MAX_REQUEST_HANDLERS_IN_POOL); maxIdleRequestHandlesInPool = StringUtils.intArg(args, "handlerCountMaxIdle", ObjectPool.MAX_IDLE_REQUEST_HANDLERS_IN_POOL); // Start the base set of handler threads for (int n = 0; n < startupRequest; n++) { unusedRequestHandlerThreads.add(new RequestHandlerThread(this, threadIndex++, simulateModUniqueId, saveSessions)); } // Initialize the request/response pools for (int n = 0; n < ObjectPool.START_REQUESTS_IN_POOL; n++) { unusedRequestPool.add(new WinstoneRequest(ObjectPool.MAXPARAMALLOWED)); } for (int n = 0; n < ObjectPool.START_RESPONSES_IN_POOL; n++) { unusedResponsePool.add(new WinstoneResponse()); } thread = new Thread(new Runnable() { /** * Every 60s, remove unused request handler. * * @see java.lang.Runnable#run() */ @Override public void run() { boolean interrupted = Boolean.FALSE; while (!interrupted) { try { Thread.sleep(ObjectPool.FLUSH_PERIOD); removeUnusedRequestHandlers(); } catch (final InterruptedException err) { interrupted = Boolean.TRUE; } } thread = null; } }, "WinstoneObjectPoolMgmt"); thread.setDaemon(Boolean.TRUE); thread.start(); } /** * remove Unused RequestHandlers. */ private void removeUnusedRequestHandlers() { // Check max idle requestHandler count synchronized (requestHandlerSemaphore) { // If we have too many idle request handlers while (unusedRequestHandlerThreads.size() > maxIdleRequestHandlesInPool) { final RequestHandlerThread rh = unusedRequestHandlerThreads.get(0); rh.destroy(); unusedRequestHandlerThreads.remove(rh); } } } /** * Destroy Object Pool. */ public void destroy() { synchronized (requestHandlerSemaphore) { List<RequestHandlerThread> handlerThreads = new ArrayList<RequestHandlerThread>(usedRequestHandlerThreads); for (final RequestHandlerThread handlerThread : handlerThreads) { releaseRequestHandler(handlerThread); } handlerThreads = new ArrayList<RequestHandlerThread>(unusedRequestHandlerThreads); for (final RequestHandlerThread handlerThread : handlerThreads) { handlerThread.destroy(); } unusedRequestHandlerThreads.clear(); } if (thread != null) { thread.interrupt(); } } /** * Once the socket request comes in, this method is called. It reserves a * request handler, then delegates the socket to that class. When it * finishes, the handler is released back into the pool. */ public void handleRequest(final Socket socket, final Listener listener) throws IOException, InterruptedException { RequestHandlerThread rh = null; synchronized (requestHandlerSemaphore) { // If we have any spare, get it from the pool final int unused = unusedRequestHandlerThreads.size(); if (unused > 0) { rh = unusedRequestHandlerThreads.remove(unused - 1); usedRequestHandlerThreads.add(rh); ObjectPool.logger.debug("RHPool: Using pooled handler thread - used: {} unused: {}", "" + usedRequestHandlerThreads.size(), "" + unusedRequestHandlerThreads.size()); } // If we are out (and not over our limit), allocate a new one else if (usedRequestHandlerThreads.size() < ObjectPool.MAX_REQUEST_HANDLERS_IN_POOL) { rh = new RequestHandlerThread(this, threadIndex++, simulateModUniqueId, saveSessions); usedRequestHandlerThreads.add(rh); ObjectPool.logger.debug("RHPool: Spawning new handler thread - used: {} unused: {}]", "" + usedRequestHandlerThreads.size(), "" + unusedRequestHandlerThreads.size()); } // otherwise throw fail message - we've blown our limit else { // Possibly insert a second chance here ? Delay and one retry ? // Remember to release the lock first ObjectPool.logger.warn("WARNING: Request handler pool limit exceeded - waiting for retry"); // socket.close(); // throw new UnavailableException("NoHandlersAvailable"); } } if (rh != null) { rh.commenceRequestHandling(socket, listener); } else { // Sleep for a set period and try again from the pool Thread.sleep(ObjectPool.RETRY_PERIOD); synchronized (requestHandlerSemaphore) { if (usedRequestHandlerThreads.size() < ObjectPool.MAX_REQUEST_HANDLERS_IN_POOL) { rh = new RequestHandlerThread(this, threadIndex++, simulateModUniqueId, saveSessions); usedRequestHandlerThreads.add(rh); ObjectPool.logger.debug("RHPool: Spawning new handler thread - used: {} unused: {}", "" + usedRequestHandlerThreads.size(), "" + unusedRequestHandlerThreads.size()); } } if (rh != null) { rh.commenceRequestHandling(socket, listener); } else { ObjectPool.logger.error("Request ignored because there were no more request handlers available in the pool"); socket.close(); } } } /** * Release the handler back into the pool */ public void releaseRequestHandler(final RequestHandlerThread rh) { synchronized (requestHandlerSemaphore) { usedRequestHandlerThreads.remove(rh); unusedRequestHandlerThreads.add(rh); ObjectPool.logger.debug("RHPool: Releasing handler thread - used: {} unused: {}", "" + usedRequestHandlerThreads.size(), "" + unusedRequestHandlerThreads.size()); } } /** * An attempt at pooling request objects for reuse. * * @return a WinstoneRequest instance. */ public WinstoneRequest getRequestFromPool() throws IOException { WinstoneRequest winstoneRequest = null; synchronized (requestPoolSemaphore) { // If we have any spare, get it from the pool final int unused = unusedRequestPool.size(); if (unused > 0) { winstoneRequest = unusedRequestPool.remove(unused - 1); ObjectPool.logger.debug("ReqPool: Using pooled request - available: {}", "" + unusedRequestPool.size()); } else { // If we are out, allocate a new one winstoneRequest = new WinstoneRequest(MAXPARAMALLOWED); ObjectPool.logger.debug("ReqPool: Spawning new request - available: {}", "" + unusedRequestPool.size()); } } return winstoneRequest; } /** * Release specified request to pool. Add it to unused if pool size is under * the limit of MAX_REQUESTS_IN_POOL objects. * * @param winstoneRequest * winstone Request */ public void releaseRequestToPool(final WinstoneRequest winstoneRequest) { winstoneRequest.cleanUp(); synchronized (requestPoolSemaphore) { if (unusedRequestPool.size() < ObjectPool.MAX_REQUESTS_IN_POOL) { unusedRequestPool.add(winstoneRequest); } ObjectPool.logger.debug("ReqPool: Request released - available: {}", "" + unusedRequestPool.size()); } } /** * An attempt at pooling request objects for reuse. * * @return a WinstoneResponse instance. */ public WinstoneResponse getResponseFromPool() throws IOException { WinstoneResponse rsp = null; synchronized (responsePoolSemaphore) { // If we have any spare, get it from the pool final int unused = unusedResponsePool.size(); if (unused > 0) { rsp = unusedResponsePool.remove(unused - 1); ObjectPool.logger.debug("RspPool: Using pooled response - available: {}", "" + unusedResponsePool.size()); } // If we are out, allocate a new one else { rsp = new WinstoneResponse(); ObjectPool.logger.debug("RspPool: Spawning new response - available: {}", "" + unusedResponsePool.size()); } } return rsp; } /** * Release WinstoneResponse instance. Add it to unused if pool size is under * the limit of MAX_REQUESTS_IN_POOL objects. * * @param winstoneResponse */ public void releaseResponseToPool(final WinstoneResponse winstoneResponse) { winstoneResponse.cleanUp(); synchronized (responsePoolSemaphore) { if (unusedResponsePool.size() < ObjectPool.MAX_RESPONSES_IN_POOL) { unusedResponsePool.add(winstoneResponse); } ObjectPool.logger.debug("RspPool: Response released - available: {}", "" + unusedResponsePool.size()); } } /** * * @return maximum Parameter Allowed. */ public static int getMaximumAllowedParameter() { return MAXPARAMALLOWED; } }
package com.thaiopensource.xml.dtd; import java.io.Reader; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; import java.util.Enumeration; /* TODO Need to ensure newline normalization is done properly. Don't unexpand entities that are not properly nested. */ public class Parser extends Token { private Parser parent; private Reader in; private char[] buf; private int bufStart = 0; private int bufEnd; private int currentTokenStart = 0; // The offset in buffer corresponding to pos. private int posOff = 0; private long bufEndStreamOffset = 0; private Position pos = new Position(); private static final int READSIZE = 1024*8; // Some temporary buffers private ReplacementTextBuffer valueBuf; private Hashtable paramEntityTable; private Vector atoms = new Vector(); static class Atom { private int tokenType; private String token; private EntityImpl entity; Atom(EntityImpl entity) { this.entity = entity; this.tokenType = -1; this.token = null; } Atom(int tokenType, String token) { this.tokenType = tokenType; this.token = token; } final int getTokenType() { return tokenType; } final String getToken() { return token; } final EntityImpl getEntity() { return entity; } void setEntity(EntityImpl entity) { this.entity = entity; } public int hashCode() { return token.hashCode(); } public boolean equals(Object obj) { if (obj == null || !(obj instanceof Atom)) return false; Atom other = (Atom)obj; if (this.entity != null) return this.entity == other.entity; else return this.tokenType == other.tokenType && this.token.equals(other.token); } } static class EntityImpl { final String name; EntityImpl(String name) { this.name = name; } char[] text; // Which parts of text came from references? EntityReference[] references; boolean open; String notationName; Vector atoms; boolean mustReparse; int textIndexToAtomIndex(int ti) { int nAtoms = atoms.size(); int len = 0; int atomIndex = 0; for (;;) { if (len == ti) return atomIndex; if (atomIndex >= nAtoms) break; Atom a = (Atom)atoms.elementAt(atomIndex); len += a.getToken().length(); if (len > ti) break; atomIndex++; } return -1; } void unexpandEntities() { if (references == null || atoms == null) return; Vector newAtoms = null; int nCopiedAtoms = 0; for (int i = 0; i < references.length; i++) { int start = textIndexToAtomIndex(references[i].start); int end = textIndexToAtomIndex(references[i].end); if (start >= 0 && end >= 0) { if (newAtoms == null) newAtoms = new Vector(); appendSlice(newAtoms, atoms, nCopiedAtoms, start); newAtoms.addElement(new Atom(references[i].entity)); if (references[i].entity.atoms == null) { Vector tem = new Vector(); references[i].entity.atoms = tem; appendSlice(tem, atoms, start, end); references[i].entity.unexpandEntities(); } nCopiedAtoms = end; } else { System.err.println("Warning: could not preserve reference to entity \"" + references[i].entity.name + "\" in entity \"" + this.name + "\""); } } if (newAtoms == null) return; appendSlice(newAtoms, atoms, nCopiedAtoms, atoms.size()); atoms = newAtoms; references = null; } static void appendSlice(Vector to, Vector from, int start, int end) { for (; start < end; start++) to.addElement(from.elementAt(start)); } } static class DeclState { EntityImpl entity; } static class EntityReference { EntityReference(EntityImpl entity, int start, int end) { this.entity = entity; this.start = start; this.end = end; } EntityImpl entity; int start; int end; } static class ReplacementTextBuffer { private static final int INIT_SIZE = 64; private char[] buf = new char[INIT_SIZE]; private int len; private boolean mustReparse = false; private EntityReference[] refs = new EntityReference[2]; int nRefs; public void clear() { len = 0; mustReparse = false; nRefs = 0; } public void setMustReparse() { mustReparse = true; } public boolean getMustReparse() { return mustReparse; } public void appendReplacementText(EntityImpl entity) { appendEntityReference(new EntityReference(entity, len, len + entity.text.length)); append(entity.text, 0, entity.text.length); } private void appendEntityReference(EntityReference r) { if (nRefs == refs.length) { EntityReference[] tem = refs; refs = new EntityReference[tem.length << 1]; System.arraycopy(tem, 0, refs, 0, tem.length); } refs[nRefs++] = r; } public EntityReference[] getReferences() { if (nRefs == 0) return null; EntityReference[] r = new EntityReference[nRefs]; System.arraycopy(refs, 0, r, 0, nRefs); return r; } public void append(char c) { need(1); buf[len++] = c; } public void appendRefCharPair(Token t) { need(2); t.getRefCharPair(buf, len); len += 2; } public void append(char[] cbuf, int start, int end) { need(end - start); for (int i = start; i < end; i++) buf[len++] = cbuf[i]; } private void need(int n) { if (len + n <= buf.length) return; char[] tem = buf; if (n > tem.length) buf = new char[n * 2]; else buf = new char[tem.length << 1]; System.arraycopy(tem, 0, buf, 0, tem.length); } public char[] getChars() { char[] text = new char[len]; System.arraycopy(buf, 0, text, 0, len); return text; } public String toString() { return new String(buf, 0, len); } public int length() { return len; } public char charAt(int i) { if (i >= len) throw new IndexOutOfBoundsException(); return buf[i]; } public void chop() { --len; } } public Parser(Reader in) { this.in = in; this.parent = null; this.buf = new char[READSIZE * 2]; this.valueBuf = new ReplacementTextBuffer(); this.bufEnd = 0; this.paramEntityTable = new Hashtable(); } private Parser(char[] buf, String entityName, boolean isParameterEntity, Parser parent) { // this.internalEntityName = entityName; // this.isParameterEntity = isParameterEntity; this.buf = buf; this.parent = parent; //baseURL = parent.baseURL; //entityManager = parent.entityManager; this.bufEnd = buf.length; this.bufEndStreamOffset = buf.length; this.valueBuf = parent.valueBuf; this.paramEntityTable = parent.paramEntityTable; } public void parse() throws IOException { System.err.println("Parsing"); parseDecls(false); System.err.println("Unexpanding entities"); for (Enumeration e = paramEntityTable.elements(); e.hasMoreElements();) ((EntityImpl)e.nextElement()).unexpandEntities(); System.err.println("Dumping"); dumpEntity("#doc", atoms); } private void parseDecls(boolean isInternal) throws IOException { PrologParser pp = new PrologParser(isInternal ? PrologParser.INTERNAL_ENTITY : PrologParser.EXTERNAL_ENTITY); DeclState declState = new DeclState(); try { for (;;) { int tok; try { tok = tokenizeProlog(); } catch (EndOfPrologException e) { fatal("SYNTAX_ERROR"); break; } catch (EmptyTokenException e) { pp.end(); break; } prologAction(tok, pp, declState); } } catch (PrologSyntaxException e) { fatal("SYNTAX_ERROR"); } finally { if (!isInternal && in != null) { in.close(); in = null; } } } private void prologAction(int tok, PrologParser pp, DeclState declState) throws IOException, PrologSyntaxException { addAtom(new Atom(tok, new String(buf, currentTokenStart, bufStart - currentTokenStart))); int action = pp.action(tok, buf, currentTokenStart, bufStart); switch (action) { case PrologParser.ACTION_IGNORE_SECT: skipIgnoreSect(); break; case PrologParser.ACTION_GENERAL_ENTITY_NAME: declState.entity = null; break; case PrologParser.ACTION_PARAM_ENTITY_NAME: { String name = new String(buf, currentTokenStart, bufStart - currentTokenStart); declState.entity = createParamEntity(name); break; } case PrologParser.ACTION_ENTITY_VALUE_WITH_PEREFS: if (declState.entity != null) { makeReplacementText(); declState.entity.text = valueBuf.getChars(); declState.entity.mustReparse = valueBuf.getMustReparse(); declState.entity.references = valueBuf.getReferences(); } break; case PrologParser.ACTION_INNER_PARAM_ENTITY_REF: case PrologParser.ACTION_OUTER_PARAM_ENTITY_REF: { int nameStart = currentTokenStart + 1; String name = new String(buf, nameStart, getNameEnd() - nameStart); EntityImpl entity = lookupParamEntity(name); if (entity == null) { fatal("UNDEF_PEREF", name); break; } Parser parser = makeParserForEntity(entity, name, true); if (parser == null) { //XXX break; } entity.open = true; if (action == PrologParser.ACTION_OUTER_PARAM_ENTITY_REF) parser.parseDecls(entity.text != null); else parser.parseInnerParamEntity(pp, declState); entity.atoms = parser.atoms; setLastAtomEntity(entity); entity.open = false; break; } } } void parseInnerParamEntity(PrologParser pp, DeclState declState) throws IOException { int groupLevel = pp.getGroupLevel(); try { for (;;) { int tok = tokenizeProlog(); prologAction(tok, pp, declState); if (tok == Tokenizer.TOK_DECL_CLOSE) fatal("PE_DECL_NESTING"); } } catch (EndOfPrologException e) { fatal("SYNTAX_ERROR"); } catch (PrologSyntaxException e) { fatal("SYNTAX_ERROR"); } catch (EmptyTokenException e) { } if (pp.getGroupLevel() != groupLevel) fatal("PE_GROUP_NESTING"); } private Parser makeParserForEntity(EntityImpl entity, String name, boolean isParameter) throws IOException { if (entity.open) fatal("RECURSION"); if (entity.notationName != null) fatal("UNPARSED_REF"); if (entity.text != null) return new Parser(entity.text, name, isParameter, this); // XXX return null; //OpenEntity openEntity // = entityManager.open(entity.systemId, entity.baseURL, entity.publicId); //if (openEntity == null) // return null; //return new EntityParser(openEntity, entityManager, app, locale, this); } /* * Make the replacement text for an entity out of the literal in the * current token. */ private void makeReplacementText() throws IOException { valueBuf.clear(); Token t = new Token(); int start = currentTokenStart + 1; final int end = bufStart - 1; try { for (;;) { int tok; int nextStart; try { tok = Tokenizer.tokenizeEntityValue(buf, start, end, t); nextStart = t.getTokenEnd(); } catch (ExtensibleTokenException e) { tok = e.getTokenType(); nextStart = end; } handleEntityValueToken(valueBuf, tok, start, nextStart, t); start = nextStart; } } catch (PartialTokenException e) { currentTokenStart = end; fatal("NOT_WELL_FORMED"); } catch (InvalidTokenException e) { currentTokenStart = e.getOffset(); reportInvalidToken(e); } catch (EmptyTokenException e) { } } private void parseEntityValue(ReplacementTextBuffer value) throws IOException { final Token t = new Token(); for (;;) { int tok; for (;;) { try { tok = Tokenizer.tokenizeEntityValue(buf, bufStart, bufEnd, t); currentTokenStart = bufStart; bufStart = t.getTokenEnd(); break; } catch (EmptyTokenException e) { if (!fill()) return; } catch (PartialTokenException e) { if (!fill()) { currentTokenStart = bufStart; bufStart = bufEnd; fatal("UNCLOSED_TOKEN"); } } catch (ExtensibleTokenException e) { if (!fill()) { currentTokenStart = bufStart; bufStart = bufEnd; tok = e.getTokenType(); break; } } catch (InvalidTokenException e) { currentTokenStart = e.getOffset(); reportInvalidToken(e); } } handleEntityValueToken(value, tok, currentTokenStart, bufStart, t); } } private void handleEntityValueToken(ReplacementTextBuffer value, int tok, int start, int end, Token t) throws IOException { switch (tok) { case Tokenizer.TOK_DATA_CHARS: case Tokenizer.TOK_ENTITY_REF: case Tokenizer.TOK_MAGIC_ENTITY_REF: value.append(buf, start, end); break; case Tokenizer.TOK_CHAR_REF: { char c = t.getRefChar(); if (c == '&' || c == '%') value.setMustReparse(); value.append(t.getRefChar()); } break; case Tokenizer.TOK_CHAR_PAIR_REF: value.appendRefCharPair(t); break; case Tokenizer.TOK_DATA_NEWLINE: value.append('\n'); break; case Tokenizer.TOK_PARAM_ENTITY_REF: String name = new String(buf, start + 1, end - start - 2); EntityImpl entity = lookupParamEntity(name); if (entity == null) { fatal("UNDEF_PEREF", name); break; } if (entity.text != null && !entity.mustReparse) value.appendReplacementText(entity); else { System.err.println("Warning: reparsed reference to entity \"" + name + "\""); Parser parser = makeParserForEntity(entity, name, true); if (parser != null) { entity.open = true; parser.parseEntityValue(value); entity.open = false; } } break; default: throw new Error("replacement text botch"); } } private final int tokenizeProlog() throws IOException, EmptyTokenException, EndOfPrologException { for (;;) { try { int tok = Tokenizer.tokenizeProlog(buf, bufStart, bufEnd, this); currentTokenStart = bufStart; bufStart = getTokenEnd(); return tok; } catch (EmptyTokenException e) { if (!fill()) throw e; } catch (PartialTokenException e) { if (!fill()) { currentTokenStart = bufStart; bufStart = bufEnd; fatal("UNCLOSED_TOKEN"); } } catch (ExtensibleTokenException e) { if (!fill()) { currentTokenStart = bufStart; bufStart = bufEnd; return e.getTokenType(); } } catch (InvalidTokenException e) { bufStart = currentTokenStart = e.getOffset(); reportInvalidToken(e); } } } private final void skipIgnoreSect() throws IOException { for (;;) { try { int sectStart = bufStart; bufStart = Tokenizer.skipIgnoreSect(buf, bufStart, bufEnd); addAtom(new Atom(Tokenizer.TOK_COND_SECT_CLOSE, new String(buf, sectStart, bufStart - sectStart))); return; } catch (PartialTokenException e) { if (!fill()) { currentTokenStart = bufStart; fatal("UNCLOSED_CONDITIONAL_SECTION"); } } catch (InvalidTokenException e) { currentTokenStart = e.getOffset(); fatal("IGNORE_SECT_CHAR"); } } } /* The size of the buffer is always a multiple of READSIZE. We do reads so that a complete read would end at the end of the buffer. Unless there has been an incomplete read, we always read in multiples of READSIZE. */ private boolean fill() throws IOException { if (in == null) return false; if (bufEnd == buf.length) { Tokenizer.movePosition(buf, posOff, bufStart, pos); /* The last read was complete. */ int keep = bufEnd - bufStart; if (keep == 0) bufEnd = 0; else if (keep + READSIZE <= buf.length) { /* * There is space in the buffer for at least READSIZE bytes. * Choose bufEnd so that it is the least non-negative integer * greater than or equal to <code>keep</code>, such * <code>bufLength - keep</code> is a multiple of READSIZE. */ bufEnd = buf.length - (((buf.length - keep)/READSIZE) * READSIZE); for (int i = 0; i < keep; i++) buf[bufEnd - keep + i] = buf[bufStart + i]; } else { char newBuf[] = new char[buf.length << 1]; bufEnd = buf.length; System.arraycopy(buf, bufStart, newBuf, bufEnd - keep, keep); buf = newBuf; } bufStart = bufEnd - keep; posOff = bufStart; } int nChars = in.read(buf, bufEnd, buf.length - bufEnd); if (nChars < 0) { in.close(); in = null; return false; } bufEnd += nChars; bufEndStreamOffset += nChars; return true; } private EntityImpl lookupParamEntity(String name) { return (EntityImpl)paramEntityTable.get(name); } private EntityImpl createParamEntity(String name) { EntityImpl e = (EntityImpl)paramEntityTable.get(name); if (e != null) return null; e = new EntityImpl(name); paramEntityTable.put(name, e); return e; } private void fatal(String s, String arg) throws IOException { throw new IOException(s + ": " + arg); } private void fatal(String s) throws IOException { // XXX throw new IOException(s); } private void reportInvalidToken(InvalidTokenException e) throws IOException { // XXX fatal("INVALID_TOKEN"); } private void addAtom(Atom a) { atoms.addElement(a); } private void setLastAtomEntity(EntityImpl e) { ((Atom)atoms.elementAt(atoms.size() - 1)).setEntity(e); } private void dumpEntity(String name, Vector atoms) { System.out.println("<e name=\"" + name + "\">"); dumpAtoms(atoms); System.out.println("</e>"); } private void dumpAtoms(Vector v) { int n = v.size(); for (int i = 0; i < n; i++) { Atom a = (Atom)v.elementAt(i); EntityImpl e = a.getEntity(); if (e != null) dumpEntity(e.name, e.atoms); else if (a.getTokenType() != Tokenizer.TOK_PROLOG_S) { System.out.print("<t>"); dumpString(a.getToken()); System.out.println("</t>"); } } } private void dumpString(String s) { int n = s.length(); for (int i = 0; i < n; i++) switch (s.charAt(i)) { case '<': System.out.print("&lt;"); break; case '>': System.out.print("&gt;"); break; case '&': System.out.print("&amp;"); break; default: System.out.print(s.charAt(i)); break; } } }
package com.evolveum.midpoint.util.aspect; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.MDC; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; @Aspect @Order(value = Ordered.HIGHEST_PRECEDENCE) public class MidpointAspect { public static final String INDENT_STRING = " "; private static AtomicInteger idcounter = new AtomicInteger(0); private static AtomicInteger subidcounter = new AtomicInteger(0); // This logger provide profiling informations private static final org.slf4j.Logger LOGGER_PROFILING = org.slf4j.LoggerFactory.getLogger("PROFILING"); // FIXME: try to switch to spring injection. Note: infra components // shouldn't depend on spring // Formatters are statically initialized from class common's DebugUtil private static List<ObjectFormatter> formatters = new ArrayList<ObjectFormatter>(); /** * Register new formatter * * @param formatter */ public static void registerFormatter(ObjectFormatter formatter) { formatters.add(formatter); } @Around("entriesIntoRepository()") public Object processRepositoryNdc(ProceedingJoinPoint pjp) throws Throwable { return markSubsystem(pjp, "REPOSITORY"); } @Around("entriesIntoTaskManager()") public Object processTaskManagerNdc(ProceedingJoinPoint pjp) throws Throwable { return markSubsystem(pjp, "TASKMANAGER"); } @Around("entriesIntoProvisioning()") public Object processProvisioningNdc(ProceedingJoinPoint pjp) throws Throwable { return markSubsystem(pjp, "PROVISIONING"); } @Around("entriesIntoResourceObjectChangeListener()") public Object processResourceObjectChangeListenerNdc(ProceedingJoinPoint pjp) throws Throwable { return markSubsystem(pjp, "RESOURCEOBJECTCHANGELISTENER"); } @Around("entriesIntoModel()") public Object processModelNdc(ProceedingJoinPoint pjp) throws Throwable { return markSubsystem(pjp, "MODEL"); } @Around("entriesIntoWeb()") public Object processWebNdc(ProceedingJoinPoint pjp) throws Throwable { return markSubsystem(pjp, "WEB"); } @Around("entriesIntoUcf()") public Object processUcfNdc(ProceedingJoinPoint pjp) throws Throwable { return markSubsystem(pjp, "UCF"); } private Object markSubsystem(ProceedingJoinPoint pjp, String subsystem) throws Throwable { Object retValue = null; String prev = null; int id = 0; int d = 1; boolean exc = false; String excName = null; // Profiling start long startTime = System.nanoTime(); final StringBuilder infoLog = new StringBuilder(" try { // Marking MDC->Subsystem with current one subsystem and mark // previous prev = (String) MDC.get("subsystem"); MDC.put("subsystem", subsystem); if (LOGGER_PROFILING.isDebugEnabled()) { id = idcounter.incrementAndGet(); infoLog.append(id); } if (LOGGER_PROFILING.isTraceEnabled()) { String depth = MDC.get("depth"); if (depth == null || depth.isEmpty()) { d = 0; } else { d = Integer.parseInt(depth); } d++; MDC.put("depth", Integer.toString(d)); for (int i = 0; i < d; i++) { infoLog.append(INDENT_STRING); } } // is profiling info is needed if (LOGGER_PROFILING.isDebugEnabled()) { infoLog.append(getClassName(pjp)); LOGGER_PROFILING.debug("{}->{}", infoLog, pjp.getSignature().getName()); // If debug enable get entry parameters and log them if (LOGGER_PROFILING.isTraceEnabled()) { final Object[] args = pjp.getArgs(); // final String[] names = ((CodeSignature) // pjp.getSignature()).getParameterNames(); // @SuppressWarnings("unchecked") // final Class<CodeSignature>[] types = ((CodeSignature) // pjp.getSignature()).getParameterTypes(); final StringBuffer sb = new StringBuffer(); sb.append(" sb.append("("); for (int i = 0; i < args.length; i++) { sb.append(formatVal(args[i])); if (args.length != i + 1) { sb.append(", "); } } sb.append(")"); LOGGER_PROFILING.trace(sb.toString()); } } // Process original call try { retValue = pjp.proceed(); } catch (Exception e) { excName = e.getClass().getName(); exc = true; throw e; } // Return original response return retValue; } finally { // Depth -1 if (LOGGER_PROFILING.isTraceEnabled()) { d MDC.put("depth", Integer.toString(d)); } // Restore previously marked subsystem executed before return if (LOGGER_PROFILING.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append(" if (LOGGER_PROFILING.isDebugEnabled()) { sb.append(id); sb.append(" "); } // sb.append("/"); if (LOGGER_PROFILING.isTraceEnabled()) { for (int i = 0; i < d + 1; i++) { sb.append(INDENT_STRING); } } sb.append(getClassName(pjp)); sb.append("->"); sb.append(pjp.getSignature().getName()); if (LOGGER_PROFILING.isDebugEnabled()) { sb.append(" etime: "); // Mark end of processing long elapsed = System.nanoTime() - startTime; sb.append((long) (elapsed / 1000000)); sb.append('.'); long mikros = (long) (elapsed / 1000) % 1000; if (mikros < 100) { sb.append('0'); } if (mikros < 10) { sb.append('0'); } sb.append(mikros); sb.append(" ms"); } LOGGER_PROFILING.debug(sb.toString()); if (LOGGER_PROFILING.isTraceEnabled()) { if (exc) { LOGGER_PROFILING.trace(" } else { LOGGER_PROFILING.trace(" } } } // Restore MDC if (prev == null) { MDC.remove("subsystem"); } else { MDC.put("subsystem", prev); } } } @Pointcut("execution(* com.evolveum.midpoint.repo.api.RepositoryService.*(..))") public void entriesIntoRepository() { } @Pointcut("execution(* com.evolveum.midpoint.task.api.TaskManager.*(..))") public void entriesIntoTaskManager() { } @Pointcut("execution(* com.evolveum.midpoint.provisioning.api.ProvisioningService.*(..))") public void entriesIntoProvisioning() { } @Pointcut("execution(* com.evolveum.midpoint.provisioning.api.ResourceObjectChangeListener.*(..))") public void entriesIntoResourceObjectChangeListener() { } @Pointcut("execution(* com.evolveum.midpoint.model.api.ModelService.*(..))") public void entriesIntoModel() { } @Pointcut("execution(* com.evolveum.midpoint.web.controller..*.*(..)) " + "&& !execution(public * com.evolveum.midpoint.web.controller..*.get*(..)) " + "&& !execution(public * com.evolveum.midpoint.web.controller..*.set*(..))" + "&& !execution(public * com.evolveum.midpoint.web.controller..*.is*(..))" + "&& !execution(* com.evolveum.midpoint.web.controller.Language..*.*(..))") public void entriesIntoWeb() { } // @Pointcut("execution(* com.evolveum.midpoint.web.model.impl..*.*(..))") // public void entriesIntoWeb() { @Pointcut("execution(* com.evolveum.midpoint.provisioning.ucf.api..*.*(..))") public void entriesIntoUcf() { } /** * Get joinpoint class name if available * * @param pjp * @return */ private String getClassName(ProceedingJoinPoint pjp) { String className = null; if (pjp.getThis() != null) { className = pjp.getThis().getClass().getName(); className = className.replaceFirst("com.evolveum.midpoint", ".."); } return className; } /** * Debug output formater * * @param value * @return */ private String formatVal(Object value) { if (value == null) { return ("null"); } else { String out = null; for (ObjectFormatter formatter : formatters) { out = formatter.format(value); if (out != null) { break; } } if (out == null) { return (value.toString()); } else { return out; } } } }
class NonShortCircuit { boolean b; boolean bothBitsFalsePositive(int i) { return and((i & 0x1) != 0, (i & 0x2) != 0); } boolean and(boolean x, boolean y) { return x & y; } void orIt(boolean x, boolean y) { x |= y; b |= x; } boolean ordered(int x, int y, int z) { if (x >= y | y >= z) System.out.println("Not ordered"); return x < y & y < z; } boolean nonEmpty(Object o[]) { return o != null & o.length > 0; } public static final int BIT0 = 1; // 1st bit protected int m_iType; public NonShortCircuit(boolean available) { m_iType |= available ? BIT0 : 0; } public String f(String tag, String value) { if (tag != null & tag.length() > 0 && value != null && value.length() > 0) return tag + ":" + value; return "?"; } }
package com.airbnb.lottie; import android.animation.Animator; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.ImageView; import androidx.annotation.FloatRange; import androidx.annotation.IntDef; import androidx.annotation.IntRange; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.annotation.RestrictTo; import com.airbnb.lottie.animation.LPaint; import com.airbnb.lottie.manager.FontAssetManager; import com.airbnb.lottie.manager.ImageAssetManager; import com.airbnb.lottie.model.KeyPath; import com.airbnb.lottie.model.Marker; import com.airbnb.lottie.model.layer.CompositionLayer; import com.airbnb.lottie.parser.LayerParser; import com.airbnb.lottie.utils.Logger; import com.airbnb.lottie.utils.LottieValueAnimator; import com.airbnb.lottie.utils.MiscUtils; import com.airbnb.lottie.value.LottieFrameInfo; import com.airbnb.lottie.value.LottieValueCallback; import com.airbnb.lottie.value.SimpleLottieValueCallback; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; @SuppressWarnings({"WeakerAccess"}) public class LottieDrawable extends Drawable implements Drawable.Callback, Animatable { private interface LazyCompositionTask { void run(LottieComposition composition); } /** * Internal record keeping of the desired play state when {@link #isVisible()} transitions to or is false. * <p> * If the animation was playing when it becomes invisible or play/pause is called on it while it is invisible, it will * store the state and then take the appropriate action when the drawable becomes visible again. */ private enum OnVisibleAction { NONE, PLAY, RESUME, } private LottieComposition composition; private final LottieValueAnimator animator = new LottieValueAnimator(); // Call animationsEnabled() instead of using these fields directly. private boolean systemAnimationsEnabled = true; private boolean ignoreSystemAnimationsDisabled = false; private boolean safeMode = false; private OnVisibleAction onVisibleAction = OnVisibleAction.NONE; private final ArrayList<LazyCompositionTask> lazyCompositionTasks = new ArrayList<>(); private final ValueAnimator.AnimatorUpdateListener progressUpdateListener = new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { if (compositionLayer != null) { compositionLayer.setProgress(animator.getAnimatedValueAbsolute()); } } }; /** * ImageAssetManager created automatically by Lottie for views. */ @Nullable private ImageAssetManager imageAssetManager; @Nullable private String imageAssetsFolder; @Nullable private ImageAssetDelegate imageAssetDelegate; @Nullable private FontAssetManager fontAssetManager; @Nullable FontAssetDelegate fontAssetDelegate; @Nullable TextDelegate textDelegate; private boolean enableMergePaths; private boolean maintainOriginalImageBounds = false; private boolean clipToCompositionBounds = true; @Nullable private CompositionLayer compositionLayer; private int alpha = 255; private boolean performanceTrackingEnabled; private boolean outlineMasksAndMattes; private boolean isApplyingOpacityToLayersEnabled; private RenderMode renderMode = RenderMode.AUTOMATIC; /** * The actual render mode derived from {@link #renderMode}. */ private boolean useSoftwareRendering = false; private final Matrix renderingMatrix = new Matrix(); private Bitmap softwareRenderingBitmap; private Canvas softwareRenderingCanvas; private Rect canvasClipBounds; private RectF canvasClipBoundsRectF; private Paint softwareRenderingPaint; private Rect softwareRenderingSrcBoundsRect; private Rect softwareRenderingDstBoundsRect; private RectF softwareRenderingDstBoundsRectF; private RectF softwareRenderingTransformedBounds; private Matrix softwareRenderingOriginalCanvasMatrix; private Matrix softwareRenderingOriginalCanvasMatrixInverse; /** * True if the drawable has not been drawn since the last invalidateSelf. * We can do this to prevent things like bounds from getting recalculated * many times. */ private boolean isDirty = false; @IntDef({RESTART, REVERSE}) @Retention(RetentionPolicy.SOURCE) public @interface RepeatMode { } /** * When the animation reaches the end and <code>repeatCount</code> is INFINITE * or a positive value, the animation restarts from the beginning. */ public static final int RESTART = ValueAnimator.RESTART; /** * When the animation reaches the end and <code>repeatCount</code> is INFINITE * or a positive value, the animation reverses direction on every iteration. */ public static final int REVERSE = ValueAnimator.REVERSE; /** * This value used used with the {@link #setRepeatCount(int)} property to repeat * the animation indefinitely. */ public static final int INFINITE = ValueAnimator.INFINITE; public LottieDrawable() { animator.addUpdateListener(progressUpdateListener); } /** * Returns whether or not any layers in this composition has masks. */ public boolean hasMasks() { return compositionLayer != null && compositionLayer.hasMasks(); } /** * Returns whether or not any layers in this composition has a matte layer. */ public boolean hasMatte() { return compositionLayer != null && compositionLayer.hasMatte(); } public boolean enableMergePathsForKitKatAndAbove() { return enableMergePaths; } /** * Enable this to get merge path support for devices running KitKat (19) and above. * <p> * Merge paths currently don't work if the the operand shape is entirely contained within the * first shape. If you need to cut out one shape from another shape, use an even-odd fill type * instead of using merge paths. */ public void enableMergePathsForKitKatAndAbove(boolean enable) { if (enableMergePaths == enable) { return; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { Logger.warning("Merge paths are not supported pre-Kit Kat."); return; } enableMergePaths = enable; if (composition != null) { buildCompositionLayer(); } } public boolean isMergePathsEnabledForKitKatAndAbove() { return enableMergePaths; } /** * Sets whether or not Lottie should clip to the original animation composition bounds. * * Defaults to true. */ public void setClipToCompositionBounds(boolean clipToCompositionBounds) { if (clipToCompositionBounds != this.clipToCompositionBounds) { this.clipToCompositionBounds = clipToCompositionBounds; CompositionLayer compositionLayer = this.compositionLayer; if (compositionLayer != null) { compositionLayer.setClipToCompositionBounds(clipToCompositionBounds); } invalidateSelf(); } } /** * Gets whether or not Lottie should clip to the original animation composition bounds. * * Defaults to true. */ public boolean getClipToCompositionBounds() { return clipToCompositionBounds; } public void setImagesAssetsFolder(@Nullable String imageAssetsFolder) { this.imageAssetsFolder = imageAssetsFolder; } @Nullable public String getImageAssetsFolder() { return imageAssetsFolder; } /** * When true, dynamically set bitmaps will be drawn with the exact bounds of the original animation, regardless of the bitmap size. * When false, dynamically set bitmaps will be drawn at the top left of the original image but with its own bounds. * <p> * Defaults to false. */ public void setMaintainOriginalImageBounds(boolean maintainOriginalImageBounds) { this.maintainOriginalImageBounds = maintainOriginalImageBounds; } /** * When true, dynamically set bitmaps will be drawn with the exact bounds of the original animation, regardless of the bitmap size. * When false, dynamically set bitmaps will be drawn at the top left of the original image but with its own bounds. * <p> * Defaults to false. */ public boolean getMaintainOriginalImageBounds() { return maintainOriginalImageBounds; } /** * Create a composition with {@link LottieCompositionFactory} * * @return True if the composition is different from the previously set composition, false otherwise. */ public boolean setComposition(LottieComposition composition) { if (this.composition == composition) { return false; } isDirty = true; clearComposition(); this.composition = composition; buildCompositionLayer(); animator.setComposition(composition); setProgress(animator.getAnimatedFraction()); // We copy the tasks to a new ArrayList so that if this method is called from multiple threads, // then there won't be two iterators iterating and removing at the same time. Iterator<LazyCompositionTask> it = new ArrayList<>(lazyCompositionTasks).iterator(); while (it.hasNext()) { LazyCompositionTask t = it.next(); // The task should never be null but it appears to happen in rare cases. Maybe it's an oem-specific or ART bug. if (t != null) { t.run(composition); } it.remove(); } lazyCompositionTasks.clear(); composition.setPerformanceTrackingEnabled(performanceTrackingEnabled); computeRenderMode(); // Ensure that ImageView updates the drawable width/height so it can // properly calculate its drawable matrix. Callback callback = getCallback(); if (callback instanceof ImageView) { ((ImageView) callback).setImageDrawable(null); ((ImageView) callback).setImageDrawable(this); } return true; } public void setRenderMode(RenderMode renderMode) { this.renderMode = renderMode; computeRenderMode(); } /** * Returns the actual render mode being used. It will always be {@link RenderMode#HARDWARE} or {@link RenderMode#SOFTWARE}. * When the render mode is set to AUTOMATIC, the value will be derived from {@link RenderMode#useSoftwareRendering(int, boolean, int)}. */ public RenderMode getRenderMode() { return useSoftwareRendering ? RenderMode.SOFTWARE : RenderMode.HARDWARE; } private void computeRenderMode() { LottieComposition composition = this.composition; if (composition == null) { return; } useSoftwareRendering = renderMode.useSoftwareRendering( Build.VERSION.SDK_INT, composition.hasDashPattern(), composition.getMaskAndMatteCount()); } public void setPerformanceTrackingEnabled(boolean enabled) { performanceTrackingEnabled = enabled; if (composition != null) { composition.setPerformanceTrackingEnabled(enabled); } } /** * Enable this to debug slow animations by outlining masks and mattes. The performance overhead of the masks and mattes will * be proportional to the surface area of all of the masks/mattes combined. * <p> * DO NOT leave this enabled in production. */ public void setOutlineMasksAndMattes(boolean outline) { if (outlineMasksAndMattes == outline) { return; } outlineMasksAndMattes = outline; if (compositionLayer != null) { compositionLayer.setOutlineMasksAndMattes(outline); } } @Nullable public PerformanceTracker getPerformanceTracker() { if (composition != null) { return composition.getPerformanceTracker(); } return null; } /** * Sets whether to apply opacity to the each layer instead of shape. * <p> * Opacity is normally applied directly to a shape. In cases where translucent shapes overlap, applying opacity to a layer will be more accurate * at the expense of performance. * <p> * The default value is false. * <p> * Note: This process is very expensive. The performance impact will be reduced when hardware acceleration is enabled. * * @see android.view.View#setLayerType(int, android.graphics.Paint) * @see LottieAnimationView#setRenderMode(RenderMode) */ public void setApplyingOpacityToLayersEnabled(boolean isApplyingOpacityToLayersEnabled) { this.isApplyingOpacityToLayersEnabled = isApplyingOpacityToLayersEnabled; } /** * This API no longer has any effect. */ @Deprecated public void disableExtraScaleModeInFitXY() { } public boolean isApplyingOpacityToLayersEnabled() { return isApplyingOpacityToLayersEnabled; } private void buildCompositionLayer() { LottieComposition composition = this.composition; if (composition == null) { return; } compositionLayer = new CompositionLayer( this, LayerParser.parse(composition), composition.getLayers(), composition); if (outlineMasksAndMattes) { compositionLayer.setOutlineMasksAndMattes(true); } compositionLayer.setClipToCompositionBounds(clipToCompositionBounds); } public void clearComposition() { if (animator.isRunning()) { animator.cancel(); if (!isVisible()) { onVisibleAction = OnVisibleAction.NONE; } } composition = null; compositionLayer = null; imageAssetManager = null; animator.clearComposition(); invalidateSelf(); } /** * If you are experiencing a device specific crash that happens during drawing, you can set this to true * for those devices. If set to true, draw will be wrapped with a try/catch which will cause Lottie to * render an empty frame rather than crash your app. * <p> * Ideally, you will never need this and the vast majority of apps and animations won't. However, you may use * this for very specific cases if absolutely necessary. */ public void setSafeMode(boolean safeMode) { this.safeMode = safeMode; } @Override public void invalidateSelf() { if (isDirty) { return; } isDirty = true; final Callback callback = getCallback(); if (callback != null) { callback.invalidateDrawable(this); } } @Override public void setAlpha(@IntRange(from = 0, to = 255) int alpha) { this.alpha = alpha; invalidateSelf(); } @Override public int getAlpha() { return alpha; } @Override public void setColorFilter(@Nullable ColorFilter colorFilter) { Logger.warning("Use addColorFilter instead."); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public void draw(@NonNull Canvas canvas) { L.beginSection("Drawable#draw"); if (safeMode) { try { if (useSoftwareRendering) { renderAndDrawAsBitmap(canvas, compositionLayer); } else { drawDirectlyToCanvas(canvas); } } catch (Throwable e) { Logger.error("Lottie crashed in draw!", e); } } else { if (useSoftwareRendering) { renderAndDrawAsBitmap(canvas, compositionLayer); } else { drawDirectlyToCanvas(canvas); } } isDirty = false; L.endSection("Drawable#draw"); } /** * To be used by lottie-compose only. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public void draw(Canvas canvas, Matrix matrix) { CompositionLayer compositionLayer = this.compositionLayer; LottieComposition composition = this.composition; if (compositionLayer == null || composition == null) { return; } if (useSoftwareRendering) { canvas.save(); canvas.concat(matrix); renderAndDrawAsBitmap(canvas, compositionLayer); canvas.restore(); } else { compositionLayer.draw(canvas, matrix, alpha); } isDirty = false; } // <editor-fold desc="animator"> @MainThread @Override public void start() { // Don't auto play when in edit mode. Callback callback = getCallback(); if (callback instanceof View && !((View) callback).isInEditMode()) { playAnimation(); } } @MainThread @Override public void stop() { endAnimation(); } @Override public boolean isRunning() { return isAnimating(); } /** * Plays the animation from the beginning. If speed is {@literal <} 0, it will start at the end * and play towards the beginning */ @MainThread public void playAnimation() { if (compositionLayer == null) { lazyCompositionTasks.add(c -> playAnimation()); return; } computeRenderMode(); if (animationsEnabled() || getRepeatCount() == 0) { if (isVisible()) { animator.playAnimation(); } else { onVisibleAction = OnVisibleAction.PLAY; } } if (!animationsEnabled()) { setFrame((int) (getSpeed() < 0 ? getMinFrame() : getMaxFrame())); animator.endAnimation(); if (!isVisible()) { onVisibleAction = OnVisibleAction.NONE; } } } @MainThread public void endAnimation() { lazyCompositionTasks.clear(); animator.endAnimation(); if (!isVisible()) { onVisibleAction = OnVisibleAction.NONE; } } /** * Continues playing the animation from its current position. If speed {@literal <} 0, it will play backwards * from the current position. */ @MainThread public void resumeAnimation() { if (compositionLayer == null) { lazyCompositionTasks.add(c -> resumeAnimation()); return; } computeRenderMode(); if (animationsEnabled() || getRepeatCount() == 0) { if (isVisible()) { animator.resumeAnimation(); } else { onVisibleAction = OnVisibleAction.RESUME; } } if (!animationsEnabled()) { setFrame((int) (getSpeed() < 0 ? getMinFrame() : getMaxFrame())); animator.endAnimation(); if (!isVisible()) { onVisibleAction = OnVisibleAction.NONE; } } } /** * Sets the minimum frame that the animation will start from when playing or looping. */ public void setMinFrame(final int minFrame) { if (composition == null) { lazyCompositionTasks.add(c -> setMinFrame(minFrame)); return; } animator.setMinFrame(minFrame); } /** * Returns the minimum frame set by {@link #setMinFrame(int)} or {@link #setMinProgress(float)} */ public float getMinFrame() { return animator.getMinFrame(); } /** * Sets the minimum progress that the animation will start from when playing or looping. */ public void setMinProgress(final float minProgress) { if (composition == null) { lazyCompositionTasks.add(c -> setMinProgress(minProgress)); return; } setMinFrame((int) MiscUtils.lerp(composition.getStartFrame(), composition.getEndFrame(), minProgress)); } /** * Sets the maximum frame that the animation will end at when playing or looping. * <p> * The value will be clamped to the composition bounds. For example, setting Integer.MAX_VALUE would result in the same * thing as composition.endFrame. */ public void setMaxFrame(final int maxFrame) { if (composition == null) { lazyCompositionTasks.add(c -> setMaxFrame(maxFrame)); return; } animator.setMaxFrame(maxFrame + 0.99f); } /** * Returns the maximum frame set by {@link #setMaxFrame(int)} or {@link #setMaxProgress(float)} */ public float getMaxFrame() { return animator.getMaxFrame(); } /** * Sets the maximum progress that the animation will end at when playing or looping. */ public void setMaxProgress(@FloatRange(from = 0f, to = 1f) final float maxProgress) { if (composition == null) { lazyCompositionTasks.add(c -> setMaxProgress(maxProgress)); return; } setMaxFrame((int) MiscUtils.lerp(composition.getStartFrame(), composition.getEndFrame(), maxProgress)); } public void setMinFrame(final String markerName) { if (composition == null) { lazyCompositionTasks.add(c -> setMinFrame(markerName)); return; } Marker marker = composition.getMarker(markerName); if (marker == null) { throw new IllegalArgumentException("Cannot find marker with name " + markerName + "."); } setMinFrame((int) marker.startFrame); } public void setMaxFrame(final String markerName) { if (composition == null) { lazyCompositionTasks.add(c -> setMaxFrame(markerName)); return; } Marker marker = composition.getMarker(markerName); if (marker == null) { throw new IllegalArgumentException("Cannot find marker with name " + markerName + "."); } setMaxFrame((int) (marker.startFrame + marker.durationFrames)); } public void setMinAndMaxFrame(final String markerName) { if (composition == null) { lazyCompositionTasks.add(c -> setMinAndMaxFrame(markerName)); return; } Marker marker = composition.getMarker(markerName); if (marker == null) { throw new IllegalArgumentException("Cannot find marker with name " + markerName + "."); } int startFrame = (int) marker.startFrame; setMinAndMaxFrame(startFrame, startFrame + (int) marker.durationFrames); } public void setMinAndMaxFrame(final String startMarkerName, final String endMarkerName, final boolean playEndMarkerStartFrame) { if (composition == null) { lazyCompositionTasks.add(c -> setMinAndMaxFrame(startMarkerName, endMarkerName, playEndMarkerStartFrame)); return; } Marker startMarker = composition.getMarker(startMarkerName); if (startMarker == null) { throw new IllegalArgumentException("Cannot find marker with name " + startMarkerName + "."); } int startFrame = (int) startMarker.startFrame; final Marker endMarker = composition.getMarker(endMarkerName); if (endMarker == null) { throw new IllegalArgumentException("Cannot find marker with name " + endMarkerName + "."); } int endFrame = (int) (endMarker.startFrame + (playEndMarkerStartFrame ? 1f : 0f)); setMinAndMaxFrame(startFrame, endFrame); } /** * @see #setMinFrame(int) * @see #setMaxFrame(int) */ public void setMinAndMaxFrame(final int minFrame, final int maxFrame) { if (composition == null) { lazyCompositionTasks.add(c -> setMinAndMaxFrame(minFrame, maxFrame)); return; } // Adding 0.99 ensures that the maxFrame itself gets played. animator.setMinAndMaxFrames(minFrame, maxFrame + 0.99f); } /** * @see #setMinProgress(float) * @see #setMaxProgress(float) */ public void setMinAndMaxProgress( @FloatRange(from = 0f, to = 1f) final float minProgress, @FloatRange(from = 0f, to = 1f) final float maxProgress) { if (composition == null) { lazyCompositionTasks.add(c -> setMinAndMaxProgress(minProgress, maxProgress)); return; } setMinAndMaxFrame((int) MiscUtils.lerp(composition.getStartFrame(), composition.getEndFrame(), minProgress), (int) MiscUtils.lerp(composition.getStartFrame(), composition.getEndFrame(), maxProgress)); } /** * Reverses the current animation speed. This does NOT play the animation. * * @see #setSpeed(float) * @see #playAnimation() * @see #resumeAnimation() */ public void reverseAnimationSpeed() { animator.reverseAnimationSpeed(); } /** * Sets the playback speed. If speed {@literal <} 0, the animation will play backwards. */ public void setSpeed(float speed) { animator.setSpeed(speed); } /** * Returns the current playback speed. This will be {@literal <} 0 if the animation is playing backwards. */ public float getSpeed() { return animator.getSpeed(); } public void addAnimatorUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) { animator.addUpdateListener(updateListener); } public void removeAnimatorUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) { animator.removeUpdateListener(updateListener); } public void removeAllUpdateListeners() { animator.removeAllUpdateListeners(); animator.addUpdateListener(progressUpdateListener); } public void addAnimatorListener(Animator.AnimatorListener listener) { animator.addListener(listener); } public void removeAnimatorListener(Animator.AnimatorListener listener) { animator.removeListener(listener); } public void removeAllAnimatorListeners() { animator.removeAllListeners(); } @RequiresApi(api = Build.VERSION_CODES.KITKAT) public void addAnimatorPauseListener(Animator.AnimatorPauseListener listener) { animator.addPauseListener(listener); } @RequiresApi(api = Build.VERSION_CODES.KITKAT) public void removeAnimatorPauseListener(Animator.AnimatorPauseListener listener) { animator.removePauseListener(listener); } /** * Sets the progress to the specified frame. * If the composition isn't set yet, the progress will be set to the frame when * it is. */ public void setFrame(final int frame) { if (composition == null) { lazyCompositionTasks.add(c -> setFrame(frame)); return; } animator.setFrame(frame); } /** * Get the currently rendered frame. */ public int getFrame() { return (int) animator.getFrame(); } public void setProgress(@FloatRange(from = 0f, to = 1f) final float progress) { if (composition == null) { lazyCompositionTasks.add(c -> setProgress(progress)); return; } L.beginSection("Drawable#setProgress"); animator.setFrame(composition.getFrameForProgress(progress)); L.endSection("Drawable#setProgress"); } /** * @see #setRepeatCount(int) */ @Deprecated public void loop(boolean loop) { animator.setRepeatCount(loop ? ValueAnimator.INFINITE : 0); } /** * Defines what this animation should do when it reaches the end. This * setting is applied only when the repeat count is either greater than * 0 or {@link #INFINITE}. Defaults to {@link #RESTART}. * * @param mode {@link #RESTART} or {@link #REVERSE} */ public void setRepeatMode(@RepeatMode int mode) { animator.setRepeatMode(mode); } /** * Defines what this animation should do when it reaches the end. * * @return either one of {@link #REVERSE} or {@link #RESTART} */ @SuppressLint("WrongConstant") @RepeatMode public int getRepeatMode() { return animator.getRepeatMode(); } /** * Sets how many times the animation should be repeated. If the repeat * count is 0, the animation is never repeated. If the repeat count is * greater than 0 or {@link #INFINITE}, the repeat mode will be taken * into account. The repeat count is 0 by default. * * @param count the number of times the animation should be repeated */ public void setRepeatCount(int count) { animator.setRepeatCount(count); } /** * Defines how many times the animation should repeat. The default value * is 0. * * @return the number of times the animation should repeat, or {@link #INFINITE} */ public int getRepeatCount() { return animator.getRepeatCount(); } @SuppressWarnings("unused") public boolean isLooping() { return animator.getRepeatCount() == ValueAnimator.INFINITE; } public boolean isAnimating() { // On some versions of Android, this is called from the LottieAnimationView constructor, before animator was created. //noinspection ConstantConditions if (animator == null) { return false; } return animator.isRunning(); } boolean isAnimatingOrWillAnimateOnVisible() { if (isVisible()) { return animator.isRunning(); } else { return onVisibleAction == OnVisibleAction.PLAY || onVisibleAction == OnVisibleAction.RESUME; } } private boolean animationsEnabled() { return systemAnimationsEnabled || ignoreSystemAnimationsDisabled; } void setSystemAnimationsAreEnabled(Boolean areEnabled) { systemAnimationsEnabled = areEnabled; } // </editor-fold> /** * Allows ignoring system animations settings, therefore allowing animations to run even if they are disabled. * <p> * Defaults to false. * * @param ignore if true animations will run even when they are disabled in the system settings. */ public void setIgnoreDisabledSystemAnimations(boolean ignore) { ignoreSystemAnimationsDisabled = ignore; } public void setImageAssetDelegate(ImageAssetDelegate assetDelegate) { this.imageAssetDelegate = assetDelegate; if (imageAssetManager != null) { imageAssetManager.setDelegate(assetDelegate); } } /** * Use this to manually set fonts. */ public void setFontAssetDelegate(FontAssetDelegate assetDelegate) { this.fontAssetDelegate = assetDelegate; if (fontAssetManager != null) { fontAssetManager.setDelegate(assetDelegate); } } public void setTextDelegate(@SuppressWarnings("NullableProblems") TextDelegate textDelegate) { this.textDelegate = textDelegate; } @Nullable public TextDelegate getTextDelegate() { return textDelegate; } public boolean useTextGlyphs() { return textDelegate == null && composition.getCharacters().size() > 0; } public LottieComposition getComposition() { return composition; } public void cancelAnimation() { lazyCompositionTasks.clear(); animator.cancel(); if (!isVisible()) { onVisibleAction = OnVisibleAction.NONE; } } public void pauseAnimation() { lazyCompositionTasks.clear(); animator.pauseAnimation(); if (!isVisible()) { onVisibleAction = OnVisibleAction.NONE; } } @FloatRange(from = 0f, to = 1f) public float getProgress() { return animator.getAnimatedValueAbsolute(); } @Override public int getIntrinsicWidth() { return composition == null ? -1 : composition.getBounds().width(); } @Override public int getIntrinsicHeight() { return composition == null ? -1 : composition.getBounds().height(); } /** * Takes a {@link KeyPath}, potentially with wildcards or globstars and resolve it to a list of * zero or more actual {@link KeyPath Keypaths} that exist in the current animation. * <p> * If you want to set value callbacks for any of these values, it is recommend to use the * returned {@link KeyPath} objects because they will be internally resolved to their content * and won't trigger a tree walk of the animation contents when applied. */ public List<KeyPath> resolveKeyPath(KeyPath keyPath) { if (compositionLayer == null) { Logger.warning("Cannot resolve KeyPath. Composition is not set yet."); return Collections.emptyList(); } List<KeyPath> keyPaths = new ArrayList<>(); compositionLayer.resolveKeyPath(keyPath, 0, keyPaths, new KeyPath()); return keyPaths; } /** * Add an property callback for the specified {@link KeyPath}. This {@link KeyPath} can resolve * to multiple contents. In that case, the callback's value will apply to all of them. * <p> * Internally, this will check if the {@link KeyPath} has already been resolved with * {@link #resolveKeyPath(KeyPath)} and will resolve it if it hasn't. */ public <T> void addValueCallback( final KeyPath keyPath, final T property, @Nullable final LottieValueCallback<T> callback) { if (compositionLayer == null) { lazyCompositionTasks.add(c -> addValueCallback(keyPath, property, callback)); return; } boolean invalidate; if (keyPath == KeyPath.COMPOSITION) { compositionLayer.addValueCallback(property, callback); invalidate = true; } else if (keyPath.getResolvedElement() != null) { keyPath.getResolvedElement().addValueCallback(property, callback); invalidate = true; } else { List<KeyPath> elements = resolveKeyPath(keyPath); for (int i = 0; i < elements.size(); i++) { //noinspection ConstantConditions elements.get(i).getResolvedElement().addValueCallback(property, callback); } invalidate = !elements.isEmpty(); } if (invalidate) { invalidateSelf(); if (property == LottieProperty.TIME_REMAP) { // Time remapping values are read in setProgress. In order for the new value // to apply, we have to re-set the progress with the current progress so that the // time remapping can be reapplied. setProgress(getProgress()); } } } /** * Overload of {@link #addValueCallback(KeyPath, Object, LottieValueCallback)} that takes an interface. This allows you to use a single abstract * method code block in Kotlin such as: * drawable.addValueCallback(yourKeyPath, LottieProperty.COLOR) { yourColor } */ public <T> void addValueCallback(KeyPath keyPath, T property, final SimpleLottieValueCallback<T> callback) { addValueCallback(keyPath, property, new LottieValueCallback<T>() { @Override public T getValue(LottieFrameInfo<T> frameInfo) { return callback.getValue(frameInfo); } }); } /** * Allows you to modify or clear a bitmap that was loaded for an image either automatically * through {@link #setImagesAssetsFolder(String)} or with an {@link ImageAssetDelegate}. * * @return the previous Bitmap or null. */ @Nullable public Bitmap updateBitmap(String id, @Nullable Bitmap bitmap) { ImageAssetManager bm = getImageAssetManager(); if (bm == null) { Logger.warning("Cannot update bitmap. Most likely the drawable is not added to a View " + "which prevents Lottie from getting a Context."); return null; } Bitmap ret = bm.updateBitmap(id, bitmap); invalidateSelf(); return ret; } /** * @deprecated use {@link #getBitmapForId(String)}. */ @Nullable @Deprecated public Bitmap getImageAsset(String id) { ImageAssetManager bm = getImageAssetManager(); if (bm != null) { return bm.bitmapForId(id); } LottieImageAsset imageAsset = composition == null ? null : composition.getImages().get(id); if (imageAsset != null) { return imageAsset.getBitmap(); } return null; } /** * Returns the bitmap that will be rendered for the given id in the Lottie animation file. * The id is the asset reference id stored in the "id" property of each object in the "assets" array. * <p> * The returned bitmap could be from: * * Embedded in the animation file as a base64 string. * * In the same directory as the animation file. * * In the same zip file as the animation file. * * Returned from an {@link ImageAssetDelegate}. * or null if the image doesn't exist from any of those places. */ @Nullable public Bitmap getBitmapForId(String id) { ImageAssetManager assetManager = getImageAssetManager(); if (assetManager != null) { return assetManager.bitmapForId(id); } return null; } /** * Returns the {@link LottieImageAsset} that will be rendered for the given id in the Lottie animation file. * The id is the asset reference id stored in the "id" property of each object in the "assets" array. * <p> * The returned bitmap could be from: * * Embedded in the animation file as a base64 string. * * In the same directory as the animation file. * * In the same zip file as the animation file. * * Returned from an {@link ImageAssetDelegate}. * or null if the image doesn't exist from any of those places. */ @Nullable public LottieImageAsset getLottieImageAssetForId(String id) { LottieComposition composition = this.composition; if (composition == null) { return null; } return composition.getImages().get(id); } private ImageAssetManager getImageAssetManager() { if (getCallback() == null) { // We can't get a bitmap since we can't get a Context from the callback. return null; } if (imageAssetManager != null && !imageAssetManager.hasSameContext(getContext())) { imageAssetManager = null; } if (imageAssetManager == null) { imageAssetManager = new ImageAssetManager(getCallback(), imageAssetsFolder, imageAssetDelegate, composition.getImages()); } return imageAssetManager; } @Nullable public Typeface getTypeface(String fontFamily, String style) { FontAssetManager assetManager = getFontAssetManager(); if (assetManager != null) { return assetManager.getTypeface(fontFamily, style); } return null; } private FontAssetManager getFontAssetManager() { if (getCallback() == null) { // We can't get a bitmap since we can't get a Context from the callback. return null; } if (fontAssetManager == null) { fontAssetManager = new FontAssetManager(getCallback(), fontAssetDelegate); } return fontAssetManager; } @Nullable private Context getContext() { Callback callback = getCallback(); if (callback == null) { return null; } if (callback instanceof View) { return ((View) callback).getContext(); } return null; } @Override public boolean setVisible(boolean visible, boolean restart) { // Sometimes, setVisible(false) gets called twice in a row. If we don't check wasNotVisibleAlready, we could // wind up clearing the onVisibleAction value for the second call. boolean wasNotVisibleAlready = !isVisible(); boolean ret = super.setVisible(visible, restart); if (visible) { if (onVisibleAction == OnVisibleAction.PLAY) { playAnimation(); } else if (onVisibleAction == OnVisibleAction.RESUME) { resumeAnimation(); } } else { if (animator.isRunning()) { pauseAnimation(); onVisibleAction = OnVisibleAction.RESUME; } else if (!wasNotVisibleAlready) { onVisibleAction = OnVisibleAction.NONE; } } return ret; } /** * These Drawable.Callback methods proxy the calls so that this is the drawable that is * actually invalidated, not a child one which will not pass the view's validateDrawable check. */ @Override public void invalidateDrawable(@NonNull Drawable who) { Callback callback = getCallback(); if (callback == null) { return; } callback.invalidateDrawable(this); } @Override public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { Callback callback = getCallback(); if (callback == null) { return; } callback.scheduleDrawable(this, what, when); } @Override public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { Callback callback = getCallback(); if (callback == null) { return; } callback.unscheduleDrawable(this, what); } /** * Hardware accelerated render path. */ private void drawDirectlyToCanvas(Canvas canvas) { CompositionLayer compositionLayer = this.compositionLayer; LottieComposition composition = this.composition; if (compositionLayer == null || composition == null) { return; } renderingMatrix.reset(); Rect bounds = getBounds(); if (!bounds.isEmpty()) { // In fitXY mode, the scale doesn't take effect. float scaleX = bounds.width() / (float) composition.getBounds().width(); float scaleY = bounds.height() / (float) composition.getBounds().height(); renderingMatrix.preScale(scaleX, scaleY); } compositionLayer.draw(canvas, renderingMatrix, alpha); } /** * Software accelerated render path. * * This draws the animation to an internally managed bitmap and then draws the bitmap to the original canvas. * * @see LottieAnimationView#setRenderMode(RenderMode) */ private void renderAndDrawAsBitmap(Canvas originalCanvas, CompositionLayer compositionLayer) { if (composition == null || compositionLayer == null) { return; } ensureSoftwareRenderingObjectsInitialized(); //noinspection deprecation originalCanvas.getMatrix(softwareRenderingOriginalCanvasMatrix); // Get the canvas clip bounds and map it to the coordinate space of canvas with it's current transform. originalCanvas.getClipBounds(canvasClipBounds); convertRect(canvasClipBounds, canvasClipBoundsRectF); softwareRenderingOriginalCanvasMatrix.mapRect(canvasClipBoundsRectF); convertRect(canvasClipBoundsRectF, canvasClipBounds); if (clipToCompositionBounds) { // Start with the intrinsic bounds. This will later be unioned with the clip bounds to find the // smallest possible render area. softwareRenderingTransformedBounds.set(0f, 0f, getIntrinsicWidth(), getIntrinsicHeight()); } else { // Calculate the full bounds of the animation. compositionLayer.getBounds(softwareRenderingTransformedBounds, null, false); } // Transform the animation bounds to the bounds that they will render to on the canvas. softwareRenderingOriginalCanvasMatrix.mapRect(softwareRenderingTransformedBounds); // The bounds are usually intrinsicWidth x intrinsicHeight. If they are different, an external source is scaling this drawable. // This is how ImageView.ScaleType.FIT_XY works. Rect bounds = getBounds(); float scaleX = bounds.width() / (float) getIntrinsicWidth(); float scaleY = bounds.height() / (float) getIntrinsicHeight(); scaleRect(softwareRenderingTransformedBounds, scaleX, scaleY); if (!ignoreCanvasClipBounds()) { softwareRenderingTransformedBounds.intersect(canvasClipBounds.left, canvasClipBounds.top, canvasClipBounds.right, canvasClipBounds.bottom); } int renderWidth = (int) Math.ceil(softwareRenderingTransformedBounds.width()); int renderHeight = (int) Math.ceil(softwareRenderingTransformedBounds.height()); if (renderWidth == 0 || renderHeight == 0) { return; } ensureSoftwareRenderingBitmap(renderWidth, renderHeight); if (isDirty) { renderingMatrix.set(softwareRenderingOriginalCanvasMatrix); renderingMatrix.preScale(scaleX, scaleY); // We want to render the smallest bitmap possible. If the animation doesn't start at the top left, we translate the canvas and shrink the // bitmap to avoid allocating and copying the empty space on the left and top. renderWidth and renderHeight take this into account. renderingMatrix.postTranslate(-softwareRenderingTransformedBounds.left, -softwareRenderingTransformedBounds.top); softwareRenderingBitmap.eraseColor(0); compositionLayer.draw(softwareRenderingCanvas, renderingMatrix, alpha); // Calculate the dst bounds. // We need to map the rendered coordinates back to the canvas's coordinates. To do so, we need to invert the transform // of the original canvas. // Take the bounds of the rendered animation and map them to the canvas's coordinates. // This is similar to the src rect above but the src bound may have a left and top offset. softwareRenderingOriginalCanvasMatrix.invert(softwareRenderingOriginalCanvasMatrixInverse); softwareRenderingOriginalCanvasMatrixInverse.mapRect(softwareRenderingDstBoundsRectF, softwareRenderingTransformedBounds); convertRect(softwareRenderingDstBoundsRectF, softwareRenderingDstBoundsRect); } softwareRenderingSrcBoundsRect.set(0, 0, renderWidth, renderHeight); originalCanvas.drawBitmap(softwareRenderingBitmap, softwareRenderingSrcBoundsRect, softwareRenderingDstBoundsRect, softwareRenderingPaint); } private void ensureSoftwareRenderingObjectsInitialized() { if (softwareRenderingCanvas != null) { return; } softwareRenderingCanvas = new Canvas(); softwareRenderingTransformedBounds = new RectF(); softwareRenderingOriginalCanvasMatrix = new Matrix(); softwareRenderingOriginalCanvasMatrixInverse = new Matrix(); canvasClipBounds = new Rect(); canvasClipBoundsRectF = new RectF(); softwareRenderingPaint = new LPaint(); softwareRenderingSrcBoundsRect = new Rect(); softwareRenderingDstBoundsRect = new Rect(); softwareRenderingDstBoundsRectF = new RectF(); } private void ensureSoftwareRenderingBitmap(int renderWidth, int renderHeight) { if (softwareRenderingBitmap == null || softwareRenderingBitmap.getWidth() < renderWidth || softwareRenderingBitmap.getHeight() < renderHeight) { // The bitmap is larger. We need to create a new one. softwareRenderingBitmap = Bitmap.createBitmap(renderWidth, renderHeight, Bitmap.Config.ARGB_8888); softwareRenderingCanvas.setBitmap(softwareRenderingBitmap); isDirty = true; } else if (softwareRenderingBitmap.getWidth() > renderWidth || softwareRenderingBitmap.getHeight() > renderHeight) { // The bitmap is smaller. Take subset of the original. softwareRenderingBitmap = Bitmap.createBitmap(softwareRenderingBitmap, 0, 0, renderWidth, renderHeight); softwareRenderingCanvas.setBitmap(softwareRenderingBitmap); isDirty = true; } } /** * Convert a RectF to a Rect */ private void convertRect(RectF src, Rect dst) { dst.set( (int) Math.floor(src.left), (int) Math.floor(src.top), (int) Math.ceil(src.right), (int) Math.ceil(src.bottom) ); } /** * Convert a Rect to a RectF */ private void convertRect(Rect src, RectF dst) { dst.set( src.left, src.top, src.right, src.bottom); } private void scaleRect(RectF rect, float scaleX, float scaleY) { rect.set( rect.left * scaleX, rect.top * scaleY, rect.right * scaleX, rect.bottom * scaleY ); } /** * When a View's parent has clipChildren set to false, it doesn't affect the clipBound * of its child canvases so we should explicitly check for it and draw the full animation * bounds instead. */ private boolean ignoreCanvasClipBounds() { Callback callback = getCallback(); if (!(callback instanceof View)) { // If the callback isn't a view then respect the canvas's clip bounds. return false; } ViewParent parent = ((View) callback).getParent(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && parent instanceof ViewGroup) { return !((ViewGroup) parent).getClipChildren(); } // Unlikely to ever happen. If the callback is a View, its parent should be a ViewGroup. return false; } }
package com.lucidera.luciddb.test.bh; import com.lucidera.jdbc.*; import java.io.*; import java.util.regex.*; import net.sf.farrago.catalog.*; import net.sf.farrago.jdbc.engine.*; import net.sf.farrago.util.*; import org.eigenbase.blackhawk.compose.AutoTest; import org.eigenbase.blackhawk.compose.Parameters; import org.eigenbase.blackhawk.compose.TestContext; import sqlline.SqlLine; /** * Simple sql test for bh-base test in the luciddb area * * @author boris * @version $Id$ */ public class SqlTest extends AutoTest { String[] args; String sqlFile; private OutputStream logOutputStream; File sqlFileSansExt; File logFile; File refFile; /** Diff masks defined so far */ // private List diffMasks; private String diffMasks; Matcher compiledDiffMatcher; private String ignorePatterns; Matcher compiledIgnoreMatcher; public SqlTest(TestContext tc) throws Exception { super(tc); // set luciddb-specific properties System.setProperty("net.sf.farrago.defaultSessionFactoryLibraryName", "class:com.lucidera.farrago.LucidDbSessionFactory"); System.setProperty("net.sf.farrago.test.jdbcDriverClass", "com.lucidera.jdbc.LucidDbLocalDriver"); Parameters param = tc.getParameters(); // obtain sql-file parameter - required sqlFile = param.getString("sql-file"); // following parameters are not required String driverName = param.getString("jdbc-driver", ""); String username = param.getString("username", ""); if (username.equals("")) { username = FarragoCatalogInit.SA_USER_NAME; } String passwd = param.getString("passwd", ""); String urlPrefix = param.getString("url", ""); if (urlPrefix.equals("")) { if (driverName.equals("")) { driverName = FarragoProperties.instance(). testJdbcDriverClass.get(); } Class clazz = Class.forName(driverName); LucidDbLocalDriver driver = (LucidDbLocalDriver) clazz.newInstance(); urlPrefix = driver.getUrlPrefix(); } assert (sqlFile.endsWith(".sql")); sqlFileSansExt = new File(sqlFile.substring(0, sqlFile.length() - 4)); args = new String [] { "-u", urlPrefix, "-d", driverName, "-n", username, "-p", passwd, "--force=true", "--silent=true", "--showWarnings=false", "--maxWidth=1024" }; } public boolean testSql() { diffMasks = ""; addDiffMask("\\$Id.*\\$"); PrintStream savedOut = System.out; PrintStream savedErr = System.err; FileInputStream inputStream = null; try { // read from the specified file inputStream = new FileInputStream(sqlFile.toString()); // to make sure the connection is closed properly, append the // !quit command String quitCommand = "\n!quit\n"; ByteArrayInputStream quitStream = new ByteArrayInputStream(quitCommand.getBytes()); SequenceInputStream sequenceStream = new SequenceInputStream(inputStream, quitStream); OutputStream outputStream = openTestLogOutputStream(sqlFileSansExt); PrintStream printStream = new PrintStream(outputStream); System.setOut(printStream); System.setErr(printStream); // tell SqlLine not to exit (this boolean is active-low) System.setProperty("sqlline.system.exit", "true"); SqlLine.mainWithInputRedirection(args, sequenceStream); printStream.flush(); diffTestLog(); } catch (Exception e) { return failure("Failed with Unexpected Exception: " + e.toString(),e); } finally { System.setOut(savedOut); System.setErr(savedErr); try { inputStream.close(); } catch (Throwable t) { tc.inform("ERROR INPUT STREAM CLOSE THREW EXCEPTION!" + t.toString()); } } return success("No problem"); } /** * NOTE: cut and pasted from DiffTestCase.java * Initializes a diff-based test, overriding the default * log file naming scheme altogether. * * @param testFileSansExt full path to log filename, without .log/.ref * extension */ protected OutputStream openTestLogOutputStream(File testFileSansExt) throws IOException { assert (logOutputStream == null); logFile = new File(testFileSansExt.toString() + ".log"); logFile.delete(); refFile = new File(testFileSansExt.toString() + ".ref"); logOutputStream = new FileOutputStream(logFile); return logOutputStream; } /** * Finishes a diff-based test. Output that was written to the Writer * returned by openTestLog is diffed against a .ref file, and if any * differences are detected, the test case fails. Note that the diff * used is just a boolean test, and does not create any .dif ouput. * * <p> * NOTE: if you wrap the Writer returned by openTestLog() (e.g. with a * PrintWriter), be sure to flush the wrapping Writer before calling this * method. * </p> */ protected void diffTestLog() throws IOException, Exception { int n = 0; assert (logOutputStream != null); logOutputStream.close(); logOutputStream = null; if (!refFile.exists()) { throw new Exception("Reference file " + refFile + " does not exist"); } // TODO: separate utility method somewhere FileReader logReader = null; FileReader refReader = null; try { /** don't do the gc trick for now if (compiledIgnoreMatcher != null) { if (gcInterval != 0) { n++; if ( n == gcInterval) { n = 0; System.gc(); } } } **/ logReader = new FileReader(logFile); refReader = new FileReader(refFile); LineNumberReader logLineReader = new LineNumberReader(logReader); LineNumberReader refLineReader = new LineNumberReader(refReader); for (;;) { String logLine = logLineReader.readLine(); String refLine = refLineReader.readLine(); while (logLine != null && matchIgnorePatterns(logLine)) { // System.out.println("logMatch Line:" + logLine); logLine = logLineReader.readLine(); } while (refLine != null && matchIgnorePatterns(refLine)) { // System.out.println("refMatch Line:" + logLine); refLine = refLineReader.readLine(); } if ((logLine == null) || (refLine == null)) { if (logLine != null) { diffFail(logFile, logLineReader.getLineNumber()); } if (refLine != null) { diffFail(logFile, refLineReader.getLineNumber()); } break; } logLine = applyDiffMask(logLine); refLine = applyDiffMask(refLine); if (!logLine.equals(refLine)) { diffFail(logFile, logLineReader.getLineNumber()); } } } finally { if (logReader != null) { logReader.close(); } if (refReader != null) { refReader.close(); } } // no diffs detected, so delete redundant .log file logFile.delete(); } /** * Adds a diff mask. Strings matching the given regular expression * will be masked before diffing. This can be used to suppress * spurious diffs on a case-by-case basis. * * @param mask a regular expression, as per String.replaceAll */ protected void addDiffMask(String mask) { // diffMasks.add(mask); if (diffMasks.length() == 0) { diffMasks = mask; } else { diffMasks = diffMasks + "|" + mask; } Pattern compiledDiffPattern = Pattern.compile(diffMasks); compiledDiffMatcher = compiledDiffPattern.matcher(""); } protected void addIgnorePattern(String javaPattern) { if (ignorePatterns.length() == 0) { ignorePatterns = javaPattern; } else { ignorePatterns = ignorePatterns + "|" + javaPattern; } Pattern compiledIgnorePattern = Pattern.compile(ignorePatterns); compiledIgnoreMatcher = compiledIgnorePattern.matcher(""); } private String applyDiffMask(String s) { if (compiledDiffMatcher != null) { compiledDiffMatcher.reset(s); // we assume most of lines do not match // so compiled matches will be faster than replaceAll. if (compiledDiffMatcher.find()) { return s.replaceAll(diffMasks, "XYZZY"); } } return s; } private boolean matchIgnorePatterns(String s) { if (compiledIgnoreMatcher != null) { compiledIgnoreMatcher.reset(s); return compiledIgnoreMatcher.matches(); } return false; } private void diffFail ( File logFile, int lineNumber) throws Exception { tc.inform("DIFF FAILED!"); final String message = "diff detected at line " + lineNumber + " in " + logFile; throw new Exception(message + fileContents(refFile) + fileContents(logFile)); } /** * Returns the contents of a file as a string. */ private static String fileContents(File file) { try { char[] buf = new char[2048]; final FileReader reader = new FileReader(file); int readCount; final StringWriter writer = new StringWriter(); while ((readCount = reader.read(buf)) >= 0) { writer.write(buf, 0, readCount); } return writer.toString(); } catch (IOException e) { throw new RuntimeException(e); } } } // End SqlTest.java
package controller; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import utils.ResponseCode; import utils.ResultData; import javax.ws.rs.core.MediaType; @RestController @RequestMapping("/message") public class MessageController { private Logger logger = LoggerFactory.getLogger(MessageController.class); @RequestMapping(method = RequestMethod.GET, value = "/sendmessage") public ModelAndView messagenotify() { ModelAndView view = new ModelAndView(); view.setViewName("/backend/order/notify"); return view; } @RequestMapping(method = RequestMethod.POST, value = "/notify") public ResultData send(String phone) { ResultData result = new ResultData(); if (StringUtils.isEmpty(phone)) { result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription("Phone number cannot be empty"); return result; } String message = "025"; Client client = Client.create(); WebResource webResource = client.resource( "http://microservice.gmair.net/message/send/single"); MultivaluedMapImpl formData = new MultivaluedMapImpl(); formData.add("phone", phone); formData.add("text", message); ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED). post(ClientResponse.class, formData); System.out.println("response:" + response); result.setResponseCode(ResponseCode.RESPONSE_OK); return result; } @RequestMapping(method = RequestMethod.POST, value = "/goodsdeliver") public ResultData deliverySend(String phone) { ResultData result = new ResultData(); if (StringUtils.isEmpty(phone)) { result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription("Phone number cannot be empty"); return result; } String message = "gmxfkf"; Client client = Client.create(); WebResource webResource = client.resource( "http://microservice.gmair.net/message/send/single"); MultivaluedMapImpl formData = new MultivaluedMapImpl(); formData.add("phone", phone); formData.add("text", message); ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED). post(ClientResponse.class, formData); System.out.println("response:" + response); result.setResponseCode(ResponseCode.RESPONSE_OK); return result; } }
package battlecode.world; import battlecode.common.*; import battlecode.schema.*; import battlecode.schema.GameMap; import battlecode.server.TeamMapping; import battlecode.util.FlatHelpers; import com.google.flatbuffers.FlatBufferBuilder; import org.apache.commons.lang3.ArrayUtils; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.List; @Ignore /** * Lets maps be built easily, for testing purposes. */ public class TestMapBuilder { private String name; private MapLocation origin; private float width; private float height; private int seed; private int rounds; private List<BodyInfo> bodies; public TestMapBuilder(String name, float oX, float oY, float width, float height, int seed, int rounds) { this(name, new MapLocation(oX, oY), width, height, seed, rounds); } public TestMapBuilder(String name, MapLocation origin, float width, float height, int seed, int rounds) { this.name = name; this.origin = origin; this.width = width; this.height = height; this.seed = seed; this.bodies = new ArrayList<>(); } public TestMapBuilder addRobot(int id, Team team, RobotType type, MapLocation loc){ bodies.add(new RobotInfo( id, team, type, loc, type.getStartingHealth(), 0, 0 )); return this; } public TestMapBuilder addNeutralTree(int id, MapLocation loc, float radius, int containedBullets, RobotType containedBody){ bodies.add(new TreeInfo( id, Team.NEUTRAL, loc, radius, 0, containedBullets, containedBody )); return this; } public TestMapBuilder addBody(BodyInfo info) { bodies.add(info); return this; } public LiveMap build() { return new LiveMap( width, height, origin, seed, GameConstants.GAME_DEFAULT_ROUNDS, name, bodies.toArray(new BodyInfo[bodies.size()]) ); } }
package ed.lang.python; import static org.testng.AssertJUnit.assertEquals; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; import org.python.core.*; import ed.js.Encoding; import ed.appserver.JSFileLibrary; import ed.appserver.templates.djang10.Printer.RedirectedPrinter; import ed.js.JSLocalFile; import ed.js.JSObjectBase; import ed.js.JSString; import ed.js.engine.Scope; import ed.js.func.JSFunctionCalls1; import ed.log.Level; import ed.log.Logger; public class PythonReloadTest extends ed.TestCase { private static final String TEST_DIR = "/tmp/"; private static final File testDir = new File(TEST_DIR); //time to wait between file modifications to allow the fs to update the timestamps private static final long SLEEP_MS = 5000; @BeforeClass public void setUp() throws IOException, InterruptedException { if(!testDir.mkdir() && !testDir.exists()) throw new IOException("Failed to create test dir"); } @Test public void test() throws IOException, InterruptedException { Scope globalScope = initScope(); RedirectedPrinter printer = new RedirectedPrinter(); globalScope.set("print", printer); globalScope.set("counter", 0); JSFileLibrary fileLib = (JSFileLibrary)globalScope.get("local"); writeTest1File1(); writeTest1File2(); writeTest1File3(); Scope oldScope = Scope.getThreadLocal(); globalScope.makeThreadLocal(); try { globalScope.eval("local.file1();"); assertRan3(globalScope); clearScope(globalScope); Thread.sleep(SLEEP_MS); writeTest1File2(); PyObject m = Py.getSystemState().__findattr__("modules"); globalScope.eval("local.file1();"); assertRan2(globalScope); Thread.sleep(SLEEP_MS); System.out.println("New test"); clearScope(globalScope); writeTest2File2(); globalScope.eval("local.file1();"); assertRan2(globalScope); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan1(globalScope); Thread.sleep(SLEEP_MS); writeTest2File2(); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan2(globalScope); Thread.sleep(SLEEP_MS); writeTest3File2(); writeTest3File3(); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan3(globalScope); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan1(globalScope); Thread.sleep(SLEEP_MS); writeTest3File2(); writeTest3File3(); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan3(globalScope); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan1(globalScope); Thread.sleep(SLEEP_MS); writeTest3File3(); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan3(globalScope); } finally { if(oldScope != null) oldScope.makeThreadLocal(); else Scope.clearThreadLocal(); try { //rdelete(testDir); } catch (Exception e) { } } } private static void rdelete(File f) { if(f.isDirectory()) { for(File sf : f.listFiles()) rdelete(sf); } f.delete(); } private Scope initScope() { Scope oldScope = Scope.getThreadLocal(); Scope globalScope = Scope.newGlobal().child(); globalScope.setGlobal(true); globalScope.makeThreadLocal(); try { //Load native objects Logger log = Logger.getRoot(); globalScope.set("log", log); log.makeThreadLocal(); Map<String, JSFileLibrary> rootFiles = new HashMap<String, JSFileLibrary>(); rootFiles.put("local", new JSFileLibrary(new File(TEST_DIR), "local", globalScope)); for(Map.Entry<String, JSFileLibrary> rootFileLib : rootFiles.entrySet()) globalScope.set(rootFileLib.getKey(), rootFileLib.getValue()); Encoding.install(globalScope); //JSHelper helper = JSHelper.install(globalScope, rootFiles, log); globalScope.set("SYSOUT", new JSFunctionCalls1() { public Object call(Scope scope, Object p0, Object[] extra) { System.out.println(p0); return null; } }); globalScope.put("openFile", new JSFunctionCalls1() { public Object call(Scope s, Object name, Object extra[]) { return new JSLocalFile(new File(TEST_DIR), name.toString()); } }, true); //helper.addTemplateRoot(globalScope, new JSString("/local")); } finally { if(oldScope != null) oldScope.makeThreadLocal(); else Scope.clearThreadLocal(); } return globalScope; } private void clearScope(Scope s){ s.set("ranFile1", 0); s.set("ranFile2", 0); s.set("ranFile3", 0); } // file1 -> file2 -> file3 private void writeTest1File1() throws IOException{ fillFile(1, true); } private void writeTest1File2() throws IOException{ fillFile(2, true); } private void writeTest1File3() throws IOException{ fillFile(3, false); } private void setTime(PrintWriter writer, String name){ writer.println("_10gen."+name+" = _10gen.counter; _10gen.counter += 1"); } private void fillFile(int n, boolean importNext) throws IOException{ File f = new File(testDir, "file"+n+".py"); PrintWriter writer = new PrintWriter(f); writer.println("import _10gen"); writer.println("_10gen.ranFile"+n+" = 1"); setTime(writer, "startFile1"); if(importNext) writer.println("import file"+(n+1)); setTime(writer, "endFile1"); writer.close(); } private void writeTest2File2() throws IOException{ File f = new File(testDir, "file2.py"); PrintWriter writer = new PrintWriter(f); writer.println("import _10gen"); writer.println("_10gen.ranFile2 = 1"); writer.println("import file2"); writer.close(); } private void writeTest3File2() throws IOException{ fillFile(2, true); } private void writeTest3File3() throws IOException{ File f = new File(testDir, "file3.py"); PrintWriter writer = new PrintWriter(f); writer.println("import _10gen"); writer.println("_10gen.ranFile3 = 1"); writer.println("import file2"); writer.close(); } private void assertRan1(Scope s){ assertEquals(s.get("ranFile1"), 1); assertEquals(s.get("ranFile2"), 0); assertEquals(s.get("ranFile3"), 0); } private void assertRan2(Scope s){ assertEquals(s.get("ranFile1"), 1); assertEquals(s.get("ranFile2"), 1); assertEquals(s.get("ranFile3"), 0); } private void assertRan3(Scope s){ assertEquals(s.get("ranFile1"), 1); assertEquals(s.get("ranFile2"), 1); assertEquals(s.get("ranFile3"), 1); } public static void main(String [] args){ (new PythonReloadTest()).runConsole(); } }
package com.github.jitpack; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class AppTest { App app = new App(); @Test public void testApp() { assertEquals("Hello world", app.greet("world")); } @Test public void testTrue() throws Exception { Thread.sleep(1000); assertTrue( true ); } @Test public void testFalse() throws Exception { Thread.sleep(1000); assertTrue( false ); } }
package javax.time; import static javax.time.MonthOfYear.FEBRUARY; import static javax.time.MonthOfYear.JANUARY; import static javax.time.MonthOfYear.JUNE; import static javax.time.calendrical.ISODateTimeRule.DAY_OF_WEEK; import static javax.time.calendrical.ISODateTimeRule.MONTH_OF_YEAR; import static javax.time.calendrical.ISODateTimeRule.QUARTER_OF_YEAR; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; import java.io.Serializable; import java.util.Locale; import javax.time.calendrical.Calendrical; import javax.time.calendrical.IllegalCalendarFieldValueException; import javax.time.format.TextStyle; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Test MonthOfYear. * * @author Michael Nascimento Santos * @author Stephen Colebourne */ @Test public class TestMonthOfYear { private static final int MAX_LENGTH = 12; @BeforeMethod (groups={"tck", "implementation"}) public void setUp() { } @Test(groups={"implementation"}) public void test_interfaces() { assertTrue(Enum.class.isAssignableFrom(MonthOfYear.class)); assertTrue(Serializable.class.isAssignableFrom(MonthOfYear.class)); assertTrue(Comparable.class.isAssignableFrom(MonthOfYear.class)); assertTrue(Calendrical.class.isAssignableFrom(MonthOfYear.class)); } @Test(groups={"tck"}) public void test_rule() { assertEquals(MonthOfYear.rule().getName(), "MonthOfYear"); assertEquals(MonthOfYear.rule().getType(), MonthOfYear.class); } @Test(groups={"tck", "implementation"}) public void test_factory_int_singleton() { for (int i = 1; i <= MAX_LENGTH; i++) { MonthOfYear test = MonthOfYear.of(i); assertEquals(test.getValue(), i); assertSame(MonthOfYear.of(i), test); } } @Test(expectedExceptions=IllegalCalendarFieldValueException.class, groups={"tck"}) public void test_factory_int_tooLow() { MonthOfYear.of(0); } @Test(expectedExceptions=IllegalCalendarFieldValueException.class, groups={"tck"}) public void test_factory_int_tooHigh() { MonthOfYear.of(13); } @Test(groups={"tck"}) public void test_factory_Calendricals() { assertEquals(MonthOfYear.from(LocalDate.of(2011, 6, 6)), JUNE); assertEquals(MonthOfYear.from(MONTH_OF_YEAR.field(1)), JANUARY); assertEquals(MonthOfYear.from(LocalDate.of(2011, 6, 6), JUNE.toField()), JUNE); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_factory_Calendricals_invalid_clash() { MonthOfYear.from(JANUARY, FEBRUARY.toField()); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_factory_Calendricals_invalid_noDerive() { MonthOfYear.from(LocalTime.of(12, 30)); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_factory_Calendricals_invalid_empty() { MonthOfYear.from(); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_factory_Calendricals_nullArray() { MonthOfYear.from((Calendrical[]) null); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_factory_Calendricals_null() { MonthOfYear.from((Calendrical) null); } // get() @Test(groups={"tck"}) public void test_get() { assertEquals(MonthOfYear.JANUARY.get(MonthOfYear.rule()), MonthOfYear.JANUARY); assertEquals(MonthOfYear.OCTOBER.get(MonthOfYear.rule()), MonthOfYear.OCTOBER); assertEquals(MonthOfYear.JANUARY.get(MONTH_OF_YEAR), MONTH_OF_YEAR.field(1)); assertEquals(MonthOfYear.APRIL.get(MONTH_OF_YEAR), MONTH_OF_YEAR.field(4)); assertEquals(MonthOfYear.JULY.get(QuarterOfYear.rule()), QuarterOfYear.Q3); assertEquals(MonthOfYear.MAY.get(QUARTER_OF_YEAR), QUARTER_OF_YEAR.field(2)); assertEquals(MonthOfYear.FEBRUARY.get(DAY_OF_WEEK), null); } // getText() @Test(groups={"tck"}) public void test_getText() { assertEquals(MonthOfYear.JANUARY.getText(TextStyle.SHORT, Locale.US), "Jan"); } @Test(expectedExceptions = NullPointerException.class, groups={"tck"}) public void test_getText_nullStyle() { MonthOfYear.JANUARY.getText(null, Locale.US); } @Test(expectedExceptions = NullPointerException.class, groups={"tck"}) public void test_getText_nullLocale() { MonthOfYear.JANUARY.getText(TextStyle.FULL, null); } // next() @Test(groups={"tck"}) public void test_next() { assertEquals(MonthOfYear.JANUARY.next(), MonthOfYear.FEBRUARY); assertEquals(MonthOfYear.FEBRUARY.next(), MonthOfYear.MARCH); assertEquals(MonthOfYear.MARCH.next(), MonthOfYear.APRIL); assertEquals(MonthOfYear.APRIL.next(), MonthOfYear.MAY); assertEquals(MonthOfYear.MAY.next(), MonthOfYear.JUNE); assertEquals(MonthOfYear.JUNE.next(), MonthOfYear.JULY); assertEquals(MonthOfYear.JULY.next(), MonthOfYear.AUGUST); assertEquals(MonthOfYear.AUGUST.next(), MonthOfYear.SEPTEMBER); assertEquals(MonthOfYear.SEPTEMBER.next(), MonthOfYear.OCTOBER); assertEquals(MonthOfYear.OCTOBER.next(), MonthOfYear.NOVEMBER); assertEquals(MonthOfYear.NOVEMBER.next(), MonthOfYear.DECEMBER); assertEquals(MonthOfYear.DECEMBER.next(), MonthOfYear.JANUARY); } // previous() @Test(groups={"tck"}) public void test_previous() { assertEquals(MonthOfYear.JANUARY.previous(), MonthOfYear.DECEMBER); assertEquals(MonthOfYear.FEBRUARY.previous(), MonthOfYear.JANUARY); assertEquals(MonthOfYear.MARCH.previous(), MonthOfYear.FEBRUARY); assertEquals(MonthOfYear.APRIL.previous(), MonthOfYear.MARCH); assertEquals(MonthOfYear.MAY.previous(), MonthOfYear.APRIL); assertEquals(MonthOfYear.JUNE.previous(), MonthOfYear.MAY); assertEquals(MonthOfYear.JULY.previous(), MonthOfYear.JUNE); assertEquals(MonthOfYear.AUGUST.previous(), MonthOfYear.JULY); assertEquals(MonthOfYear.SEPTEMBER.previous(), MonthOfYear.AUGUST); assertEquals(MonthOfYear.OCTOBER.previous(), MonthOfYear.SEPTEMBER); assertEquals(MonthOfYear.NOVEMBER.previous(), MonthOfYear.OCTOBER); assertEquals(MonthOfYear.DECEMBER.previous(), MonthOfYear.NOVEMBER); } // roll(int) @Test(groups={"tck"}) public void test_roll_january() { assertEquals(MonthOfYear.JANUARY.roll(-12), MonthOfYear.JANUARY); assertEquals(MonthOfYear.JANUARY.roll(-11), MonthOfYear.FEBRUARY); assertEquals(MonthOfYear.JANUARY.roll(-10), MonthOfYear.MARCH); assertEquals(MonthOfYear.JANUARY.roll(-9), MonthOfYear.APRIL); assertEquals(MonthOfYear.JANUARY.roll(-8), MonthOfYear.MAY); assertEquals(MonthOfYear.JANUARY.roll(-7), MonthOfYear.JUNE); assertEquals(MonthOfYear.JANUARY.roll(-6), MonthOfYear.JULY); assertEquals(MonthOfYear.JANUARY.roll(-5), MonthOfYear.AUGUST); assertEquals(MonthOfYear.JANUARY.roll(-4), MonthOfYear.SEPTEMBER); assertEquals(MonthOfYear.JANUARY.roll(-3), MonthOfYear.OCTOBER); assertEquals(MonthOfYear.JANUARY.roll(-2), MonthOfYear.NOVEMBER); assertEquals(MonthOfYear.JANUARY.roll(-1), MonthOfYear.DECEMBER); assertEquals(MonthOfYear.JANUARY.roll(0), MonthOfYear.JANUARY); assertEquals(MonthOfYear.JANUARY.roll(1), MonthOfYear.FEBRUARY); assertEquals(MonthOfYear.JANUARY.roll(2), MonthOfYear.MARCH); assertEquals(MonthOfYear.JANUARY.roll(3), MonthOfYear.APRIL); assertEquals(MonthOfYear.JANUARY.roll(4), MonthOfYear.MAY); assertEquals(MonthOfYear.JANUARY.roll(5), MonthOfYear.JUNE); assertEquals(MonthOfYear.JANUARY.roll(6), MonthOfYear.JULY); assertEquals(MonthOfYear.JANUARY.roll(7), MonthOfYear.AUGUST); assertEquals(MonthOfYear.JANUARY.roll(8), MonthOfYear.SEPTEMBER); assertEquals(MonthOfYear.JANUARY.roll(9), MonthOfYear.OCTOBER); assertEquals(MonthOfYear.JANUARY.roll(10), MonthOfYear.NOVEMBER); assertEquals(MonthOfYear.JANUARY.roll(11), MonthOfYear.DECEMBER); assertEquals(MonthOfYear.JANUARY.roll(12), MonthOfYear.JANUARY); } @Test(groups={"tck"}) public void test_roll_july() { assertEquals(MonthOfYear.JULY.roll(-12), MonthOfYear.JULY); assertEquals(MonthOfYear.JULY.roll(-11), MonthOfYear.AUGUST); assertEquals(MonthOfYear.JULY.roll(-10), MonthOfYear.SEPTEMBER); assertEquals(MonthOfYear.JULY.roll(-9), MonthOfYear.OCTOBER); assertEquals(MonthOfYear.JULY.roll(-8), MonthOfYear.NOVEMBER); assertEquals(MonthOfYear.JULY.roll(-7), MonthOfYear.DECEMBER); assertEquals(MonthOfYear.JULY.roll(-6), MonthOfYear.JANUARY); assertEquals(MonthOfYear.JULY.roll(-5), MonthOfYear.FEBRUARY); assertEquals(MonthOfYear.JULY.roll(-4), MonthOfYear.MARCH); assertEquals(MonthOfYear.JULY.roll(-3), MonthOfYear.APRIL); assertEquals(MonthOfYear.JULY.roll(-2), MonthOfYear.MAY); assertEquals(MonthOfYear.JULY.roll(-1), MonthOfYear.JUNE); assertEquals(MonthOfYear.JULY.roll(0), MonthOfYear.JULY); assertEquals(MonthOfYear.JULY.roll(1), MonthOfYear.AUGUST); assertEquals(MonthOfYear.JULY.roll(2), MonthOfYear.SEPTEMBER); assertEquals(MonthOfYear.JULY.roll(3), MonthOfYear.OCTOBER); assertEquals(MonthOfYear.JULY.roll(4), MonthOfYear.NOVEMBER); assertEquals(MonthOfYear.JULY.roll(5), MonthOfYear.DECEMBER); assertEquals(MonthOfYear.JULY.roll(6), MonthOfYear.JANUARY); assertEquals(MonthOfYear.JULY.roll(7), MonthOfYear.FEBRUARY); assertEquals(MonthOfYear.JULY.roll(8), MonthOfYear.MARCH); assertEquals(MonthOfYear.JULY.roll(9), MonthOfYear.APRIL); assertEquals(MonthOfYear.JULY.roll(10), MonthOfYear.MAY); assertEquals(MonthOfYear.JULY.roll(11), MonthOfYear.JUNE); assertEquals(MonthOfYear.JULY.roll(12), MonthOfYear.JULY); } @Test(groups={"tck"}) public void test_roll_largerThanTwelveMonths(){ assertEquals(MonthOfYear.JULY.roll(-13), MonthOfYear.JUNE); assertEquals(MonthOfYear.JULY.roll(13), MonthOfYear.AUGUST); int multipleOfMaxLenghthCloserToIntMaxValue = (Integer.MAX_VALUE/MAX_LENGTH)*MAX_LENGTH; assertEquals(MonthOfYear.JULY.roll(multipleOfMaxLenghthCloserToIntMaxValue), MonthOfYear.JULY); assertEquals(MonthOfYear.JULY.roll(-(multipleOfMaxLenghthCloserToIntMaxValue)), MonthOfYear.JULY); } // lengthInDays(boolean) @Test(groups={"tck"}) public void test_lengthInDays_boolean_notLeapYear() { assertEquals(MonthOfYear.JANUARY.lengthInDays(false), 31); assertEquals(MonthOfYear.FEBRUARY.lengthInDays(false), 28); assertEquals(MonthOfYear.MARCH.lengthInDays(false), 31); assertEquals(MonthOfYear.APRIL.lengthInDays(false), 30); assertEquals(MonthOfYear.MAY.lengthInDays(false), 31); assertEquals(MonthOfYear.JUNE.lengthInDays(false), 30); assertEquals(MonthOfYear.JULY.lengthInDays(false), 31); assertEquals(MonthOfYear.AUGUST.lengthInDays(false), 31); assertEquals(MonthOfYear.SEPTEMBER.lengthInDays(false), 30); assertEquals(MonthOfYear.OCTOBER.lengthInDays(false), 31); assertEquals(MonthOfYear.NOVEMBER.lengthInDays(false), 30); assertEquals(MonthOfYear.DECEMBER.lengthInDays(false), 31); } @Test(groups={"tck"}) public void test_lengthInDays_boolean_leapYear() { assertEquals(MonthOfYear.JANUARY.lengthInDays(true), 31); assertEquals(MonthOfYear.FEBRUARY.lengthInDays(true), 29); assertEquals(MonthOfYear.MARCH.lengthInDays(true), 31); assertEquals(MonthOfYear.APRIL.lengthInDays(true), 30); assertEquals(MonthOfYear.MAY.lengthInDays(true), 31); assertEquals(MonthOfYear.JUNE.lengthInDays(true), 30); assertEquals(MonthOfYear.JULY.lengthInDays(true), 31); assertEquals(MonthOfYear.AUGUST.lengthInDays(true), 31); assertEquals(MonthOfYear.SEPTEMBER.lengthInDays(true), 30); assertEquals(MonthOfYear.OCTOBER.lengthInDays(true), 31); assertEquals(MonthOfYear.NOVEMBER.lengthInDays(true), 30); assertEquals(MonthOfYear.DECEMBER.lengthInDays(true), 31); } // minLengthInDays() @Test(groups={"tck"}) public void test_minLengthInDays() { assertEquals(MonthOfYear.JANUARY.minLengthInDays(), 31); assertEquals(MonthOfYear.FEBRUARY.minLengthInDays(), 28); assertEquals(MonthOfYear.MARCH.minLengthInDays(), 31); assertEquals(MonthOfYear.APRIL.minLengthInDays(), 30); assertEquals(MonthOfYear.MAY.minLengthInDays(), 31); assertEquals(MonthOfYear.JUNE.minLengthInDays(), 30); assertEquals(MonthOfYear.JULY.minLengthInDays(), 31); assertEquals(MonthOfYear.AUGUST.minLengthInDays(), 31); assertEquals(MonthOfYear.SEPTEMBER.minLengthInDays(), 30); assertEquals(MonthOfYear.OCTOBER.minLengthInDays(), 31); assertEquals(MonthOfYear.NOVEMBER.minLengthInDays(), 30); assertEquals(MonthOfYear.DECEMBER.minLengthInDays(), 31); } // maxLengthInDays() @Test(groups={"tck"}) public void test_maxLengthInDays() { assertEquals(MonthOfYear.JANUARY.maxLengthInDays(), 31); assertEquals(MonthOfYear.FEBRUARY.maxLengthInDays(), 29); assertEquals(MonthOfYear.MARCH.maxLengthInDays(), 31); assertEquals(MonthOfYear.APRIL.maxLengthInDays(), 30); assertEquals(MonthOfYear.MAY.maxLengthInDays(), 31); assertEquals(MonthOfYear.JUNE.maxLengthInDays(), 30); assertEquals(MonthOfYear.JULY.maxLengthInDays(), 31); assertEquals(MonthOfYear.AUGUST.maxLengthInDays(), 31); assertEquals(MonthOfYear.SEPTEMBER.maxLengthInDays(), 30); assertEquals(MonthOfYear.OCTOBER.maxLengthInDays(), 31); assertEquals(MonthOfYear.NOVEMBER.maxLengthInDays(), 30); assertEquals(MonthOfYear.DECEMBER.maxLengthInDays(), 31); } // getLastDayOfMonth(boolean) @Test(groups={"tck"}) public void test_getLastDayOfMonth_notLeapYear() { assertEquals(MonthOfYear.JANUARY.getLastDayOfMonth(false), 31); assertEquals(MonthOfYear.FEBRUARY.getLastDayOfMonth(false), 28); assertEquals(MonthOfYear.MARCH.getLastDayOfMonth(false), 31); assertEquals(MonthOfYear.APRIL.getLastDayOfMonth(false), 30); assertEquals(MonthOfYear.MAY.getLastDayOfMonth(false), 31); assertEquals(MonthOfYear.JUNE.getLastDayOfMonth(false), 30); assertEquals(MonthOfYear.JULY.getLastDayOfMonth(false), 31); assertEquals(MonthOfYear.AUGUST.getLastDayOfMonth(false), 31); assertEquals(MonthOfYear.SEPTEMBER.getLastDayOfMonth(false), 30); assertEquals(MonthOfYear.OCTOBER.getLastDayOfMonth(false), 31); assertEquals(MonthOfYear.NOVEMBER.getLastDayOfMonth(false), 30); assertEquals(MonthOfYear.DECEMBER.getLastDayOfMonth(false), 31); } @Test(groups={"tck"}) public void test_getLastDayOfMonth_leapYear() { assertEquals(MonthOfYear.JANUARY.getLastDayOfMonth(true), 31); assertEquals(MonthOfYear.FEBRUARY.getLastDayOfMonth(true), 29); assertEquals(MonthOfYear.MARCH.getLastDayOfMonth(true), 31); assertEquals(MonthOfYear.APRIL.getLastDayOfMonth(true), 30); assertEquals(MonthOfYear.MAY.getLastDayOfMonth(true), 31); assertEquals(MonthOfYear.JUNE.getLastDayOfMonth(true), 30); assertEquals(MonthOfYear.JULY.getLastDayOfMonth(true), 31); assertEquals(MonthOfYear.AUGUST.getLastDayOfMonth(true), 31); assertEquals(MonthOfYear.SEPTEMBER.getLastDayOfMonth(true), 30); assertEquals(MonthOfYear.OCTOBER.getLastDayOfMonth(true), 31); assertEquals(MonthOfYear.NOVEMBER.getLastDayOfMonth(true), 30); assertEquals(MonthOfYear.DECEMBER.getLastDayOfMonth(true), 31); } // getMonthStartDayOfYear(boolean) @Test(groups={"tck"}) public void test_getMonthStartDayOfYear_notLeapYear() { assertEquals(MonthOfYear.JANUARY.getMonthStartDayOfYear(false), 1); assertEquals(MonthOfYear.FEBRUARY.getMonthStartDayOfYear(false), 1 + 31); assertEquals(MonthOfYear.MARCH.getMonthStartDayOfYear(false), 1 + 31 + 28); assertEquals(MonthOfYear.APRIL.getMonthStartDayOfYear(false), 1 + 31 + 28 + 31); assertEquals(MonthOfYear.MAY.getMonthStartDayOfYear(false), 1 + 31 + 28 + 31 + 30); assertEquals(MonthOfYear.JUNE.getMonthStartDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31); assertEquals(MonthOfYear.JULY.getMonthStartDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31 + 30); assertEquals(MonthOfYear.AUGUST.getMonthStartDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31 + 30 + 31); assertEquals(MonthOfYear.SEPTEMBER.getMonthStartDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31); assertEquals(MonthOfYear.OCTOBER.getMonthStartDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30); assertEquals(MonthOfYear.NOVEMBER.getMonthStartDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31); assertEquals(MonthOfYear.DECEMBER.getMonthStartDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30); } @Test(groups={"tck"}) public void test_getMonthStartDayOfYear_leapYear() { assertEquals(MonthOfYear.JANUARY.getMonthStartDayOfYear(true), 1); assertEquals(MonthOfYear.FEBRUARY.getMonthStartDayOfYear(true), 1 + 31); assertEquals(MonthOfYear.MARCH.getMonthStartDayOfYear(true), 1 + 31 + 29); assertEquals(MonthOfYear.APRIL.getMonthStartDayOfYear(true), 1 + 31 + 29 + 31); assertEquals(MonthOfYear.MAY.getMonthStartDayOfYear(true), 1 + 31 + 29 + 31 + 30); assertEquals(MonthOfYear.JUNE.getMonthStartDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31); assertEquals(MonthOfYear.JULY.getMonthStartDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31 + 30); assertEquals(MonthOfYear.AUGUST.getMonthStartDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31 + 30 + 31); assertEquals(MonthOfYear.SEPTEMBER.getMonthStartDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31); assertEquals(MonthOfYear.OCTOBER.getMonthStartDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30); assertEquals(MonthOfYear.NOVEMBER.getMonthStartDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31); assertEquals(MonthOfYear.DECEMBER.getMonthStartDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30); } // getMonthEndDayOfYear(boolean) @Test(groups={"tck"}) public void test_getMonthEndDayOfYear_notLeapYear() { assertEquals(MonthOfYear.JANUARY.getMonthEndDayOfYear(false), 31); assertEquals(MonthOfYear.FEBRUARY.getMonthEndDayOfYear(false), 31 + 28); assertEquals(MonthOfYear.MARCH.getMonthEndDayOfYear(false), 31 + 28 + 31); assertEquals(MonthOfYear.APRIL.getMonthEndDayOfYear(false), 31 + 28 + 31 + 30); assertEquals(MonthOfYear.MAY.getMonthEndDayOfYear(false), 31 + 28 + 31 + 30 + 31); assertEquals(MonthOfYear.JUNE.getMonthEndDayOfYear(false), 31 + 28 + 31 + 30 + 31 + 30); assertEquals(MonthOfYear.JULY.getMonthEndDayOfYear(false), 31 + 28 + 31 + 30 + 31 + 30 + 31); assertEquals(MonthOfYear.AUGUST.getMonthEndDayOfYear(false), 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31); assertEquals(MonthOfYear.SEPTEMBER.getMonthEndDayOfYear(false), 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30); assertEquals(MonthOfYear.OCTOBER.getMonthEndDayOfYear(false), 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31); assertEquals(MonthOfYear.NOVEMBER.getMonthEndDayOfYear(false), 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30); assertEquals(MonthOfYear.DECEMBER.getMonthEndDayOfYear(false), 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31); } @Test(groups={"tck"}) public void test_getMonthEndDayOfYear_leapYear() { assertEquals(MonthOfYear.JANUARY.getMonthEndDayOfYear(true), 31); assertEquals(MonthOfYear.FEBRUARY.getMonthEndDayOfYear(true), 31 + 29); assertEquals(MonthOfYear.MARCH.getMonthEndDayOfYear(true), 31 + 29 + 31); assertEquals(MonthOfYear.APRIL.getMonthEndDayOfYear(true), 31 + 29 + 31 + 30); assertEquals(MonthOfYear.MAY.getMonthEndDayOfYear(true), 31 + 29 + 31 + 30 + 31); assertEquals(MonthOfYear.JUNE.getMonthEndDayOfYear(true), 31 + 29 + 31 + 30 + 31 + 30); assertEquals(MonthOfYear.JULY.getMonthEndDayOfYear(true), 31 + 29 + 31 + 30 + 31 + 30 + 31); assertEquals(MonthOfYear.AUGUST.getMonthEndDayOfYear(true), 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31); assertEquals(MonthOfYear.SEPTEMBER.getMonthEndDayOfYear(true), 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30); assertEquals(MonthOfYear.OCTOBER.getMonthEndDayOfYear(true), 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31); assertEquals(MonthOfYear.NOVEMBER.getMonthEndDayOfYear(true), 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30); assertEquals(MonthOfYear.DECEMBER.getMonthEndDayOfYear(true), 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31); } // getQuarterOfYear() @Test(groups={"tck"}) public void test_getQuarterOfYear() { assertEquals(MonthOfYear.JANUARY.getQuarterOfYear(), QuarterOfYear.Q1); assertEquals(MonthOfYear.FEBRUARY.getQuarterOfYear(), QuarterOfYear.Q1); assertEquals(MonthOfYear.MARCH.getQuarterOfYear(), QuarterOfYear.Q1); assertEquals(MonthOfYear.APRIL.getQuarterOfYear(), QuarterOfYear.Q2); assertEquals(MonthOfYear.MAY.getQuarterOfYear(), QuarterOfYear.Q2); assertEquals(MonthOfYear.JUNE.getQuarterOfYear(), QuarterOfYear.Q2); assertEquals(MonthOfYear.JULY.getQuarterOfYear(), QuarterOfYear.Q3); assertEquals(MonthOfYear.AUGUST.getQuarterOfYear(), QuarterOfYear.Q3); assertEquals(MonthOfYear.SEPTEMBER.getQuarterOfYear(), QuarterOfYear.Q3); assertEquals(MonthOfYear.OCTOBER.getQuarterOfYear(), QuarterOfYear.Q4); assertEquals(MonthOfYear.NOVEMBER.getQuarterOfYear(), QuarterOfYear.Q4); assertEquals(MonthOfYear.DECEMBER.getQuarterOfYear(), QuarterOfYear.Q4); } // getMonthOfQuarter() @Test(groups={"tck"}) public void test_getMonthOfQuarter() { assertEquals(MonthOfYear.JANUARY.getMonthOfQuarter(), 1); assertEquals(MonthOfYear.FEBRUARY.getMonthOfQuarter(), 2); assertEquals(MonthOfYear.MARCH.getMonthOfQuarter(), 3); assertEquals(MonthOfYear.APRIL.getMonthOfQuarter(), 1); assertEquals(MonthOfYear.MAY.getMonthOfQuarter(), 2); assertEquals(MonthOfYear.JUNE.getMonthOfQuarter(), 3); assertEquals(MonthOfYear.JULY.getMonthOfQuarter(), 1); assertEquals(MonthOfYear.AUGUST.getMonthOfQuarter(), 2); assertEquals(MonthOfYear.SEPTEMBER.getMonthOfQuarter(), 3); assertEquals(MonthOfYear.OCTOBER.getMonthOfQuarter(), 1); assertEquals(MonthOfYear.NOVEMBER.getMonthOfQuarter(), 2); assertEquals(MonthOfYear.DECEMBER.getMonthOfQuarter(), 3); } // toField() @Test(groups={"tck"}) public void test_toField() { assertEquals(MonthOfYear.JANUARY.toField(), MONTH_OF_YEAR.field(1)); assertEquals(MonthOfYear.APRIL.toField(), MONTH_OF_YEAR.field(4)); } // toString() @Test(groups={"tck", "implementation"}) public void test_toString() { assertEquals(MonthOfYear.JANUARY.toString(), "JANUARY"); assertEquals(MonthOfYear.FEBRUARY.toString(), "FEBRUARY"); assertEquals(MonthOfYear.MARCH.toString(), "MARCH"); assertEquals(MonthOfYear.APRIL.toString(), "APRIL"); assertEquals(MonthOfYear.MAY.toString(), "MAY"); assertEquals(MonthOfYear.JUNE.toString(), "JUNE"); assertEquals(MonthOfYear.JULY.toString(), "JULY"); assertEquals(MonthOfYear.AUGUST.toString(), "AUGUST"); assertEquals(MonthOfYear.SEPTEMBER.toString(), "SEPTEMBER"); assertEquals(MonthOfYear.OCTOBER.toString(), "OCTOBER"); assertEquals(MonthOfYear.NOVEMBER.toString(), "NOVEMBER"); assertEquals(MonthOfYear.DECEMBER.toString(), "DECEMBER"); } // generated methods @Test(groups={"tck", "implementation"}) public void test_enum() { assertEquals(MonthOfYear.valueOf("JANUARY"), MonthOfYear.JANUARY); assertEquals(MonthOfYear.values()[0], MonthOfYear.JANUARY); } }
package objektwerks; import java.util.*; import org.junit.jupiter.api.Test; enum Level { high, medium, low; int toInt() { return switch(this) { case high -> 1; case medium -> 2; case low -> 3; }; } } class CollectionTest { @Test void enumTest() { var high = Level.high; assert(high.toString().equals("high")); assert(Level.valueOf("high") == high); assert(Level.values().length == 3); for (Level level : Level.values()) { assert(!level.name().isEmpty()); } assert(Level.high.toInt() == 1); assert(Level.medium.toInt() == 2); assert(Level.low.toInt() == 3); } @Test void enumSetTest() { var enumSet = EnumSet.of(Level.high, Level.medium, Level.low); assert(enumSet.size() == 3); assert(enumSet.contains(Level.high)); assert(enumSet.contains(Level.medium)); assert(enumSet.contains(Level.low)); } @Test void enumMapTest() { var enumMap = new EnumMap<Level, Integer>(Level.class); enumMap.put(Level.high, 1); enumMap.put(Level.medium, 2); enumMap.put(Level.low, 3); assert(enumMap.size() == 3); assert(enumMap.get(Level.high) == 1); assert(enumMap.get(Level.medium) == 2); assert(enumMap.get(Level.low) == 3); } @Test void arrayTest() { int[] xs = {1, 2, 3}; assert(xs.length == 3); int[] ys = new int[3]; ys[0] = 1; ys[1] = 2; ys[2] = 3; assert(ys.length == 3); assert(xs != ys); // reference equality assert(Arrays.equals(xs, ys)); // structural equality } @Test void arrayListTest() { int[] xs = {1, 2, 3}; ArrayList<Integer> ys = new ArrayList<>(); for (int x : xs) { ys.add(x); } assert(ys.size() == 3); } @Test void immutableListTest() { var immutableList = List.of(1, 2, 3); assert(immutableList.size() == 3); assert(immutableList.get(0) == 1); } @Test void mutableListTest() { var mutableList = new ArrayList<Integer>(); mutableList.add(1); mutableList.add(2); mutableList.add(3); assert(mutableList.add(4)); assert(mutableList.remove(3) == 4); } @Test void setTest() { var set = Set.of(1, 2, 3); assert(set.size() == 3); assert(set.contains(1)); assert(set.contains(2)); assert(set.contains(3)); } @Test void sortedSetTest() { var set = new TreeSet<Integer>(); set.add(3); set.add(2); set.add(1); assert(set.size() == 3); assert(set.first() == 1); assert(set.last() == 3); } @Test void mapTest() { var map = Map.of(1, 1, 2, 2, 3, 3); assert(map.size() == 3 ); assert(map.get(1) == 1); assert(map.get(2) == 2); assert(map.get(3) == 3); } @Test void sortedMapTest() { var map = new TreeMap<Integer, Integer>(); map.put(1, 1); map.put(2, 2); map.put(3, 3); assert(map.size() == 3); assert(map.firstKey() == 1); assert(map.lastKey() == 3); } }
package org.sagebionetworks; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.io.IOException; import java.util.List; import org.apache.http.HttpException; import org.json.JSONException; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.sagebionetworks.bridge.model.Community; import org.sagebionetworks.bridge.model.versionInfo.BridgeVersionInfo; import org.sagebionetworks.client.BridgeClient; import org.sagebionetworks.client.BridgeClientImpl; import org.sagebionetworks.client.BridgeProfileProxy; import org.sagebionetworks.client.SynapseClient; import org.sagebionetworks.client.SynapseClientImpl; import org.sagebionetworks.client.exceptions.SynapseException; import org.sagebionetworks.client.exceptions.SynapseNotFoundException; import org.sagebionetworks.client.exceptions.SynapseServiceException; import org.sagebionetworks.client.exceptions.SynapseUserException; import org.sagebionetworks.repo.model.ObjectType; import org.sagebionetworks.repo.model.PaginatedResults; import org.sagebionetworks.repo.model.dao.WikiPageKey; import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage; import com.google.common.collect.Lists; /** * Run this integration test as a sanity check to ensure our Synapse Java Client is working * * @author deflaux */ public class IT600BridgeCommunities { public static final int PREVIEW_TIMOUT = 10 * 1000; public static final int RDS_WORKER_TIMEOUT = 1000 * 60; // One min private List<String> communitiesToDelete = Lists.newArrayList(); private static BridgeClient bridge = null; private static BridgeClient bridgeTwo = null; public static BridgeClient createBridgeClient(String user, String pw) throws SynapseException { SynapseClientImpl synapse = new SynapseClientImpl(); synapse.setAuthEndpoint(StackConfiguration.getAuthenticationServicePrivateEndpoint()); synapse.setRepositoryEndpoint(StackConfiguration.getRepositoryServiceEndpoint()); synapse.setFileEndpoint(StackConfiguration.getFileServiceEndpoint()); synapse.login(user, pw); BridgeClientImpl bridge = new BridgeClientImpl(synapse); bridge.setBridgeEndpoint(StackConfiguration.getBridgeServiceEndpoint()); // Return a proxy return BridgeProfileProxy.createProfileProxy(bridge); } public static SynapseClient createSynapse(BridgeClient bridge) { SynapseClient synapse = new SynapseClientImpl(bridge); synapse.setRepositoryEndpoint(StackConfiguration.getRepositoryServiceEndpoint()); synapse.setFileEndpoint(StackConfiguration.getFileServiceEndpoint()); return synapse; } /** * @throws Exception * */ @BeforeClass public static void beforeClass() throws Exception { bridge = createBridgeClient(StackConfiguration.getIntegrationTestUserOneName(), StackConfiguration.getIntegrationTestUserOnePassword()); bridgeTwo = createBridgeClient(StackConfiguration.getIntegrationTestUserTwoName(), StackConfiguration.getIntegrationTestUserTwoPassword()); } @Before public void before() throws SynapseException { // Delete all communities that bridge and bridgeTwo are members of for (Community community : bridge.getCommunities(1000, 0).getResults()) { deleteCommunity(community.getId()); } for (Community community : bridgeTwo.getCommunities(1000, 0).getResults()) { deleteCommunity(community.getId()); } } /** * @throws Exception * @throws HttpException * @throws IOException * @throws JSONException * @throws SynapseUserException * @throws SynapseServiceException */ @After public void after() throws Exception { for (String communityId : communitiesToDelete) { deleteCommunity(communityId); } } private void deleteCommunity(String communityId) { try { bridge.deleteCommunity(communityId); } catch (Exception e) { try { bridgeTwo.deleteCommunity(communityId); } catch (Exception e2) { System.err.println(e.getMessage()); System.err.println(e2.getMessage()); } } } @Test public void testGetVersion() throws Exception { BridgeVersionInfo versionInfo = bridge.getBridgeVersionInfo(); assertFalse(versionInfo.getVersion().isEmpty()); } /** * @throws Exception */ @Test public void testCommunityCRUD() throws Exception { String communityName = "my-first-community-" + System.currentTimeMillis(); Community communityToCreate = new Community(); communityToCreate.setName(communityName); Community newCommunity = bridge.createCommunity(communityToCreate); assertEquals(communityName, newCommunity.getName()); assertNotNull(newCommunity.getId()); assertNotNull(newCommunity.getTeamId()); assertNull(newCommunity.getDescription()); assertNotNull(newCommunity.getWelcomePageWikiId()); assertNotNull(newCommunity.getIndexPageWikiId()); WikiPageKey key = new WikiPageKey(newCommunity.getId(), ObjectType.ENTITY, newCommunity.getWelcomePageWikiId()); V2WikiPage v2WikiPage = createSynapse(bridge).getV2WikiPage(key); assertEquals("Welcome to " + communityName, v2WikiPage.getTitle()); key = new WikiPageKey(newCommunity.getId(), ObjectType.ENTITY, newCommunity.getIndexPageWikiId()); v2WikiPage = createSynapse(bridge).getV2WikiPage(key); assertEquals("Index of " + communityName, v2WikiPage.getTitle()); newCommunity.setDescription("some description"); newCommunity = bridge.updateCommunity(newCommunity); assertEquals("some description", newCommunity.getDescription()); Community community = bridge.getCommunity(newCommunity.getId()); assertEquals(newCommunity.getId(), community.getId()); assertEquals("some description", community.getDescription()); bridge.deleteCommunity(newCommunity.getId()); try { community = bridge.getCommunity(newCommunity.getId()); fail("Should not have found the entity"); } catch (SynapseNotFoundException e) { } } @Test public void testAddRemoveUsers() throws Exception { int beforeCount = (int) bridge.getAllCommunities(1000, 0).getTotalNumberOfResults(); Community community = createCommunity(); PaginatedResults<Community> allCommunities = bridge.getAllCommunities(1000, 0); assertEquals(beforeCount + 1, allCommunities.getTotalNumberOfResults()); assertEquals(1, bridge.getCommunities(1000, 0).getTotalNumberOfResults()); assertEquals(community, bridge.getCommunities(1000, 0).getResults().get(0)); assertEquals(0, bridgeTwo.getCommunities(1000, 0).getTotalNumberOfResults()); bridgeTwo.joinCommunity(community.getId()); assertEquals(1, bridge.getCommunities(1000, 0).getTotalNumberOfResults()); assertEquals(1, bridgeTwo.getCommunities(1000, 0).getTotalNumberOfResults()); assertEquals(community, bridgeTwo.getCommunities(1000, 0).getResults().get(0)); bridgeTwo.leaveCommunity(community.getId()); assertEquals(1, bridge.getCommunities(1000, 0).getTotalNumberOfResults()); assertEquals(0, bridgeTwo.getCommunities(1000, 0).getTotalNumberOfResults()); } @Test public void testAddRemoveAdmin() throws Exception { Community community = createCommunity(); bridgeTwo.joinCommunity(community.getId()); bridge.addCommunityAdmin(community.getId(), StackConfiguration.getIntegrationTestUserTwoName()); bridge.removeCommunityAdmin(community.getId(), StackConfiguration.getIntegrationTestUserTwoName()); bridgeTwo.leaveCommunity(community.getId()); } @Test public void testAddRemoveAdminIdempotentcy() throws Exception { Community community = createCommunity(); bridgeTwo.joinCommunity(community.getId()); bridge.addCommunityAdmin(community.getId(), StackConfiguration.getIntegrationTestUserTwoName()); bridge.addCommunityAdmin(community.getId(), StackConfiguration.getIntegrationTestUserTwoName()); bridge.removeCommunityAdmin(community.getId(), StackConfiguration.getIntegrationTestUserTwoName()); bridge.removeCommunityAdmin(community.getId(), StackConfiguration.getIntegrationTestUserTwoName()); bridgeTwo.leaveCommunity(community.getId()); } @Test public void testAddAdminAndLeave() throws Exception { Community community = createCommunity(); bridgeTwo.joinCommunity(community.getId()); bridge.addCommunityAdmin(community.getId(), StackConfiguration.getIntegrationTestUserTwoName()); bridgeTwo.leaveCommunity(community.getId()); } @Test public void testAddOtherAdminAndLeave() throws Exception { Community community = createCommunity(); bridgeTwo.joinCommunity(community.getId()); bridge.addCommunityAdmin(community.getId(), StackConfiguration.getIntegrationTestUserTwoName()); bridge.leaveCommunity(community.getId()); } @Test(expected = SynapseException.class) public void testLeaveLastAdminNotAllowed() throws Exception { Community community = createCommunity(); bridgeTwo.joinCommunity(community.getId()); bridge.leaveCommunity(community.getId()); } private Community createCommunity() throws SynapseException { String communityName = "my-first-community-" + System.currentTimeMillis() + "-" + communitiesToDelete.size(); Community communityToCreate = new Community(); communityToCreate.setName(communityName); Community newCommunity = bridge.createCommunity(communityToCreate); assertEquals(communityName, newCommunity.getName()); assertNotNull(newCommunity.getId()); assertNotNull(newCommunity.getTeamId()); assertNull(newCommunity.getDescription()); communitiesToDelete.add(newCommunity.getId()); return newCommunity; } }
package org.jbake.app; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import org.apache.commons.configuration.CompositeConfiguration; import org.jbake.model.DocumentTypes; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import static org.assertj.core.api.Assertions.*; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.Map; import java.util.Scanner; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class RendererTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); private File sourceFolder; private File destinationFolder; private File templateFolder; private CompositeConfiguration config; private ODatabaseDocumentTx db; @Before public void setup() throws Exception, IOException, URISyntaxException { URL sourceUrl = this.getClass().getResource("/"); sourceFolder = new File(sourceUrl.getFile()); if (!sourceFolder.exists()) { throw new Exception("Cannot find sample data structure!"); } destinationFolder = folder.getRoot(); templateFolder = new File(sourceFolder, "templates"); if (!templateFolder.exists()) { throw new Exception("Cannot find template folder!"); } config = ConfigUtil.load(new File(this.getClass().getResource("/").getFile())); Assert.assertEquals(".html", config.getString("output.extension")); db = DBUtil.createDB("memory", "documents"+System.currentTimeMillis()); } @After public void cleanup() throws InterruptedException { db.drop(); db.close(); } @Test public void render() throws Exception { Parser parser = new Parser(config, sourceFolder.getPath()); Renderer renderer = new Renderer(db, destinationFolder, templateFolder, config); File sampleFile = new File(sourceFolder.getPath() + File.separator + "content" + File.separator + "blog" + File.separator + "2013" + File.separator + "second-post.html"); Map<String, Object> content = parser.processFile(sampleFile); content.put("uri", "/second-post.html"); renderer.render(content); File outputFile = new File(destinationFolder, "second-post.html"); Assert.assertTrue(outputFile.exists()); Scanner scanner = new Scanner(outputFile); boolean foundTitle = false; boolean foundDate = false; boolean foundBody = false; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("<h2>Second Post</h2>")) { foundTitle = true; } if (line.trim().startsWith("<p class=\"post-date\">28") && line.endsWith("2013</p>")) { foundDate = true; } if (line.contains("Lorem ipsum dolor sit amet")) { foundBody = true; } if (foundTitle && foundDate && foundBody) { break; } } Assert.assertTrue(foundTitle); Assert.assertTrue(foundDate); Assert.assertTrue(foundBody); } @Test public void renderIndex() throws Exception { //setup Crawler crawler = new Crawler(db, sourceFolder, config); crawler.crawl(new File(sourceFolder.getPath() + File.separator + "content")); Renderer renderer = new Renderer(db, destinationFolder, templateFolder, config); //exec renderer.renderIndex("index.html"); //validate File outputFile = new File(destinationFolder, "index.html"); Assert.assertTrue(outputFile.exists()); Scanner scanner = new Scanner(outputFile); boolean foundFirstTitle = false; boolean foundSecondTitle = false; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("<h4><a href=\"/blog/2012/first-post.html\">First Post</a></h4>")) { foundFirstTitle = true; } if (line.contains("<h4><a href=\"/blog/2013/second-post.html\">Second Post</a></h4>")) { foundSecondTitle = true; } if (foundFirstTitle && foundSecondTitle) { break; } } Assert.assertTrue(foundFirstTitle); Assert.assertTrue(foundSecondTitle); } @Test public void renderFeed() throws Exception { Crawler crawler = new Crawler(db, sourceFolder, config); crawler.crawl(new File(sourceFolder.getPath() + File.separator + "content")); Renderer renderer = new Renderer(db, destinationFolder, templateFolder, config); renderer.renderFeed("feed.xml"); File outputFile = new File(destinationFolder, "feed.xml"); Assert.assertTrue(outputFile.exists()); Scanner scanner = new Scanner(outputFile); boolean foundDescription = false; boolean foundFirstTitle = false; boolean foundSecondTitle = false; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("<description>My corner of the Internet</description>")) { foundDescription = true; } if (line.contains("<title>Second Post</title>")) { foundFirstTitle = true; } if (line.contains("<title>First Post</title>")) { foundSecondTitle = true; } if (foundDescription && foundFirstTitle && foundSecondTitle) { break; } } Assert.assertTrue(foundDescription); Assert.assertTrue(foundFirstTitle); Assert.assertTrue(foundSecondTitle); } @Test public void renderArchive() throws Exception { Crawler crawler = new Crawler(db, sourceFolder, config); crawler.crawl(new File(sourceFolder.getPath() + File.separator + "content")); Renderer renderer = new Renderer(db, destinationFolder, templateFolder, config); renderer.renderArchive("archive.html"); File outputFile = new File(destinationFolder, "archive.html"); Assert.assertTrue(outputFile.exists()); // verify String output = FileUtils.readFileToString(outputFile); assertThat(output) .contains("<a href=\"/blog/2013/second-post.html\">Second Post</a></h4>") .contains("<a href=\"/blog/2012/first-post.html\">First Post</a></h4>"); } @Test public void renderTags() throws Exception { Crawler crawler = new Crawler(db, sourceFolder, config); crawler.crawl(new File(sourceFolder.getPath() + File.separator + "content")); Renderer renderer = new Renderer(db, destinationFolder, templateFolder, config); renderer.renderTags(crawler.getTags(), "tags"); // verify File outputFile = new File(destinationFolder + File.separator + "tags" + File.separator + "blog.html"); Assert.assertTrue(outputFile.exists()); String output = FileUtils.readFileToString(outputFile); assertThat(output) .contains("<a href=\"/blog/2013/second-post.html\">Second Post</a></h4>") .contains("<a href=\"/blog/2012/first-post.html\">First Post</a></h4>"); } @Test public void renderSitemap() throws Exception { DocumentTypes.addDocumentType("paper"); DBUtil.updateSchema(db); Crawler crawler = new Crawler(db, sourceFolder, config); crawler.crawl(new File(sourceFolder.getPath() + File.separator + "content")); Renderer renderer = new Renderer(db, destinationFolder, templateFolder, config); renderer.renderSitemap("sitemap.xml"); File outputFile = new File(destinationFolder, "sitemap.xml"); Assert.assertTrue(outputFile.exists()); // verify String output = FileUtils.readFileToString(outputFile); assertThat(output) .contains("/blog/2013/second-post.html") .contains("/blog/2012/first-post.html") .contains("/papers/published-paper.html") .doesNotContain("draft-paper.html"); } }
package arez.integration.util; import arez.SpyEventHandler; import java.util.ArrayList; import java.util.function.Consumer; import javax.annotation.Nonnull; import static org.testng.Assert.*; @SuppressWarnings( { "UnusedReturnValue", "WeakerAccess" } ) public final class TestSpyEventHandler implements SpyEventHandler { private final ArrayList<Object> _events = new ArrayList<>(); /** * When ussing assertNextEvent this tracks the index that we are up to. */ private int _currentAssertIndex; @Override public void onSpyEvent( @Nonnull final Object event ) { _events.add( event ); } /** * Assert Event at index is of specific type and return it. */ @Nonnull public <T> T assertEvent( @Nonnull final Class<T> type, final int index ) { assertTrue( eventCount() > index ); final Object event = _events.get( index ); assertTrue( type.isInstance( event ), "Expected event at index " + index + " to be of type " + type + " but is " + " of type " + event.getClass() + " with value " + event ); return type.cast( event ); } public void assertEventCount( final int count ) { assertEquals( eventCount(), count, "Actual events: " + _events ); } public void assertEventCountAtLeast( final int count ) { assertTrue( eventCount() >= count, "Expected more than " + count + ". Actual events: " + _events ); } /** * Assert "next" Event is of specific type. * Increment the next counter. */ @Nonnull public <T> T assertNextEvent( @Nonnull final Class<T> type ) { final T event = assertEvent( type, _currentAssertIndex ); _currentAssertIndex++; return event; } /** * Assert "next" Event is of specific type. * Increment the next counter, run action. */ @Nonnull public <T> T assertNextEvent( @Nonnull final Class<T> type, @Nonnull final Consumer<T> action ) { final T event = assertNextEvent( type ); action.accept( event ); return event; } public int eventCount() { return _events.size(); } }
package sample; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Test; public class StaticResourcesTest extends JerseyTest { /** * hello.txt * * @throws Exception */ @Test public void testGetHelloText() throws Exception { Response response = target("static/hello.txt").request().get(); assertThat("Status code", response.getStatusInfo(), is(Status.OK)); assertThat("Conetnt-Type", response.getMediaType(), is(MediaType.TEXT_PLAIN_TYPE)); assertThat("Entity body", response.readEntity(String.class), is("Hello, world!")); } /** * JavaScript * * @throws Exception */ @Test public void testGetFibJs() throws Exception { Response response = target("static/fib.js").request().get(); assertThat("Status code", response.getStatusInfo(), is(Status.OK)); assertThat("Conetnt-Type", response.getMediaType(), is(MediaType.valueOf("text/javascript"))); ScriptEngine engine = new ScriptEngineManager() .getEngineByMimeType("text/javascript"); engine.eval(response.readEntity(String.class)); assertThat("fib(0)", engine.eval("fib(0)"), is(0)); assertThat("fib(1)", engine.eval("fib(1)"), is(1)); assertThat("fib(2)", engine.eval("fib(2)"), is(1.0)); assertThat("fib(3)", engine.eval("fib(3)"), is(2.0)); assertThat("fib(4)", engine.eval("fib(4)"), is(3.0)); assertThat("fib(5)", engine.eval("fib(5)"), is(5.0)); assertThat("fib(6)", engine.eval("fib(6)"), is(8.0)); assertThat("fib(7)", engine.eval("fib(7)"), is(13.0)); assertThat("fib(8)", engine.eval("fib(8)"), is(21.0)); assertThat("fib(9)", engine.eval("fib(9)"), is(34.0)); } /** * 404 * * @throws Exception */ @Test public void testResetCssNotFound() throws Exception { Response response = target("static/reset.css").request().get(); assertThat("Status code", response.getStatusInfo(), is(Status.NOT_FOUND)); } @Override protected Application configure() { return new ResourceConfig(StaticResources.class); } }
package org.flymine.objectstore.webservice; import java.lang.reflect.Constructor; import java.net.URL; import java.net.MalformedURLException; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.rmi.RemoteException; import org.flymine.objectstore.webservice.ser.SerializationUtil; import org.flymine.objectstore.ObjectStoreAbstractImpl; import org.flymine.objectstore.ObjectStoreException; import org.flymine.objectstore.query.Query; import org.flymine.objectstore.query.ResultsRow; import org.flymine.objectstore.query.ResultsInfo; import org.flymine.objectstore.query.fql.FqlQuery; import org.flymine.metadata.Model; import org.flymine.metadata.ClassDescriptor; import org.apache.axis.AxisFault; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.encoding.TypeMapping; import javax.xml.namespace.QName; /** * ObjectStore implementation that accesses a remote ObjectStore via JAX-RPC. * * @author Andrew Varley * @author Mark Woodbridge */ public class ObjectStoreClient extends ObjectStoreAbstractImpl { protected static Map instances = new HashMap(); protected Call call; protected Map queryIds = new IdentityHashMap(); /** * Construct an ObjectStoreClient pointing at an ObjectStore service on a remote URL * * @param url the URL of the remote ObjectStore * @param model the model used by this ObjectStore * @throws ObjectStoreException if any error with the remote service */ protected ObjectStoreClient(URL url, Model model) throws ObjectStoreException { super(model); if (url == null) { throw new NullPointerException("url must not be null"); } // Set up the service and call objects so that the session can be maintained try { Service service = new Service(); call = (Call) service.createCall(); call.setMaintainSession(true); call.setTargetEndpointAddress(url); TypeMapping tm = call.getTypeMapping(); SerializationUtil.registerMappings(tm); Iterator iter = model.getClassDescriptors().iterator(); while (iter.hasNext()) { Class cls = Class.forName(((ClassDescriptor) iter.next()).getName()); SerializationUtil.registerDefaultMapping(tm, cls); } } catch (Exception e) { throw new ObjectStoreException("Calling remote service failed", e); } } /** * Gets a ObjectStoreClient instance for the given properties * * @param props The properties used to configure an ObjectStoreClient * @param model the metadata associated with this objectstore * @return the ObjectStoreClient for the given properties * @throws ObjectStoreException if there is any problem with the underlying ObjectStore */ public static ObjectStoreClient getInstance(Properties props, Model model) throws ObjectStoreException { String urlString = props.getProperty("url"); if (urlString == null) { throw new ObjectStoreException("No 'url' property specified for" + " ObjectStoreClient (check properties file)"); } URL url = null; try { url = new URL(urlString); } catch (MalformedURLException e) { throw new ObjectStoreException("URL (" + urlString + ") is invalid", e); } synchronized (instances) { if (!(instances.containsKey(urlString))) { instances.put(urlString, new ObjectStoreClient(url, model)); } } return (ObjectStoreClient) instances.get(urlString); } /** * Execute a method on the remote ObjectStore web service * * @param methodName the name of the remote method * @param params the parameters to pass to that method * @return the resulting Object from the remote method * @throws ObjectStoreException if any error occurs */ protected Object remoteMethod(String methodName, Object [] params) throws ObjectStoreException { call.setOperationName(new QName("", methodName)); try { return call.invoke(params); } catch (AxisFault af) { //AxisFault extends RemoteException, but carries no cause af.printStackTrace(); Exception real = null; try { String[] split = af.toString().split(":"); //<exceptionClassName>:<errorString> if (split.length == 1) { // probably a server error string throw new ObjectStoreException(af); } Class c = Class.forName(split[0]); Constructor cons = c.getConstructor(new Class[] {String.class}); real = (Exception) cons.newInstance(new Object[] {split[1]}); } catch (Exception e) { throw new ObjectStoreException(e); } if (real instanceof ObjectStoreException) { throw (ObjectStoreException) real; } else if (real instanceof RuntimeException) { throw (RuntimeException) real; } else { throw new ObjectStoreException(real); } } catch (RemoteException re) { throw new ObjectStoreException(re); } } /** * @see ObjectStore#execute */ public List execute(Query q, int start, int limit, boolean optimise) throws ObjectStoreException { ResultsInfo estimate = estimate(q); if (estimate.getComplete() > maxTime) { throw new ObjectStoreException("Estimated time to run query (" + estimate.getComplete() + ") greater than permitted maximum (" + maxTime + ")"); } List results = (List) remoteMethod("execute", new Object [] {getQueryId(q), new Integer(start), new Integer(limit)}); for (int i = 0; i < results.size(); i++) { ResultsRow row = new ResultsRow((List) results.get(i)); for (Iterator colIter = row.iterator(); colIter.hasNext();) { promoteProxies(colIter.next()); } results.set(i, row); } return results; } /** * @see ObjectStore#estimate */ public ResultsInfo estimate(Query q) throws ObjectStoreException { return (ResultsInfo) remoteMethod("estimate", new Object [] {getQueryId(q)}); } /** * @see ObjectStore#count */ public int count(Query q) throws ObjectStoreException { return ((Integer) remoteMethod("count", new Object [] {getQueryId(q)})).intValue(); } /** * @see ObjectStore#getObjectByExample */ public Object getObjectByExample(Object obj) throws ObjectStoreException { Object object = remoteMethod("getObjectByExample", new Object[] {obj}); promoteProxies(object); return object; } /** * Get the id for the query if it has already been registered. If not, register it. * * @param q the Query to get the id for * @return the id of the query * @throws ObjectStoreException if an error occurs */ protected Integer getQueryId(Query q) throws ObjectStoreException { if (!queryIds.containsKey(q)) { queryIds.put(q, (Integer) remoteMethod("registerQuery", new Object[] {new FqlQuery(q)})); } return (Integer) queryIds.get(q); } }
package com.intellij.xml.util; import com.intellij.codeInspection.InspectionProfile; import com.intellij.codeInspection.htmlInspections.XmlEntitiesInspection; import com.intellij.ide.highlighter.HtmlFileType; import com.intellij.ide.highlighter.XHtmlFileType; import com.intellij.javaee.ExternalResourceManagerEx; import com.intellij.lang.Language; import com.intellij.lang.html.HTMLLanguage; import com.intellij.lang.xhtml.XHTMLLanguage; import com.intellij.lang.xml.XMLLanguage; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.registry.RegistryValue; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.XmlRecursiveElementWalkingVisitor; import com.intellij.psi.html.HtmlTag; import com.intellij.psi.impl.source.html.HtmlDocumentImpl; import com.intellij.psi.impl.source.parsing.xml.HtmlBuilderDriver; import com.intellij.psi.impl.source.parsing.xml.XmlBuilder; import com.intellij.psi.impl.source.tree.CompositeElement; import com.intellij.psi.impl.source.xml.XmlTagImpl; import com.intellij.psi.templateLanguages.OuterLanguageElement; import com.intellij.psi.templateLanguages.TemplateLanguageFileViewProvider; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.*; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.xml.*; import com.intellij.xml.impl.schema.XmlAttributeDescriptorImpl; import com.intellij.xml.impl.schema.XmlElementDescriptorImpl; import com.intellij.xml.util.documentation.MimeTypeDictionary; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jetbrains.annotations.*; import java.nio.charset.Charset; import java.util.*; /** * @author Maxim.Mossienko */ public class HtmlUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.xml.util.HtmlUtil"); @NonNls private static final String JSFC = "jsfc"; @NonNls private static final String CHARSET = "charset"; @NonNls private static final String CHARSET_PREFIX = CHARSET+"="; @NonNls public static final String HTML5_DATA_ATTR_PREFIX = "data-"; public static final String SCRIPT_TAG_NAME = "script"; public static final String STYLE_TAG_NAME = "style"; public static final String STYLE_ATTRIBUTE_NAME = STYLE_TAG_NAME; public static final String ID_ATTRIBUTE_NAME = "id"; public static final String CLASS_ATTRIBUTE_NAME = "class"; public static final String[] CONTENT_TYPES = ArrayUtil.toStringArray(MimeTypeDictionary.getContentTypes()); @NonNls public static final String MATH_ML_NAMESPACE = "http: @NonNls public static final String SVG_NAMESPACE = "http: public static final String[] RFC2616_HEADERS = new String[]{"Accept", "Accept-Charset", "Accept-Encoding", "Accept-Language", "Accept-Ranges", "Age", "Allow", "Authorization", "Cache-Control", "Connection", "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type", "Date", "ETag", "Expect", "Expires", "From", "Host", "If-Match", "If-Modified-Since", "If-None-Match", "If-Range", "If-Unmodified-Since", "Last-Modified", "Location", "Max-Forwards", "Pragma", "Proxy-Authenticate", "Proxy-Authorization", "Range", "Referer", "Refresh", "Retry-After", "Server", "TE", "Trailer", "Transfer-Encoding", "Upgrade", "User-Agent", "Vary", "Via", "Warning", "WWW-Authenticate"}; private HtmlUtil() { } private static final Set<String> EMPTY_TAGS_MAP = new THashSet<>(); @NonNls private static final String[] OPTIONAL_END_TAGS = { //"html", "head", //"body", "p", "li", "dd", "dt", "thead", "tfoot", "tbody", "colgroup", "tr", "th", "td", "option", "embed", "noembed" }; private static final Set<String> OPTIONAL_END_TAGS_MAP = new THashSet<>(); @NonNls private static final String[] BLOCK_TAGS = {"p", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "dir", "menu", "pre", "dl", "div", "center", "noscript", "noframes", "blockquote", "form", "isindex", "hr", "table", "fieldset", "address", // nonexplicitly specified "map", // flow elements "body", "object", "applet", "ins", "del", "dd", "li", "button", "th", "td", "iframe", "comment" }; // flow elements are block or inline, so they should not close <p> for example @NonNls private static final String[] POSSIBLY_INLINE_TAGS = {"a", "abbr", "acronym", "applet", "b", "basefont", "bdo", "big", "br", "button", "cite", "code", "del", "dfn", "em", "font", "i", "iframe", "img", "input", "ins", "kbd", "label", "map", "object", "q", "s", "samp", "select", "small", "span", "strike", "strong", "sub", "sup", "textarea", "tt", "u", "var"}; private static final Set<String> BLOCK_TAGS_MAP = new THashSet<>(); @NonNls private static final String[] INLINE_ELEMENTS_CONTAINER = {"p", "h1", "h2", "h3", "h4", "h5", "h6", "pre"}; private static final Set<String> INLINE_ELEMENTS_CONTAINER_MAP = new THashSet<>(); private static final Set<String> POSSIBLY_INLINE_TAGS_MAP = new THashSet<>(); @NonNls private static final String[] HTML5_TAGS = { "article", "aside", "audio", "canvas", "command", "datalist", "details", "embed", "figcaption", "figure", "footer", "header", "keygen", "mark", "meter", "nav", "output", "progress", "rp", "rt", "ruby", "section", "source", "summary", "time", "video", "wbr", "main" }; private static final Set<String> HTML5_TAGS_SET = new THashSet<>(); private static final Map<String, Set<String>> AUTO_CLOSE_BY_MAP = new THashMap<>(); static { for (HTMLControls.Control control : HTMLControls.getControls()) { final String tagName = StringUtil.toLowerCase(control.name); if (control.endTag == HTMLControls.TagState.FORBIDDEN) EMPTY_TAGS_MAP.add(tagName); AUTO_CLOSE_BY_MAP.put(tagName, new THashSet<>(control.autoClosedBy)); } ContainerUtil.addAll(OPTIONAL_END_TAGS_MAP, OPTIONAL_END_TAGS); ContainerUtil.addAll(BLOCK_TAGS_MAP, BLOCK_TAGS); ContainerUtil.addAll(INLINE_ELEMENTS_CONTAINER_MAP, INLINE_ELEMENTS_CONTAINER); ContainerUtil.addAll(POSSIBLY_INLINE_TAGS_MAP, POSSIBLY_INLINE_TAGS); ContainerUtil.addAll(HTML5_TAGS_SET, HTML5_TAGS); } public static boolean isSingleHtmlTag(@NotNull XmlTag tag, boolean lowerCase) { final XmlExtension extension = XmlExtension.getExtensionByElement(tag); final String name = tag.getName(); boolean result = EMPTY_TAGS_MAP.contains(!lowerCase || (tag instanceof XmlTagImpl && ((XmlTagImpl)tag).isCaseSensitive()) ? name : StringUtil.toLowerCase(name)); return result && (extension == null || !extension.isSingleTagException(tag)); } public static boolean isSingleHtmlTag(String tagName) { return EMPTY_TAGS_MAP.contains(StringUtil.toLowerCase(tagName)); } public static boolean isSingleHtmlTagL(String tagName) { return EMPTY_TAGS_MAP.contains(tagName); } public static boolean isOptionalEndForHtmlTag(String tagName) { return OPTIONAL_END_TAGS_MAP.contains(StringUtil.toLowerCase(tagName)); } public static boolean isOptionalEndForHtmlTagL(String tagName) { return OPTIONAL_END_TAGS_MAP.contains(tagName); } public static boolean canTerminate(final String childTagName, final String tagName) { final Set<String> closingTags = AUTO_CLOSE_BY_MAP.get(tagName); return closingTags != null && closingTags.contains(childTagName); } public static boolean isHtmlBlockTag(String tagName) { return BLOCK_TAGS_MAP.contains(StringUtil.toLowerCase(tagName)); } public static boolean isPossiblyInlineTag(String tagName) { return POSSIBLY_INLINE_TAGS_MAP.contains(tagName); } public static boolean isHtmlBlockTagL(String tagName) { return BLOCK_TAGS_MAP.contains(tagName); } public static boolean isInlineTagContainer(String tagName) { return INLINE_ELEMENTS_CONTAINER_MAP.contains(StringUtil.toLowerCase(tagName)); } public static boolean isInlineTagContainerL(String tagName) { return INLINE_ELEMENTS_CONTAINER_MAP.contains(tagName); } public static void addHtmlSpecificCompletions(final XmlElementDescriptor descriptor, final XmlTag element, final List<? super XmlElementDescriptor> variants) { // add html block completions for tags with optional ends! String name = descriptor.getName(element); if (name != null && isOptionalEndForHtmlTag(name)) { PsiElement parent = element.getParent(); if (parent instanceof XmlTag && XmlChildRole.CLOSING_TAG_START_FINDER.findChild(parent.getNode()) != null) { return; } if (parent != null) { // we need grand parent since completion already uses parent's descriptor parent = parent.getParent(); } if (parent instanceof HtmlTag) { final XmlElementDescriptor parentDescriptor = ((HtmlTag)parent).getDescriptor(); if (parentDescriptor != descriptor && parentDescriptor != null) { for (final XmlElementDescriptor elementsDescriptor : parentDescriptor.getElementsDescriptors((XmlTag)parent)) { if (isHtmlBlockTag(elementsDescriptor.getName())) { variants.add(elementsDescriptor); } } } } else if (parent instanceof HtmlDocumentImpl) { final XmlNSDescriptor nsDescriptor = descriptor.getNSDescriptor(); for (XmlElementDescriptor elementDescriptor : nsDescriptor.getRootElementsDescriptors((XmlDocument)parent)) { if (isHtmlBlockTag(elementDescriptor.getName()) && !variants.contains(elementDescriptor)) { variants.add(elementDescriptor); } } } } } @Nullable public static XmlDocument getRealXmlDocument(@Nullable XmlDocument doc) { return HtmlPsiUtil.getRealXmlDocument(doc); } public static boolean isShortNotationOfBooleanAttributePreferred() { return Registry.is("html.prefer.short.notation.of.boolean.attributes", true); } @TestOnly public static void setShortNotationOfBooleanAttributeIsPreferred(boolean value, Disposable parent) { final boolean oldValue = isShortNotationOfBooleanAttributePreferred(); final RegistryValue registryValue = Registry.get("html.prefer.short.notation.of.boolean.attributes"); registryValue.setValue(value); Disposer.register(parent, new Disposable() { @Override public void dispose() { registryValue.setValue(oldValue); } }); } public static boolean isBooleanAttribute(@NotNull XmlAttributeDescriptor descriptor, @Nullable PsiElement context) { if (descriptor.isEnumerated()) { final String[] values = descriptor.getEnumeratedValues(); if (values == null) { return false; } if (values.length == 2) { return values[0].isEmpty() && values[1].equals(descriptor.getName()) || values[1].isEmpty() && values[0].equals(descriptor.getName()); } else if (values.length == 1) { return descriptor.getName().equals(values[0]); } } return context != null && isCustomBooleanAttribute(descriptor.getName(), context); } public static boolean isCustomBooleanAttribute(@NotNull String attributeName, @NotNull PsiElement context) { final String entitiesString = getEntitiesString(context, XmlEntitiesInspection.BOOLEAN_ATTRIBUTE_SHORT_NAME); if (entitiesString != null) { StringTokenizer tokenizer = new StringTokenizer(entitiesString, ","); while (tokenizer.hasMoreElements()) { if (tokenizer.nextToken().equalsIgnoreCase(attributeName)) { return true; } } } return false; } public static XmlAttributeDescriptor[] getCustomAttributeDescriptors(XmlElement context) { String entitiesString = getEntitiesString(context, XmlEntitiesInspection.ATTRIBUTE_SHORT_NAME); if (entitiesString == null) return XmlAttributeDescriptor.EMPTY; StringTokenizer tokenizer = new StringTokenizer(entitiesString, ","); XmlAttributeDescriptor[] descriptors = new XmlAttributeDescriptor[tokenizer.countTokens()]; int index = 0; while (tokenizer.hasMoreElements()) { final String customName = tokenizer.nextToken(); if (customName.length() == 0) continue; descriptors[index++] = new XmlAttributeDescriptorImpl() { @Override public String getName(PsiElement context) { return customName; } @Override public String getName() { return customName; } }; } return descriptors; } public static XmlElementDescriptor[] getCustomTagDescriptors(@Nullable PsiElement context) { String entitiesString = getEntitiesString(context, XmlEntitiesInspection.TAG_SHORT_NAME); if (entitiesString == null) return XmlElementDescriptor.EMPTY_ARRAY; StringTokenizer tokenizer = new StringTokenizer(entitiesString, ","); XmlElementDescriptor[] descriptors = new XmlElementDescriptor[tokenizer.countTokens()]; int index = 0; while (tokenizer.hasMoreElements()) { final String tagName = tokenizer.nextToken(); if (tagName.length() == 0) continue; descriptors[index++] = new CustomXmlTagDescriptor(tagName); } return descriptors; } @Nullable public static String getEntitiesString(@Nullable PsiElement context, @NotNull String inspectionName) { if (context == null) return null; PsiFile containingFile = context.getContainingFile().getOriginalFile(); final InspectionProfile profile = InspectionProjectProfileManager.getInstance(context.getProject()).getCurrentProfile(); XmlEntitiesInspection inspection = (XmlEntitiesInspection)profile.getUnwrappedTool(inspectionName, containingFile); if (inspection != null) { return inspection.getAdditionalEntries(); } return null; } public static XmlAttributeDescriptor[] appendHtmlSpecificAttributeCompletions(final XmlTag declarationTag, XmlAttributeDescriptor[] descriptors, final XmlAttribute context) { if (declarationTag instanceof HtmlTag) { descriptors = ArrayUtil.mergeArrays( descriptors, getCustomAttributeDescriptors(context) ); return descriptors; } boolean isJsfHtmlNamespace = false; for (String jsfHtmlUri : XmlUtil.JSF_HTML_URIS) { if (declarationTag.getPrefixByNamespace(jsfHtmlUri) != null) { isJsfHtmlNamespace = true; break; } } if (isJsfHtmlNamespace && declarationTag.getNSDescriptor(XmlUtil.XHTML_URI, true) != null && !XmlUtil.JSP_URI.equals(declarationTag.getNamespace())) { descriptors = ArrayUtil.append( descriptors, new XmlAttributeDescriptorImpl() { @Override public String getName(PsiElement context) { return JSFC; } @Override public String getName() { return JSFC; } }, XmlAttributeDescriptor.class ); } return descriptors; } public static boolean isHtml5Document(XmlDocument doc) { if (doc == null) { return false; } XmlProlog prolog = doc.getProlog(); XmlDoctype doctype = prolog != null ? prolog.getDoctype() : null; if (!isHtmlTagContainingFile(doc)) { return false; } final PsiFile htmlFile = doc.getContainingFile(); final String htmlFileFullName; if (htmlFile != null) { final VirtualFile vFile = htmlFile.getVirtualFile(); if (vFile != null) { htmlFileFullName = vFile.getPath(); } else { htmlFileFullName = htmlFile.getName(); } } else { htmlFileFullName = "unknown"; } if (doctype == null) { LOG.debug("DOCTYPE for " + htmlFileFullName + " is null"); return Html5SchemaProvider.getHtml5SchemaLocation() .equals(ExternalResourceManagerEx.getInstanceEx().getDefaultHtmlDoctype(doc.getProject())); } final boolean html5Doctype = isHtml5Doctype(doctype); final String doctypeDescription = "text: " + doctype.getText() + ", dtdUri: " + doctype.getDtdUri() + ", publicId: " + doctype.getPublicId() + ", markupDecl: " + doctype.getMarkupDecl(); LOG.debug("DOCTYPE for " + htmlFileFullName + "; " + doctypeDescription + "; HTML5: " + html5Doctype); return html5Doctype; } public static boolean isHtml5Doctype(XmlDoctype doctype) { return doctype.getDtdUri() == null && doctype.getPublicId() == null && doctype.getMarkupDecl() == null; } public static boolean isHtml5Context(XmlElement context) { XmlDocument doc = PsiTreeUtil.getParentOfType(context, XmlDocument.class); if (doc == null && context != null) { return Html5SchemaProvider.getHtml5SchemaLocation() .equals(ExternalResourceManagerEx.getInstanceEx().getDefaultHtmlDoctype(context.getProject())); } return isHtml5Document(doc); } public static boolean isHtmlTag(@NotNull XmlTag tag) { if (!tag.getLanguage().isKindOf(HTMLLanguage.INSTANCE)) return false; XmlDocument doc = PsiTreeUtil.getParentOfType(tag, XmlDocument.class); String doctype = null; if (doc != null) { doctype = XmlUtil.getDtdUri(doc); } doctype = doctype == null ? ExternalResourceManagerEx.getInstanceEx().getDefaultHtmlDoctype(tag.getProject()) : doctype; return XmlUtil.XHTML4_SCHEMA_LOCATION.equals(doctype) || !StringUtil.containsIgnoreCase(doctype, "xhtml"); } public static boolean hasNonHtml5Doctype(XmlElement context) { XmlDocument doc = PsiTreeUtil.getParentOfType(context, XmlDocument.class); if (doc == null) { return false; } XmlProlog prolog = doc.getProlog(); XmlDoctype doctype = prolog != null ? prolog.getDoctype() : null; return doctype != null && !isHtml5Doctype(doctype); } public static boolean isHtml5Tag(String tagName) { return HTML5_TAGS_SET.contains(tagName); } public static boolean isCustomHtml5Attribute(String attributeName) { return attributeName.startsWith(HTML5_DATA_ATTR_PREFIX); } @Nullable public static String getHrefBase(XmlFile file) { final XmlTag root = file.getRootTag(); final XmlTag head = root != null ? root.findFirstSubTag("head") : null; final XmlTag base = head != null ? head.findFirstSubTag("base") : null; return base != null ? base.getAttributeValue("href") : null; } public static boolean isOwnHtmlAttribute(XmlAttributeDescriptor descriptor) { // common html attributes are defined mostly in common.rnc, core-scripting.rnc, etc // while own tag attributes are defined in meta.rnc final PsiElement declaration = descriptor.getDeclaration(); final PsiFile file = declaration != null ? declaration.getContainingFile() : null; final String name = file != null ? file.getName() : null; return "meta.rnc".equals(name); } public static boolean tagHasHtml5Schema(@NotNull XmlTag context) { XmlElementDescriptor descriptor = context.getDescriptor(); if (descriptor != null) { XmlNSDescriptor nsDescriptor = descriptor.getNSDescriptor(); XmlFile descriptorFile = nsDescriptor != null ? nsDescriptor.getDescriptorFile() : null; String descriptorPath = descriptorFile != null ? descriptorFile.getVirtualFile().getPath() : null; return Comparing.equal(Html5SchemaProvider.getHtml5SchemaLocation(), descriptorPath) || Comparing.equal(Html5SchemaProvider.getXhtml5SchemaLocation(), descriptorPath); } return false; } private static class TerminateException extends RuntimeException { private static final TerminateException INSTANCE = new TerminateException(); } public static Charset detectCharsetFromMetaTag(@NotNull CharSequence content) { // check for <meta http-equiv="charset=CharsetName" > or <meta charset="CharsetName"> and return Charset // because we will lightly parse and explicit charset isn't used very often do quick check for applicability int charPrefix = StringUtil.indexOf(content, CHARSET); do { if (charPrefix == -1) return null; int charsetPrefixEnd = charPrefix + CHARSET.length(); while (charsetPrefixEnd < content.length() && Character.isWhitespace(content.charAt(charsetPrefixEnd))) ++charsetPrefixEnd; if (charsetPrefixEnd < content.length() && content.charAt(charsetPrefixEnd) == '=') break; charPrefix = StringUtil.indexOf(content,CHARSET, charsetPrefixEnd); } while(true); final Ref<String> charsetNameRef = new Ref<>(); try { new HtmlBuilderDriver(content).build(new XmlBuilder() { @NonNls final Set<String> inTag = new THashSet<>(); boolean metHttpEquiv = false; boolean metHttml5Charset = false; @Override public void doctype(@Nullable final CharSequence publicId, @Nullable final CharSequence systemId, final int startOffset, final int endOffset) { } @Override public ProcessingOrder startTag(final CharSequence localName, final String namespace, final int startoffset, final int endoffset, final int headerEndOffset) { @NonNls String name = StringUtil.toLowerCase(localName.toString()); inTag.add(name); if (!inTag.contains("head") && !"html".equals(name)) terminate(); return ProcessingOrder.TAGS_AND_ATTRIBUTES; } private void terminate() { throw TerminateException.INSTANCE; } @Override public void endTag(final CharSequence localName, final String namespace, final int startoffset, final int endoffset) { @NonNls final String name = StringUtil.toLowerCase(localName.toString()); if ("meta".equals(name) && (metHttpEquiv || metHttml5Charset) && contentAttributeValue != null) { String charsetName; if (metHttpEquiv) { int start = contentAttributeValue.indexOf(CHARSET_PREFIX); if (start == -1) return; start += CHARSET_PREFIX.length(); int end = contentAttributeValue.indexOf(';', start); if (end == -1) end = contentAttributeValue.length(); charsetName = contentAttributeValue.substring(start, end); } else /*if (metHttml5Charset) */ { charsetName = StringUtil.stripQuotesAroundValue(contentAttributeValue); } charsetNameRef.set(charsetName); terminate(); } if ("head".equals(name)) { terminate(); } inTag.remove(name); metHttpEquiv = false; metHttml5Charset = false; contentAttributeValue = null; } private String contentAttributeValue; @Override public void attribute(final CharSequence localName, final CharSequence v, final int startoffset, final int endoffset) { @NonNls final String name = StringUtil.toLowerCase(localName.toString()); if (inTag.contains("meta")) { @NonNls String value = StringUtil.toLowerCase(v.toString()); if (name.equals("http-equiv")) { metHttpEquiv |= value.equals("content-type"); } else if (name.equals(CHARSET)) { metHttml5Charset = true; contentAttributeValue = value; } if (name.equals("content")) { contentAttributeValue = value; } } } @Override public void textElement(final CharSequence display, final CharSequence physical, final int startoffset, final int endoffset) { } @Override public void entityRef(final CharSequence ref, final int startOffset, final int endOffset) { } @Override public void error(@NotNull String message, int startOffset, int endOffset) { } }); } catch (TerminateException ignored) { //ignore } catch (Exception ignored) { // some weird things can happen, like unbalanaced tree } String name = charsetNameRef.get(); return CharsetToolkit.forName(name); } public static boolean isTagWithoutAttributes(@NonNls String tagName) { return tagName != null && "br".equalsIgnoreCase(tagName); } public static boolean hasHtml(@NotNull PsiFile file) { return isHtmlFile(file) || file.getViewProvider() instanceof TemplateLanguageFileViewProvider; } public static boolean supportsXmlTypedHandlers(@NotNull PsiFile file) { Language language = file.getLanguage(); while (language != null) { if ("JavaScript".equals(language.getID())) return true; if ("Dart".equals(language.getID())) return true; language = language.getBaseLanguage(); } return false; } public static boolean hasHtmlPrefix(@NotNull String url) { return url.startsWith("http: url.startsWith("https: url.startsWith("//") || //Protocol-relative URL url.startsWith("ftp: } public static boolean isHtmlFile(@NotNull PsiElement element) { Language language = element.getLanguage(); return language.isKindOf(HTMLLanguage.INSTANCE) || language == XHTMLLanguage.INSTANCE; } public static boolean isHtmlFile(@NotNull VirtualFile file) { FileType fileType = file.getFileType(); return fileType == HtmlFileType.INSTANCE || fileType == XHtmlFileType.INSTANCE; } public static boolean isHtmlTagContainingFile(PsiElement element) { if (element == null) { return false; } final PsiFile containingFile = element.getContainingFile(); if (containingFile != null) { final XmlTag tag = PsiTreeUtil.getParentOfType(element, XmlTag.class, false); if (tag instanceof HtmlTag) { return true; } final XmlDocument document = PsiTreeUtil.getParentOfType(element, XmlDocument.class, false); if (document instanceof HtmlDocumentImpl) { return true; } final FileViewProvider provider = containingFile.getViewProvider(); Language language; if (provider instanceof TemplateLanguageFileViewProvider) { language = ((TemplateLanguageFileViewProvider)provider).getTemplateDataLanguage(); } else { language = provider.getBaseLanguage(); } return language == XHTMLLanguage.INSTANCE; } return false; } public static boolean isScriptTag(@Nullable XmlTag tag) { return tag != null && tag.getLocalName().equalsIgnoreCase(SCRIPT_TAG_NAME); } public static class CustomXmlTagDescriptor extends XmlElementDescriptorImpl { private final String myTagName; public CustomXmlTagDescriptor(String tagName) { super(null); myTagName = tagName; } @Override public String getName(PsiElement context) { return myTagName; } @Override public String getDefaultName() { return myTagName; } @Override public boolean allowElementsFromNamespace(final String namespace, final XmlTag context) { return true; } } @Nullable public static Iterable<String> splitClassNames(@Nullable String classAttributeValue) { // comma is useduse as separator because class name cannot contain comma but it can be part of JSF classes attributes return classAttributeValue != null ? StringUtil.tokenize(classAttributeValue, " \t,") : Collections.emptyList(); } @Contract("!null -> !null") public static String getTagPresentation(final @Nullable XmlTag tag) { if (tag == null) return null; StringBuilder builder = new StringBuilder(tag.getLocalName()); String idValue = getAttributeValue(tag, ID_ATTRIBUTE_NAME); if (idValue != null) { builder.append('#').append(idValue); } String classValue = getAttributeValue(tag, CLASS_ATTRIBUTE_NAME); if (classValue != null) { for (String className : splitClassNames(classValue)) { builder.append('.').append(className); } } return builder.toString(); } @Nullable private static String getAttributeValue(@NotNull XmlTag tag, @NotNull String attrName) { XmlAttribute classAttribute = getAttributeByName(tag, attrName); if (classAttribute != null && !containsOuterLanguageElements(classAttribute)) { String value = classAttribute.getValue(); if (!StringUtil.isEmptyOrSpaces(value)) return value; } return null; } @Nullable private static XmlAttribute getAttributeByName(@NotNull XmlTag tag, @NotNull String name) { PsiElement child = tag.getFirstChild(); while (child != null) { if (child instanceof XmlAttribute) { PsiElement nameElement = child.getFirstChild(); if (nameElement != null && nameElement.getNode().getElementType() == XmlTokenType.XML_NAME && name.equalsIgnoreCase(nameElement.getText())) { return (XmlAttribute)child; } } child = child.getNextSibling(); } return null; } private static boolean containsOuterLanguageElements(@NotNull PsiElement element) { PsiElement child = element.getFirstChild(); while (child != null) { if (child instanceof CompositeElement) { return containsOuterLanguageElements(child); } else if (child instanceof OuterLanguageElement) { return true; } child = child.getNextSibling(); } return false; } public static List<XmlAttributeValue> getIncludedPathsElements(@NotNull final XmlFile file) { final List<XmlAttributeValue> result = new ArrayList<>(); file.acceptChildren(new XmlRecursiveElementWalkingVisitor() { @Override public void visitXmlTag(XmlTag tag) { XmlAttribute attribute = null; if ("link".equalsIgnoreCase(tag.getName())) { attribute = tag.getAttribute("href"); } else if ("script".equalsIgnoreCase(tag.getName()) || "img".equalsIgnoreCase(tag.getName())) { attribute = tag.getAttribute("src"); } if (attribute != null) result.add(attribute.getValueElement()); super.visitXmlTag(tag); } @Override public void visitElement(PsiElement element) { if (element.getLanguage() instanceof XMLLanguage) { super.visitElement(element); } } }); return result.isEmpty() ? Collections.emptyList() : result; } }
package com.intellij.debugger.memory.agent; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.engine.evaluation.EvaluationContextImpl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.concurrency.AppExecutorUtil; import com.sun.jdi.ObjectReference; import com.sun.jdi.ReferenceType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; class MemoryAgentImpl implements MemoryAgent { private enum MemoryAgentActionState { RUNNING, FINISHED, CANCELLED } private static final Logger LOG = Logger.getInstance(MemoryAgentImpl.class); static final MemoryAgent DISABLED = new MemoryAgentImpl(); private final IdeaNativeAgentProxyMirror myProxy; private final MemoryAgentProgressTracker myProgressTracker; private MemoryAgentCapabilities myCapabilities; private MemoryAgentActionState myState; private File myCancellationFile; private ProgressIndicator myProgressIndicator; public static MemoryAgent createMemoryAgent(@NotNull EvaluationContextImpl evaluationContext) throws EvaluateException { MemoryAgentImpl memoryAgent = new MemoryAgentImpl(); memoryAgent.myCapabilities = memoryAgent.myProxy.initializeCapabilities(evaluationContext); return memoryAgent; } private MemoryAgentImpl() { String tempDir = FileUtil.getTempDirectory() + "/"; int version = new Random().nextInt(); myProxy = new IdeaNativeAgentProxyMirror( tempDir + "memoryAgentCancellationFile" + version, tempDir + "memoryAgentProgressFile" + version + ".json" ); myCapabilities = MemoryAgentCapabilities.DISABLED; myState = MemoryAgentActionState.FINISHED; myProgressTracker = new MemoryAgentProgressTracker(); } private <T> MemoryAgentActionResult<T> executeOperation(Callable<MemoryAgentActionResult<T>> callable) throws EvaluateException { if (myState == MemoryAgentActionState.RUNNING) { throw new EvaluateException("Some action is already running"); } if (myCancellationFile != null) { FileUtil.delete(myCancellationFile); myCancellationFile = null; } try { myState = MemoryAgentActionState.RUNNING; myProgressTracker.startMonitoringProgress(); return callable.call(); } catch (Exception ex) { throw new EvaluateException(ex.getMessage()); } finally { myProgressTracker.stopMonitoringProgress(); FileUtil.delete(new File(myProxy.getProgressFileName())); myState = MemoryAgentActionState.FINISHED; } } @NotNull @Override public MemoryAgentActionResult<Pair<long[], ObjectReference[]>> estimateObjectSize(@NotNull EvaluationContextImpl evaluationContext, @NotNull ObjectReference reference, long timeoutInMillis) throws EvaluateException { if (!myCapabilities.canEstimateObjectSize()) { throw new UnsupportedOperationException("Memory agent can't estimate object size"); } return executeOperation(() -> myProxy.estimateObjectSize(evaluationContext, reference, timeoutInMillis)); } @NotNull @Override public MemoryAgentActionResult<long[]> estimateObjectsSizes(@NotNull EvaluationContextImpl evaluationContext, @NotNull List<ObjectReference> references, long timeoutInMillis) throws EvaluateException { if (!myCapabilities.canEstimateObjectsSizes()) { throw new UnsupportedOperationException("Memory agent can't estimate objects sizes"); } return executeOperation(() -> myProxy.estimateObjectsSizes(evaluationContext, references, timeoutInMillis)); } @NotNull @Override public MemoryAgentActionResult<long[]> getShallowSizeByClasses(@NotNull EvaluationContextImpl evaluationContext, @NotNull List<ReferenceType> classes, long timeoutInMillis) throws EvaluateException { if (!myCapabilities.canGetShallowSizeByClasses()) { throw new UnsupportedOperationException("Memory agent can't get shallow size by classes"); } return executeOperation(() -> myProxy.getShallowSizeByClasses(evaluationContext, classes, timeoutInMillis)); } @NotNull @Override public MemoryAgentActionResult<long[]> getRetainedSizeByClasses(@NotNull EvaluationContextImpl evaluationContext, @NotNull List<ReferenceType> classes, long timeoutInMillis) throws EvaluateException { if (!myCapabilities.canGetRetainedSizeByClasses()) { throw new UnsupportedOperationException("Memory agent can't get retained size by classes"); } return executeOperation(() -> myProxy.getRetainedSizeByClasses(evaluationContext, classes, timeoutInMillis)); } @NotNull @Override public MemoryAgentActionResult<Pair<long[], long[]>> getShallowAndRetainedSizeByClasses(@NotNull EvaluationContextImpl evaluationContext, @NotNull List<ReferenceType> classes, long timeoutInMillis) throws EvaluateException { if (!myCapabilities.canGetRetainedSizeByClasses() || !myCapabilities.canGetShallowSizeByClasses()) { throw new UnsupportedOperationException("Memory agent can't get shallow and retained size by classes"); } return executeOperation(() -> myProxy.getShallowAndRetainedSizeByClasses(evaluationContext, classes, timeoutInMillis)); } @NotNull @Override public MemoryAgentActionResult<ReferringObjectsInfo> findPathsToClosestGCRoots(@NotNull EvaluationContextImpl evaluationContext, @NotNull ObjectReference reference, int pathsNumber, int objectsNumber, long timeoutInMillis) throws EvaluateException { if (!myCapabilities.canFindPathsToClosestGcRoots()) { throw new UnsupportedOperationException("Memory agent can't provide paths to closest gc roots"); } return executeOperation(() -> myProxy.findPathsToClosestGCRoots(evaluationContext, reference, pathsNumber, objectsNumber, timeoutInMillis)); } @Override public void cancelAction() { if (myState == MemoryAgentActionState.RUNNING) { try { myProgressTracker.cancelMonitoringProgress(); myCancellationFile = FileUtil.createTempFile(myProxy.getCancellationFileName(), "", true); myState = MemoryAgentActionState.CANCELLED; } catch (IOException ex) { LOG.error("Couldn't create memory agent cancellation file", ex); } } } @Override public void setProgressIndicator(@NotNull ProgressIndicator progressIndicator) { myProgressIndicator = progressIndicator; } @Nullable @Override public MemoryAgentProgressPoint checkProgress() { return myProxy.checkProgress(); } @NotNull @Override public MemoryAgentCapabilities getCapabilities() { return myCapabilities; } private class MemoryAgentProgressTracker { private static final int PROGRESS_CHECKING_DELAY_MS = 500; private ScheduledFuture<?> myProgressCheckingFuture; private void startMonitoringProgress() { if (myProgressIndicator != null) { myProgressIndicator.start(); myProgressCheckingFuture = AppExecutorUtil.getAppScheduledExecutorService() .scheduleWithFixedDelay(this::updateProgress, 0, PROGRESS_CHECKING_DELAY_MS, TimeUnit.MILLISECONDS); } } public void cancelMonitoringProgress() { stopMonitoringProgress(true); } public void stopMonitoringProgress() { stopMonitoringProgress(false); } private void stopMonitoringProgress(boolean cancel) { if (myProgressCheckingFuture != null) { myProgressCheckingFuture.cancel(true); } if (myProgressIndicator != null && myProgressIndicator.isRunning()) { if (cancel) { myProgressIndicator.cancel(); } else { myProgressIndicator.stop(); } } myProgressCheckingFuture = null; } @SuppressWarnings("HardCodedStringLiteral") private void updateProgress() { ApplicationManager.getApplication().assertIsNonDispatchThread(); if (myProgressIndicator == null) { stopMonitoringProgress(); } MemoryAgentProgressPoint progressPoint = checkProgress(); if (progressPoint == null) { return; } ApplicationManager.getApplication().invokeLater(() -> { if (myProgressIndicator != null) { myProgressIndicator.setText(progressPoint.getMessage()); myProgressIndicator.setFraction(progressPoint.getFraction()); } }); if (progressPoint.isFinished()) { stopMonitoringProgress(); } } } }
package org.jasig.portal; import org.jasig.portal.security.IPerson; import org.jasig.portal.services.LogService; import org.jasig.portal.services.GroupService; import java.sql.*; import org.jasig.portal.groups.IEntityGroup; import org.jasig.portal.groups.EntityImpl; import org.jasig.portal.groups.IGroupMember; import org.jasig.portal.utils.CounterStoreFactory; /** * SQL implementation for managing creation and removal of User Portal Data * @author Susan Bramhall, Yale University */ public class RDBMUserIdentityStore implements IUserIdentityStore { /** * constructor gets an rdbm service */ public void RDBMUserIdentityStore () { rdbmService = new RDBMServices(); } /** * getuPortalUID - return a unique uPortal key for a user. * calls alternate signature with createPortalData set to false. * @param IPerson object * @return uPortalUID number * @throws Authorization exception if no user is found. */ public int getPortalUID (IPerson person) throws AuthorizationException { int uPortalUID=-1; uPortalUID=this.getPortalUID(person, false); return uPortalUID; } /** * * removeuPortalUID * @param uPortalUID integer key to uPortal data for a user * @throws Authorization exception if a sql error is encountered */ public void removePortalUID(int uPortalUID) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); if (con.getMetaData().supportsTransactions()) con.setAutoCommit(false); try { String SQLDelete = "DELETE FROM UP_USER WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_USER_LAYOUT WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_USER_PARAM WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_USER_PROFILE WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_SS_USER_ATTS WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_SS_USER_PARM WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_LAYOUT_PARAM WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_USER_UA_MAP WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_LAYOUT_STRUCT WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); if (con.getMetaData().supportsTransactions()) con.commit(); } finally { stmt.close(); } } catch (SQLException se) { try { if (con.getMetaData().supportsTransactions()) con.rollback(); } catch (SQLException e) {} if (DEBUG>0){ System.err.println("SQLException: " + se.getMessage()); System.err.println("SQLState: " + se.getSQLState()); System.err.println("Message: " + se.getMessage()); System.err.println("Vendor: " + se.getErrorCode());} AuthorizationException ae = new AuthorizationException("SQL Database Error"); LogService.log(LogService.ERROR, "RDBMUserIdentityStore::removePortalUID(): " + ae); throw (ae); } finally { rdbmService.releaseConnection(con); } } /** * * getuPortalUID * @param IPerson object, boolean createPortalData indicating whether to try to create * all uPortal data for this user from temp[late prototype * @return uPortalUID number or -1 if unable to create user. * @throws Authorization exception if createPortalData is false and no user is found * or if a sql error is encountered */ public int getPortalUID (IPerson person, boolean createPortalData) throws AuthorizationException { int uPortalUID=-1; // Get a connection to the database Connection con = rdbmService.getConnection(); Statement stmt = null; Statement insertStmt = null; try { // Create the JDBC statement stmt = con.createStatement(); // Create a separate statement for inserts so it doesn't // interfere with ResultSets insertStmt = con.createStatement(); } catch(SQLException se) { try { // Release the connection rdbmService.releaseConnection(con); } catch(Exception e) {} // Log the exception LogService.instance().log(LogService.ERROR, "RDBMUserIdentityStore::getPortalUID(): Could not create database statement", se); throw new AuthorizationException("RDBMUserIdentityStore: Could not create database statement"); } try { // Retrieve the USER_ID that is mapped to their portal UID String query = "SELECT USER_ID, USER_NAME FROM UP_USER WHERE USER_NAME = '" + person.getAttribute("username") + "'"; // DEBUG LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + query); // Execute the query ResultSet rset = stmt.executeQuery(query); // Check to see if we've got a result if (rset.next()) { uPortalUID = rset.getInt("USER_ID"); } // If no result and we're not creating new users then fail else if(!createPortalData) { throw new AuthorizationException("No portal information exists for user " + person.getAttribute("username")); } else { /* attempt to create portal data for a new user */ int newUID; int templateUID; int templateUSER_DFLT_USR_ID ; int templateUSER_DFLT_LAY_ID; java.sql.Date templateLST_CHAN_UPDT_DT = new java.sql.Date(System.currentTimeMillis()); String defaultTemplateUserName = PropertiesManager.getProperty("org.jasig.portal.services.Authentication.defaultTemplateUserName"); // Retrieve the username of the user to use as a template for this new user String templateName=(String) person.getAttribute(templateAttrName); if (DEBUG>0) System.err.println("Attempting to autocreate user from template "+templateName); LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + "template name is " + templateName); // Just use the default template if requested template not populated if (templateName == null || templateName=="") { templateName=defaultTemplateUserName; } // Retrieve the information for the template user query = "SELECT USER_ID, USER_DFLT_USR_ID, USER_DFLT_LAY_ID, NEXT_STRUCT_ID, LST_CHAN_UPDT_DT FROM UP_USER WHERE USER_NAME = '"+templateName+"'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + query); // Execute the query rset = stmt.executeQuery(query); // Check to see if the template user exists if (rset.next()) { templateUID = rset.getInt("USER_ID"); templateUSER_DFLT_USR_ID = templateUID; templateUSER_DFLT_LAY_ID = rset.getInt("USER_DFLT_LAY_ID"); } // if no results on default template throw error // otherwise try the default else { if (templateName.equals(defaultTemplateUserName)) throw new AuthorizationException("No information found for template user = " + templateName + ". Cannot create new account for " + person.getAttribute("username")); else { templateName=defaultTemplateUserName; query = "SELECT USER_ID, USER_DFLT_USR_ID, USER_DFLT_LAY_ID, NEXT_STRUCT_ID, LST_CHAN_UPDT_DT FROM UP_USER WHERE USER_NAME = '"+ templateName+"'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + query); // Execute the query rset = stmt.executeQuery(query); // Check to see if the template user exists if (rset.next()) { templateUID = rset.getInt("USER_ID"); templateUSER_DFLT_USR_ID = templateUID; templateUSER_DFLT_LAY_ID = rset.getInt("USER_DFLT_LAY_ID"); } else throw new AuthorizationException("No information found for template user = " + templateName + ". Cannot create new account for " + person.getAttribute("username")); } } /* get a new uid for the person */ try { newUID = CounterStoreFactory.getCounterStoreImpl().getIncrementIntegerId("UP_USER"); } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMUserIdentityStore::getPortalUID(): error getting next sequence: ", e); throw new AuthorizationException("RDBMUserIdentityStore error, see error log."); } /* put new user in groups that template is in */ try{ IGroupMember me = GroupService.getEntity(String.valueOf(newUID), Class.forName("org.jasig.portal.security.IPerson")); IGroupMember template = GroupService.getEntity(String.valueOf(templateUID), Class.forName("org.jasig.portal.security.IPerson")); java.util.Iterator templateGroups = template.getContainingGroups(); while (templateGroups.hasNext()) { IEntityGroup eg = (IEntityGroup) templateGroups.next(); eg.addMember(me); eg.updateMembers(); } } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMUserIdentityStore::getPortalUID(): error adding new user to groups: ", e); } try { // Turn off autocommit if the database supports it if (con.getMetaData().supportsTransactions()) { con.setAutoCommit(false); } } catch(SQLException se) { // Log the exception LogService.instance().log(LogService.WARN, "RDBMUserIdentityStore: Could not turn off autocommit", se); } String Insert = new String(); /* insert new user record in UP_USER */ Insert = "INSERT INTO UP_USER "+ "(USER_ID, USER_NAME, USER_DFLT_USR_ID, USER_DFLT_LAY_ID, NEXT_STRUCT_ID, LST_CHAN_UPDT_DT) "+ " VALUES ("+ newUID+", '"+ person.getAttribute("username")+ "',"+ templateUSER_DFLT_USR_ID+", "+ templateUSER_DFLT_LAY_ID+", "+ "null, "+ "null)"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + Insert); stmt.executeUpdate(Insert); // replaced INSERT INTO SELECT statements with queries followed // by INSERTS because MySQL does not support this using the same // table. // Courtesy of John Fereira <jaf30@cornell.edu> /* insert row into up_user_layout */ query = "SELECT USER_ID,LAYOUT_ID,LAYOUT_TITLE,INIT_STRUCT_ID FROM UP_USER_LAYOUT WHERE USER_ID="+templateUID; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + query); if (DEBUG>0) System.err.println(query); rset = stmt.executeQuery(query); while (rset.next()) { Insert = "INSERT INTO UP_USER_LAYOUT (USER_ID,LAYOUT_ID,LAYOUT_TITLE,INIT_STRUCT_ID) "+ "VALUES("+ newUID+","+ rset.getInt("LAYOUT_ID")+","+ "'"+rset.getString("LAYOUT_TITLE")+"',"+ "NULL)"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + Insert); if (DEBUG>0) System.err.println(Insert); insertStmt.executeUpdate(Insert); } /* insert row into up_user_param */ query = "SELECT USER_ID,USER_PARAM_NAME,USER_PARAM_VALUE FROM UP_USER_PARAM WHERE USER_ID="+templateUID; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + query); if (DEBUG>0) System.err.println(query); rset = stmt.executeQuery(query); while (rset.next()) { Insert = "INSERT INTO UP_USER_PARAM (USER_ID, USER_PARAM_NAME, USER_PARAM_VALUE ) "+ "VALUES("+ newUID+","+ ",'"+rset.getString("USER_PARAM_NAME")+"',"+ ",'"+rset.getString("USER_PARAM_VALUE")+"')"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + Insert); if (DEBUG>0) System.err.println(Insert); stmt.executeUpdate(Insert); } /* insert row into up_user_profile */ query = "SELECT USER_ID, PROFILE_ID, PROFILE_NAME, DESCRIPTION, NULL, NULL, NULL "+ "FROM UP_USER_PROFILE WHERE USER_ID="+templateUID; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + query); if (DEBUG>0) System.err.println(query); rset = stmt.executeQuery(query); while (rset.next()) { Insert = "INSERT INTO UP_USER_PROFILE (USER_ID, PROFILE_ID, PROFILE_NAME, DESCRIPTION, LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID ) "+ "VALUES("+ newUID+","+ rset.getInt("PROFILE_ID")+","+ "'"+rset.getString("PROFILE_NAME")+"',"+ "'"+rset.getString("DESCRIPTION")+"',"+ "NULL,"+ "NULL,"+ "NULL)"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + Insert); if (DEBUG>0) System.err.println(Insert); insertStmt.executeUpdate(Insert); } /* insert row into up_user_ua_map */ query = " SELECT USER_ID, USER_AGENT, PROFILE_ID"+ " FROM UP_USER_UA_MAP WHERE USER_ID="+templateUID; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + query); if (DEBUG>0) System.err.println(query); rset = stmt.executeQuery(query); while (rset.next()) { Insert = "INSERT INTO UP_USER_UA_MAP (USER_ID, USER_AGENT, PROFILE_ID) "+ "VALUES("+ newUID+","+ "'"+rset.getString("USER_AGENT")+"',"+ rset.getInt("PROFILE_ID")+")"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + Insert); if (DEBUG>0) System.err.println(Insert); insertStmt.executeUpdate(Insert); } /* insert row(s) into up_ss_user_parm */ query = "SELECT USER_ID, PROFILE_ID, SS_ID, SS_TYPE, PARAM_NAME, PARAM_VAL "+ " FROM UP_SS_USER_PARM WHERE USER_ID="+templateUID; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + query); if (DEBUG>0) System.err.println(query); rset = stmt.executeQuery(query); while (rset.next()) { Insert = "INSERT INTO UP_SS_USER_PARM (USER_ID, PROFILE_ID, SS_ID, SS_TYPE, PARAM_NAME, PARAM_VAL) "+ "VALUES("+ newUID+","+ rset.getInt("PROFILE_ID")+","+ rset.getInt("SS_ID")+","+ rset.getInt("SS_TYPE")+","+ "'"+rset.getString("PARAM_NAME")+"',"+ "'"+rset.getString("PARAM_VAL")+"')"; LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + Insert); if (DEBUG>0) System.err.println(Insert); insertStmt.executeUpdate(Insert); } // end of changes for MySQL support // Check to see if the database supports transactions boolean supportsTransactions = false; try { supportsTransactions = con.getMetaData().supportsTransactions(); } catch(Exception e) {} if(supportsTransactions) { // Commit the transaction con.commit(); // Use our new ID if we made it through all of the SQL uPortalUID = newUID; } else { // Use our new ID if we made it through all of the SQL uPortalUID = newUID; } } } catch (SQLException se) { // Log the exception LogService.log(LogService.ERROR, "RDBMUserIdentityStore::getPortalUID(): " + se); // Rollback the transaction try { if (con.getMetaData().supportsTransactions()) { con.rollback(); } } catch (SQLException e) { LogService.instance().log(LogService.WARN, "RDBMUserIdentityStore.getPortalUID(): Unable to rollback transaction", se); } // DEBUG if (DEBUG>0) { System.err.println("SQLException: " + se.getMessage()); System.err.println("SQLState: " + se.getSQLState()); System.err.println("Message: " + se.getMessage()); System.err.println("Vendor: " + se.getErrorCode()); } // Throw an exception throw (new AuthorizationException("SQL database error while retrieving user's portal UID")); } finally { rdbmService.releaseConnection(con); } // Return the user's ID return(uPortalUID); } static final protected void commit (Connection connection) { try { if (connection.getMetaData().supportsTransactions()) connection.commit(); } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMUserIdentityStore::commit(): " + e); } } static final protected void rollback (Connection connection) { try { if (connection.getMetaData().supportsTransactions()) connection.rollback(); } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMUserIdentityStore::rollback(): " + e); } } }
package fm.jiecao.jcvideoplayer_lib; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.nostra13.universalimageloader.core.ImageLoader; import java.util.Formatter; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import de.greenrobot.event.EventBus; public class JCVideoPlayer extends FrameLayout implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, SurfaceHolder.Callback { ImageView ivStart; ProgressBar pbLoading; ImageView ivFullScreen; SeekBar sbProgress; TextView tvTimeCurrent, tvTimeTotal; ResizeSurfaceView surfaceView; SurfaceHolder surfaceHolder; LinearLayout llBottomControl; TextView tvTitle; ImageView ivThumb; LinearLayout rlParent; LinearLayout llTitleContainer; public String url; public String thumb; public String title; public boolean ifFullScreen = false; public String uuid; public boolean ifShowTitle = false; public int CURRENT_STATE = -1;//-1null public static final int CURRENT_STATE_PREPAREING = 0; public static final int CURRENT_STATE_PAUSE = 1; public static final int CURRENT_STATE_PLAYING = 2; public static final int CURRENT_STATE_OVER = 3;//normal public static final int CURRENT_STATE_NORMAL = 4; private OnTouchListener mSeekbarOnTouchListener; private Timer mDismissControlViewTimer; private static Timer mUpdateBufferTimer; public JCVideoPlayer(Context context, AttributeSet attrs) { super(context, attrs); uuid = UUID.randomUUID().toString(); init(context); } private void init(Context context) { View.inflate(context, R.layout.video_control_view, this); ivStart = (ImageView) findViewById(R.id.start); pbLoading = (ProgressBar) findViewById(R.id.loading); ivFullScreen = (ImageView) findViewById(R.id.fullscreen); sbProgress = (SeekBar) findViewById(R.id.progress); tvTimeCurrent = (TextView) findViewById(R.id.current); tvTimeTotal = (TextView) findViewById(R.id.total); surfaceView = (ResizeSurfaceView) findViewById(R.id.surfaceView); llBottomControl = (LinearLayout) findViewById(R.id.bottom_control); tvTitle = (TextView) findViewById(R.id.title); ivThumb = (ImageView) findViewById(R.id.thumb); rlParent = (LinearLayout) findViewById(R.id.parentview); llTitleContainer = (LinearLayout) findViewById(R.id.title_container); // surfaceView.setZOrderOnTop(true); // surfaceView.setBackgroundColor(R.color.black_a10_color); surfaceHolder = surfaceView.getHolder(); ivStart.setOnClickListener(this); ivThumb.setOnClickListener(this); ivFullScreen.setOnClickListener(this); sbProgress.setOnSeekBarChangeListener(this); surfaceHolder.addCallback(this); surfaceView.setOnClickListener(this); llBottomControl.setOnClickListener(this); rlParent.setOnClickListener(this); findViewById(R.id.back).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { quitFullScreen(); } }); sbProgress.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: cancelDismissControlViewTimer(); break; case MotionEvent.ACTION_UP: startDismissControlViewTimer(); break; } if (mSeekbarOnTouchListener != null) { mSeekbarOnTouchListener.onTouch(v, event); } return false; } }); } /** * @param ifShowTitle */ public void setUp(String url, String thumb, String title, boolean ifFullScreen, boolean ifShowTitle) { setIfShowTitle(ifShowTitle); setUp(url, thumb, title, ifFullScreen); } public void setUp(String url, String thumb, String title, boolean ifFullScreen) { this.url = url; this.thumb = thumb; this.title = title; this.ifFullScreen = ifFullScreen; if (ifFullScreen) { ivFullScreen.setImageResource(R.drawable.shrink_video); } else { ivFullScreen.setImageResource(R.drawable.enlarge_video); } tvTitle.setText(title); ivThumb.setVisibility(View.VISIBLE); ivStart.setVisibility(View.VISIBLE); llBottomControl.setVisibility(View.GONE); ivThumb.setImageResource(R.drawable.ic_logo_small); ImageLoader.getInstance().displayImage(thumb, ivThumb); CURRENT_STATE = CURRENT_STATE_NORMAL; setTitleVisibility(View.VISIBLE); } public void setState(int state) { this.CURRENT_STATE = state; if (CURRENT_STATE == CURRENT_STATE_PREPAREING) { ivStart.setVisibility(View.INVISIBLE); ivThumb.setVisibility(View.INVISIBLE); pbLoading.setVisibility(View.VISIBLE); setProgressAndTime(0, 0, 0, 0); } else if (CURRENT_STATE == CURRENT_STATE_PLAYING) { updateStartImage(); ivStart.setVisibility(View.VISIBLE); llBottomControl.setVisibility(View.VISIBLE); setTitleVisibility(View.VISIBLE); ivThumb.setVisibility(View.INVISIBLE); } else if (CURRENT_STATE == CURRENT_STATE_PAUSE) { updateStartImage(); ivStart.setVisibility(View.VISIBLE); llBottomControl.setVisibility(View.VISIBLE); setTitleVisibility(View.VISIBLE); ivThumb.setVisibility(View.INVISIBLE); } else if (CURRENT_STATE == CURRENT_STATE_NORMAL) { ivStart.setVisibility(View.VISIBLE); ivThumb.setVisibility(View.VISIBLE); llBottomControl.setVisibility(View.INVISIBLE); updateStartImage(); cancelDismissControlViewTimer(); cancelBufferTimer(); } } public void setSeekbarOnTouchListener(OnTouchListener listener) { mSeekbarOnTouchListener = listener; } private void startDismissControlViewTimer() { cancelDismissControlViewTimer(); mDismissControlViewTimer = new Timer(); mDismissControlViewTimer.schedule(new TimerTask() { @Override public void run() { if (getContext() != null && getContext() instanceof Activity) { ((Activity) getContext()).runOnUiThread(new Runnable() { @Override public void run() { dismissControlView(); } }); } } }, 2500); } private void cancelDismissControlViewTimer() { if (mDismissControlViewTimer != null) { mDismissControlViewTimer.cancel(); } } private void startUpdateBufferTimer() { cancelBufferTimer(); mUpdateBufferTimer = new Timer(); mUpdateBufferTimer.schedule(new TimerTask() { @Override public void run() { if (getContext() != null && getContext() instanceof Activity) { ((Activity) getContext()).runOnUiThread(new Runnable() { @Override public void run() { VideoEvents videoEvents = new VideoEvents().setType(VideoEvents.VE_MEDIAPLAYER_BUFFERUPDATE); videoEvents.obj = -1; EventBus.getDefault().post(videoEvents); Log.i("update buffer", "updatebuffer:: "); } }); } } }, 0, 300); Log.i("update buffer", "updatebuffer:: start"); } private void cancelBufferTimer() { if (uuid.equals(JCMediaPlayer.intance().uuid)) { if (mUpdateBufferTimer != null) { mUpdateBufferTimer.cancel(); Log.i("update buffer", "updatebuffer:: cancel"); } } } private void dismissControlView() { llBottomControl.setVisibility(View.INVISIBLE); setTitleVisibility(View.INVISIBLE); ivStart.setVisibility(View.INVISIBLE); pbLoading.setVisibility(View.INVISIBLE); } public void setIfShowTitle(boolean ifShowTitle) { this.ifShowTitle = ifShowTitle; } private void setTitleVisibility(int visable) { if (ifShowTitle) { llTitleContainer.setVisibility(visable); } else { if (ifFullScreen) { llTitleContainer.setVisibility(visable); } else { llTitleContainer.setVisibility(View.INVISIBLE); } } } @Override public void onClick(View v) { int i = v.getId(); if (i == R.id.start || i == R.id.thumb) { //1.normalprepare if (CURRENT_STATE == CURRENT_STATE_NORMAL) { JCMediaPlayer.intance().clearWidthAndHeight(); CURRENT_STATE = CURRENT_STATE_PREPAREING; ivStart.setVisibility(View.INVISIBLE); ivThumb.setVisibility(View.INVISIBLE); pbLoading.setVisibility(View.VISIBLE); setProgressAndTime(0, 0, 0, 0); JCMediaPlayer.intance().prepareToPlay(getContext(), url); JCMediaPlayer.intance().setUuid(uuid); VideoEvents videoEvents = new VideoEvents().setType(VideoEvents.VE_START); videoEvents.obj = uuid; EventBus.getDefault().post(videoEvents); surfaceView.requestLayout(); setKeepScreenOn(true); } else if (CURRENT_STATE == CURRENT_STATE_PLAYING) { CURRENT_STATE = CURRENT_STATE_PAUSE; ivThumb.setVisibility(View.INVISIBLE); JCMediaPlayer.intance().mediaPlayer.pause(); updateStartImage(); setKeepScreenOn(false); cancelDismissControlViewTimer(); } else if (CURRENT_STATE == CURRENT_STATE_PAUSE) { CURRENT_STATE = CURRENT_STATE_PLAYING; ivThumb.setVisibility(View.INVISIBLE); JCMediaPlayer.intance().mediaPlayer.start(); updateStartImage(); setKeepScreenOn(true); startDismissControlViewTimer(); } } else if (i == R.id.fullscreen) { //loading if (ifFullScreen) { quitFullScreen(); } else { JCMediaPlayer.intance().mediaPlayer.setDisplay(null); isClickFullscreen = true; FullScreenActivity.toActivity(getContext(), CURRENT_STATE, url, thumb, title); } } else if (i == R.id.surfaceView || i == R.id.parentview) { toggleClear(); startDismissControlViewTimer(); } else if (i == R.id.bottom_control) { JCMediaPlayer.intance().mediaPlayer.setDisplay(surfaceHolder); } } private void toggleClear() { if (CURRENT_STATE == CURRENT_STATE_PREPAREING) { if (llBottomControl.getVisibility() == View.VISIBLE) { llBottomControl.setVisibility(View.INVISIBLE); setTitleVisibility(View.INVISIBLE); } else { llBottomControl.setVisibility(View.VISIBLE); setTitleVisibility(View.VISIBLE); } ivStart.setVisibility(View.INVISIBLE); pbLoading.setVisibility(View.VISIBLE); } else if (CURRENT_STATE == CURRENT_STATE_PLAYING) { if (llBottomControl.getVisibility() == View.VISIBLE) { llBottomControl.setVisibility(View.INVISIBLE); setTitleVisibility(View.INVISIBLE); ivStart.setVisibility(View.INVISIBLE); } else { updateStartImage(); ivStart.setVisibility(View.VISIBLE); llBottomControl.setVisibility(View.VISIBLE); setTitleVisibility(View.VISIBLE); } pbLoading.setVisibility(View.INVISIBLE); } else if (CURRENT_STATE == CURRENT_STATE_PAUSE) { if (llBottomControl.getVisibility() == View.VISIBLE) { llBottomControl.setVisibility(View.INVISIBLE); setTitleVisibility(View.INVISIBLE); ivStart.setVisibility(View.INVISIBLE); } else { updateStartImage(); ivStart.setVisibility(View.VISIBLE); llBottomControl.setVisibility(View.VISIBLE); setTitleVisibility(View.VISIBLE); } pbLoading.setVisibility(View.INVISIBLE); } } public void quitFullScreen() { JCMediaPlayer.intance().mediaPlayer.setDisplay(null); JCMediaPlayer.intance().revertUuid(); VideoEvents videoEvents = new VideoEvents().setType(VideoEvents.VE_SURFACEHOLDER_FINISH_FULLSCREEN); videoEvents.obj = CURRENT_STATE; EventBus.getDefault().post(videoEvents); } private void updateStartImage() { if (CURRENT_STATE == CURRENT_STATE_PLAYING) { ivStart.setImageResource(R.drawable.click_video_pause_selector); } else { ivStart.setImageResource(R.drawable.click_video_play_selector); } } private void setProgressAndTimeFromMediaPlayer(int secProgress) { final int position = JCMediaPlayer.intance().mediaPlayer.getCurrentPosition(); final int duration = JCMediaPlayer.intance().mediaPlayer.getDuration(); int progress = position * 100 / duration; setProgressAndTime(progress, secProgress, position, duration); } private void setProgressAndTime(int progress, int secProgress, int currentTime, int totalTime) { sbProgress.setProgress(progress); if (secProgress >= 0) { sbProgress.setSecondaryProgress(secProgress); } tvTimeCurrent.setText(stringForTime(currentTime)); tvTimeTotal.setText(stringForTime(totalTime)); } public void onEventMainThread(VideoEvents videoEvents) { if (videoEvents.type == VideoEvents.VE_MEDIAPLAYER_FINISH_COMPLETE) { // if (CURRENT_STATE != CURRENT_STATE_PREPAREING) { cancelBufferTimer(); ivStart.setImageResource(R.drawable.click_video_play_selector); ivThumb.setVisibility(View.VISIBLE); ivStart.setVisibility(View.VISIBLE); // JCMediaPlayer.intance().mediaPlayer.setDisplay(null); //TODO // surfaceView.setBackgroundColor(R.color.black_a10_color); CURRENT_STATE = CURRENT_STATE_NORMAL; setKeepScreenOn(false); } if (!JCMediaPlayer.intance().uuid.equals(uuid)) { if (videoEvents.type == VideoEvents.VE_START) { if (CURRENT_STATE != CURRENT_STATE_NORMAL) { setState(CURRENT_STATE_NORMAL); } } return; } if (videoEvents.type == VideoEvents.VE_PREPARED) { JCMediaPlayer.intance().mediaPlayer.setDisplay(surfaceHolder); JCMediaPlayer.intance().mediaPlayer.start(); pbLoading.setVisibility(View.INVISIBLE); llBottomControl.setVisibility(View.VISIBLE); CURRENT_STATE = CURRENT_STATE_PLAYING; startDismissControlViewTimer(); startUpdateBufferTimer(); } else if (videoEvents.type == VideoEvents.VE_MEDIAPLAYER_BUFFERUPDATE) { if (CURRENT_STATE != CURRENT_STATE_NORMAL || CURRENT_STATE != CURRENT_STATE_PREPAREING) { int percent = Integer.valueOf(videoEvents.obj.toString()); setProgressAndTimeFromMediaPlayer(percent); } } else if (videoEvents.type == VideoEvents.VE_SURFACEHOLDER_FINISH_FULLSCREEN) { if (isClickFullscreen) { isFromFullScreenBackHere = true; isClickFullscreen = false; int prev_state = Integer.valueOf(videoEvents.obj.toString()); setState(prev_state); } } else if (videoEvents.type == VideoEvents.VE_SURFACEHOLDER_CREATED) { if (isFromFullScreenBackHere) { //200ms,, // delaySetdisplay(); JCMediaPlayer.intance().mediaPlayer.setDisplay(surfaceHolder); stopToFullscreenOrQuitFullscreenShowDisplay(); isFromFullScreenBackHere = false; } } else if (videoEvents.type == VideoEvents.VE_MEDIAPLAYER_RESIZE) { int mVideoWidth = JCMediaPlayer.intance().currentVideoWidth; int mVideoHeight = JCMediaPlayer.intance().currentVideoHeight; if (mVideoWidth != 0 && mVideoHeight != 0) { surfaceHolder.setFixedSize(mVideoWidth, mVideoHeight); surfaceView.requestLayout(); } } } public void delaySetdisplay() { new Thread(new Runnable() { @Override public void run() { // try { // Thread.sleep(50); // } catch (InterruptedException e) { // e.printStackTrace(); ((Activity) getContext()).runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getContext(), " " + CURRENT_STATE + " " + ifFullScreen, Toast.LENGTH_SHORT).show(); JCMediaPlayer.intance().mediaPlayer.setDisplay(surfaceHolder); } }); } }).start(); } boolean isFromFullScreenBackHere = false;//true boolean isClickFullscreen = false; public void release() { setState(CURRENT_STATE_NORMAL); //surfaceview } // public void drawBlack() {//surfaceview // Canvas canvas = surfaceHolder.lockCanvas(); // canvas.drawColor(R.color.biz_audio_progress_second); // surfaceHolder.unlockCanvasAndPost(canvas); @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { int time = progress * JCMediaPlayer.intance().mediaPlayer.getDuration() / 100; JCMediaPlayer.intance().mediaPlayer.seekTo(time); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); EventBus.getDefault().unregister(this); cancelDismissControlViewTimer(); if (uuid.equals(JCMediaPlayer.intance().uuid)) { JCMediaPlayer.intance().mediaPlayer.stop(); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); EventBus.getDefault().register(this); } @Override public void surfaceCreated(SurfaceHolder holder) { //TODO MediaPlayer set holder,MediaPlayer prepareToPlay EventBus.getDefault().post(new VideoEvents().setType(VideoEvents.VE_SURFACEHOLDER_CREATED)); // drawBlack(); if (ifFullScreen) { JCMediaPlayer.intance().mediaPlayer.setDisplay(surfaceHolder); stopToFullscreenOrQuitFullscreenShowDisplay(); } if (CURRENT_STATE != CURRENT_STATE_NORMAL) { startDismissControlViewTimer(); } } private void stopToFullscreenOrQuitFullscreenShowDisplay() { if (CURRENT_STATE == CURRENT_STATE_PAUSE) { JCMediaPlayer.intance().mediaPlayer.start(); CURRENT_STATE = CURRENT_STATE_PLAYING; new Thread(new Runnable() { @Override public void run() { // try { // Thread.sleep(50); // } catch (InterruptedException e) { // e.printStackTrace(); ((Activity) getContext()).runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getContext(), " " + CURRENT_STATE + " " + ifFullScreen, Toast.LENGTH_SHORT).show(); JCMediaPlayer.intance().mediaPlayer.pause(); CURRENT_STATE = CURRENT_STATE_PAUSE; } }); } }).start(); surfaceView.requestLayout(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { } private String stringForTime(int timeMs) { if (timeMs <= 0 || timeMs >= 24 * 60 * 60 * 1000) { return "00:00"; } int totalSeconds = timeMs / 1000; int seconds = totalSeconds % 60; int minutes = (totalSeconds / 60) % 60; int hours = totalSeconds / 3600; StringBuilder mFormatBuilder = new StringBuilder(); Formatter mFormatter = new Formatter(mFormatBuilder, Locale.getDefault()); if (hours > 0) { return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString(); } else { return mFormatter.format("%02d:%02d", minutes, seconds).toString(); } } public static void releaseAllVideo() { if (JCMediaPlayer.intance().mediaPlayer.isPlaying()) { JCMediaPlayer.intance().mediaPlayer.stop(); JCMediaPlayer.intance().setUuid(""); JCMediaPlayer.intance().setUuid(""); EventBus.getDefault().post(new VideoEvents().setType(VideoEvents.VE_MEDIAPLAYER_FINISH_COMPLETE)); } } }
package weave.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CommandUtils { public static int runCommand(String[] args) throws IOException { return runCommand(args, false); } public static int runCommand(String[] args, boolean debug) throws IOException { Runtime run = Runtime.getRuntime(); Process proc = null; proc = run.exec(args); BufferedReader stdout = new BufferedReader( new InputStreamReader(proc.getInputStream()) ); BufferedReader stderr = new BufferedReader( new InputStreamReader(proc.getErrorStream()) ); while (true) { String line = null; try { // check both streams for new data if (stdout.ready()) { if (debug) line = stdout.readLine(); else stdout.skip(Long.MAX_VALUE); } else if (stderr.ready()) { if (debug) line = stderr.readLine(); else stderr.skip(Long.MAX_VALUE); } // print out data from stream if (line != null) { System.out.println(line); continue; } } catch (IOException ioe) { // stream error, get the return value of the process and return from this function try { return proc.exitValue(); } catch (IllegalThreadStateException itse) { return -Integer.MAX_VALUE; } } try { // if process finished, return return proc.exitValue(); } catch (IllegalThreadStateException itse) { // process is still running, continue } } } }
package src.audio; import be.tarsos.dsp.AudioDispatcher; import be.tarsos.dsp.AudioEvent; import be.tarsos.dsp.AudioProcessor; import be.tarsos.dsp.io.jvm.AudioDispatcherFactory; import be.tarsos.dsp.util.fft.FFT; import be.tarsos.dsp.util.fft.HammingWindow; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; public class Detector { static final int CUTOFF = 20; static final double MEAN = 1.3; // 1.3f static final double DST = 0.23; public static LinkedList<Double> load(File f) { AudioDispatcher dispatcher = null; final FFT fft = new FFT(1024); try { dispatcher = AudioDispatcherFactory.fromPipe(f.getCanonicalPath(), 44100, 1024, 0); } catch (Exception e) { System.out.printf("%s decoding error\n", f.getName()); return null; } final LinkedList<Double> output = new LinkedList<Double>(); final HammingWindow ham = new HammingWindow(); /* * Beat Detection */ AudioProcessor detectProcessor = new AudioProcessor() { double[] spectrum = new double[1024 / 2 + 1]; double[] lastSpectrum = new double[1024 / 2 + 1]; ArrayList<Double> spectralFlux = new ArrayList<Double>(); ArrayList<Double> threshould = new ArrayList<Double>(); ArrayList<Double> pruned = new ArrayList<Double>(); ArrayList<Double> peaks = new ArrayList<Double>(); @Override public boolean process(AudioEvent audioEvent) { float[] buff = audioEvent.getFloatBuffer(); ham.apply(buff); fft.forwardTransform(buff); System.arraycopy(spectrum, 0, lastSpectrum, 0, spectrum.length); /* doubletime */ for (int i = 0; i < spectrum.length; ++i) { spectrum[i] = (double) buff[i]; } //System.arraycopy(buff, 0, spectrum, 0, spectrum.length); /* calculate spectrual flux (distance variance between each height) */ double flux = 0; for (int i = 0; i < spectrum.length; ++i) { double value = (spectrum[i] - lastSpectrum[i]); flux += value < 0 ? 0 : value; // ignore negatives } spectralFlux.add(flux); return true; } @Override public void processingFinished() { /* Use threshold to eliminate noise */ /* its the running average of the spectral flux function */ /* we can detect outliers which indicate a rhythmic onset / beat */ for (int i = 0; i < spectralFlux.size(); i++) { int start = Math.max(0, i - CUTOFF); int end = Math.min(spectralFlux.size() - 1, i + CUTOFF); double mean = 0; for (int j = start; j <= end; ++j) mean += spectralFlux.get(j); mean /= (end - start); threshould.add(mean * MEAN); } /* disregard beats that are not equal to or above the threshold */ for (int i = 0; i < threshould.size(); ++i) { double value = (threshould.get(i) <= spectralFlux.get(i)) ? spectralFlux.get(i) - threshould.get(i) : 0; pruned.add(value); } /* finally capture the peaks in the audio */ for (int i = 0; i < pruned.size() - 1; ++i) { double value = (pruned.get(i) > pruned.get(i + 1)) ? pruned.get(i) : 0; peaks.add(value); } int count = 0; double avg = 0.0f; double prev = 0.0f; double time = 1024.0f / 44100.0f; for (int i = 0; i < peaks.size(); ++i) { double p = peaks.get(i); if (p > 0) { if (Math.abs((i * time) - prev) >= DST) { // if there is at least DST seconds betof each otherw. // System.out.println(i * time); output.add(i * time); count++; } avg += i * time; prev = i * time; } } //System.out.println(count); } }; dispatcher.addAudioProcessor(detectProcessor); dispatcher.run(); return output; } public static void main(String[] args) { Detector.load(new File("closer.mp3")); } }
package info.jiripospisil.pb4nb.ui; import info.jiripospisil.pb4nb.ui.models.ExpirationComboBoxModel; import info.jiripospisil.pb4nb.ui.models.LanguageComboBoxModel; import info.jiripospisil.pb4nb.ui.models.Preferences; import info.jiripospisil.pb4nb.utils.editor.CurrentDocument; import info.jiripospisil.pb4nb.utils.editor.DocumentInfo; import info.jiripospisil.pb4nb.utils.request.PastebinRequest; import info.jiripospisil.pb4nb.utils.request.Post; import info.jiripospisil.pb4nb.utils.stores.ExpirationElement; import info.jiripospisil.pb4nb.utils.stores.LanguageElement; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JComboBox; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JRadioButton; import javax.swing.SwingUtilities; import javax.swing.text.EditorKit; import org.javabuilders.BuildResult; import org.javabuilders.annotations.DoInBackground; import org.javabuilders.event.BackgroundEvent; import org.javabuilders.swing.SwingJavaBuilder; import org.netbeans.api.editor.mimelookup.MimeLookup; /** * * @author Jiri Pospisil <mekishizufu@gmail.com> */ public class PostDialog extends JFrame { private static final Logger log = Logger.getLogger(PastebinRequest.class. getName()); private final BuildResult result; private final PropertyChangeSupport support; private JComboBox languages, expiration; private JEditorPane editor; private Preferences preferences; @SuppressWarnings("LeakingThisInConstructor") public PostDialog() { setupComponents(); support = new PropertyChangeSupport(this); result = SwingJavaBuilder.build(this); } private void setupComponents() { SwingJavaBuilder.getConfig().addResourceBundle(PostDialog.class.getName()); DocumentInfo docInfo = CurrentDocument.getDocumentInfo(); LanguageComboBoxModel languageComboBoxModel = new LanguageComboBoxModel(); languageComboBoxModel.setSelectedItem(docInfo.getContentType()); languages = new JComboBox(languageComboBoxModel); ExpirationComboBoxModel expirationComboBoxModel = new ExpirationComboBoxModel(); expirationComboBoxModel.setSelectedItem("1M"); expiration = new JComboBox(expirationComboBoxModel); editor = new JEditorPane(); editor.setEditorKit( MimeLookup.getLookup(docInfo.getContentType()).lookup(EditorKit.class)); editor.setText(docInfo.getText()); preferences = new Preferences(); preferences.load(); } @DoInBackground(progressMessage = "label.sending") private void post(BackgroundEvent evt) { preferences.save(); try { Post post = getPostFromForm(); final String url = new PastebinRequest().execute(post); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new CopyDialog(url).setVisible(true); } }); } catch (Exception ex) { showAndLogErrorMessage(ex); } } private void showAndLogErrorMessage(Exception ex) { JOptionPane.showMessageDialog(this, "Unable to send the post. See log for details."); log.log(Level.SEVERE, ex.toString()); } private Post getPostFromForm() { Post post = new Post(); post.setEmail(preferences.getEmail()); post.setName(preferences.getNameTitle()); post.setSubdomain(preferences.getSubdomain()); post.setText(editor.getText()); boolean exposure = ((JRadioButton) result.get("exposure_private")). isSelected(); post.setPrivacy(exposure); LanguageElement languageElement = (LanguageElement) languages.getModel(). getSelectedItem(); post.setLanguage(languageElement.getCode()); ExpirationElement expirationElement = (ExpirationElement) expiration. getModel(). getSelectedItem(); post.setExpiration(expirationElement.getCode()); return post; } private void close() { setVisible(false); dispose(); } @Override public void addPropertyChangeListener(PropertyChangeListener listener) { support.addPropertyChangeListener(listener); } @Override public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { support.addPropertyChangeListener(propertyName, listener); } @Override public void removePropertyChangeListener(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } @Override public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { support.removePropertyChangeListener(propertyName, listener); } }
package org.apache.velocity.app; import java.io.Writer; import java.util.Hashtable; import java.util.Properties; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.IOException; import java.io.Reader; import java.io.BufferedReader; import java.io.StringReader; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.velocity.context.Context; import org.apache.velocity.Template; import org.apache.velocity.context.InternalContextAdapterImpl; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.parser.ParserTreeConstants; import org.apache.velocity.runtime.parser.node.SimpleNode; import org.apache.velocity.runtime.directive.VelocimacroProxy; import org.apache.velocity.runtime.configuration.Configuration; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.MethodInvocationException; import org.apache.velocity.runtime.parser.ParseException; import org.apache.commons.collections.ExtendedProperties; /** * This class provides services to the application * developer, such as : * <ul> * <li> Simple Velocity Runtime engine initialization methods. * <li> Functions to apply the template engine to streams and strings * to allow embedding and dynamic template generation. * <li> Methods to access Velocimacros directly. * </ul> * * <br><br> * While the most common way to use Velocity is via templates, as * Velocity is a general-purpose template engine, there are other * uses that Velocity is well suited for, such as processing dynamically * created templates, or processing content streams. * * <br><br> * The methods herein were developed to allow easy access to the Velocity * facilities without direct spelunking of the internals. If there is * something you feel is necessary to add here, please, send a patch. * * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> * @author <a href="Christoph.Reck@dlr.de">Christoph Reck</a> * @author <a href="jvanzyl@apache.org">Jason van Zyl</a> * @version $Id: Velocity.java,v 1.19 2001/07/02 02:28:10 geirm Exp $ */ public class Velocity implements RuntimeConstants { /** * initialize the Velocity runtime engine, using the default * properties of the Velocity distribution */ public static void init() throws Exception { Runtime.init(); } /** * initialize the Velocity runtime engine, using default properties * plus the properties in the properties file passed in as the arg * * @param propsFilename file containing properties to use to initialize * the Velocity runtime */ public static void init( String propsFilename ) throws Exception { Runtime.init(propsFilename); } /** * initialize the Velocity runtime engine, using default properties * plus the properties in the passed in java.util.Properties object * * @param p Proprties object containing initialization properties * */ public static void init( Properties p ) throws Exception { Runtime.init( p ); } /** * Set a Velocity Runtime property. * * @param String key * @param Object value */ public static void setProperty(String key, Object value) { Runtime.setProperty(key,value); } /** * Add a Velocity Runtime property. * * @param String key * @param Object value */ public static void addProperty(String key, Object value) { Runtime.addProperty(key,value); } /** * Clear a Velocity Runtime property. * * @param key of property to clear */ public static void clearProperty(String key) { Runtime.clearProperty(key); } /** * Set an entire configuration at once. This is * useful in cases where the parent application uses * the Configuration class and the velocity configuration * is a subset of the parent application's configuration. * * @param Configuration configuration * * @deprecated Use * {@link #setExtendedProperties( ExtendedProperties ) } */ public static void setConfiguration(Configuration configuration) { /* * Yuk. We added a little helper to Configuration to * help with deprecation. The Configuration class * contains a 'shadow' ExtendedProperties */ ExtendedProperties ep = configuration.getExtendedProperties(); Runtime.setConfiguration( ep ); } /** * Set an entire configuration at once. This is * useful in cases where the parent application uses * the ExtendedProperties class and the velocity configuration * is a subset of the parent application's configuration. * * @param ExtendedProperties configuration * */ public static void setExtendedProperties( ExtendedProperties configuration) { Runtime.setConfiguration( configuration ); } /** * Get a Velocity Runtime property. * * @param key property to retrieve * @return property value or null if the property * not currently set */ public static Object getProperty( String key ) { return Runtime.getProperty( key ); } /** * renders the input string using the context into the output writer. * To be used when a template is dynamically constructed, or want to use * Velocity as a token replacer. * * @param context context to use in rendering input string * @param out Writer in which to render the output * @param logTag string to be used as the template name for log * messages in case of error * @param instring input string containing the VTL to be rendered * * @return true if successful, false otherwise. If false, see * Velocity runtime log */ public static boolean evaluate( Context context, Writer out, String logTag, String instring ) throws ParseErrorException, MethodInvocationException, IOException { return evaluate( context, out, logTag, new BufferedReader( new StringReader( instring )) ); } /** * Renders the input stream using the context into the output writer. * To be used when a template is dynamically constructed, or want to * use Velocity as a token replacer. * * @param context context to use in rendering input string * @param out Writer in which to render the output * @param logTag string to be used as the template name for log messages * in case of error * @param instream input stream containing the VTL to be rendered * * @return true if successful, false otherwise. If false, see * Velocity runtime log * @deprecated Use * {@link #evaluate( Context context, Writer writer, * String logTag, Reader reader ) } */ public static boolean evaluate( Context context, Writer writer, String logTag, InputStream instream ) throws ParseErrorException, MethodInvocationException, IOException { /* * first, parse - convert ParseException if thrown */ BufferedReader br = null; String encoding = null; try { encoding = Runtime.getString(INPUT_ENCODING,ENCODING_DEFAULT); br = new BufferedReader( new InputStreamReader( instream, encoding)); } catch( UnsupportedEncodingException uce ) { String msg = "Unsupported input encoding : " + encoding + " for template " + logTag; throw new ParseErrorException( msg ); } return evaluate( context, writer, logTag, br ); } /** * Renders the input reader using the context into the output writer. * To be used when a template is dynamically constructed, or want to * use Velocity as a token replacer. * * @param context context to use in rendering input string * @param out Writer in which to render the output * @param logTag string to be used as the template name for log messages * in case of error * @param reader Reader containing the VTL to be rendered * * @return true if successful, false otherwise. If false, see * Velocity runtime log * * @since Velocity v1.1 */ public static boolean evaluate( Context context, Writer writer, String logTag, Reader reader ) throws ParseErrorException, MethodInvocationException, IOException { SimpleNode nodeTree = null; try { nodeTree = Runtime.parse( reader, logTag ); } catch ( ParseException pex ) { throw new ParseErrorException( pex.getMessage() ); } /* * now we want to init and render */ if (nodeTree != null) { InternalContextAdapterImpl ica = new InternalContextAdapterImpl( context ); ica.pushCurrentTemplateName( logTag ); try { try { nodeTree.init( ica, null ); } catch( Exception e ) { Runtime.error("Velocity.evaluate() : init exception for tag = " + logTag + " : " + e ); } /* * now render, and let any exceptions fly */ nodeTree.render( ica, writer ); } finally { ica.popCurrentTemplateName(); } return true; } return false; } /** * Invokes a currently registered Velocimacro with the parms provided * and places the rendered stream into the writer. * * Note : currently only accepts args to the VM if they are in the context. * * @param vmName name of Velocimacro to call * @param params[] args used to invoke Velocimacro. In context key format : * eg "foo","bar" (rather than "$foo","$bar") * @param context Context object containing data/objects used for rendering. * @param writer Writer for output stream * @return true if Velocimacro exists and successfully invoked, false otherwise. */ public static boolean invokeVelocimacro( String vmName, String namespace, String params[], Context context, Writer writer ) { /* * check parms */ if ( vmName == null || params == null || context == null || writer == null || namespace == null) { Runtime.error( "Velocity.invokeVelocimacro() : invalid parameter"); return false; } /* * does the VM exist? */ if (!Runtime.isVelocimacro( vmName, namespace )) { Runtime.error( "Velocity.invokeVelocimacro() : VM '"+ vmName + "' not registered."); return false; } /* * apparently. Ok, make one.. */ VelocimacroProxy vp = (VelocimacroProxy) Runtime.getVelocimacro( vmName, namespace ); if ( vp == null ) { Runtime.error( "Velocity.invokeVelocimacro() : VM '" + vmName + "' : severe error. Unable to get VM from factory."); return false; } /* * if we get enough args? */ if ( vp.getNumArgs() > params.length ) { Runtime.error( "Velocity.invokeVelocimacro() : VM '" + vmName + "' : invalid # of args. Needed " + vp.getNumArgs() + " but called with " + params.length); return false; } /* * ok. setup the vm */ /* * fix the parms : since we don't require the $ from the caller, * we need to add it */ int [] types = new int[vp.getNumArgs()]; String[] p = new String[vp.getNumArgs()]; for( int i = 0; i < types.length; i++) { types[i] = ParserTreeConstants.JJTREFERENCE; p[i] = "$" + params[i]; } vp.setupMacro( p, types ); try { InternalContextAdapterImpl ica = new InternalContextAdapterImpl( context ); try { ica.pushCurrentTemplateName( namespace ); vp.render( ica, writer, null); } finally { ica.popCurrentTemplateName(); } } catch (Exception e ) { Runtime.error("Velocity.invokeVelocimacro() : " + e ); return false; } return true; } /** * merges a template and puts the rendered stream into the writer * * @param templateName name of template to be used in merge * @param context filled context to be used in merge * @param writer writer to write template into * * @return true if successful, false otherwise. Errors * logged to velocity log. * * @deprecated Use * {@link #mergeTemplate( String templateName, String encoding, * Context context, Writer writer )} */ public static boolean mergeTemplate( String templateName, Context context, Writer writer ) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, Exception { return mergeTemplate( templateName, Runtime.getString(INPUT_ENCODING,ENCODING_DEFAULT), context, writer ); } /** * merges a template and puts the rendered stream into the writer * * @param templateName name of template to be used in merge * @param encoding encoding used in template * @param context filled context to be used in merge * @param writer writer to write template into * * @return true if successful, false otherwise. Errors * logged to velocity log * * @since Velocity v1.1 */ public static boolean mergeTemplate( String templateName, String encoding, Context context, Writer writer ) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, Exception { Template template = Runtime.getTemplate(templateName, encoding); if ( template == null ) { Runtime.error("Velocity.parseTemplate() failed loading template '" + templateName + "'" ); return false; } else { template.merge(context, writer); return true; } } /** * Returns a <code>Template</code> from the Velocity * resource management system. * * @param name The file name of the desired template. * @return The template. * @throws ResourceNotFoundException if template not found * from any available source. * @throws ParseErrorException if template cannot be parsed due * to syntax (or other) error. * @throws Exception if an error occurs in template initialization */ public static Template getTemplate(String name) throws ResourceNotFoundException, ParseErrorException, Exception { return Runtime.getTemplate( name ); } /** * Returns a <code>Template</code> from the Velocity * resource management system. * * @param name The file name of the desired template. * @param encoding The character encoding to use for the template. * @return The template. * @throws ResourceNotFoundException if template not found * from any available source. * @throws ParseErrorException if template cannot be parsed due * to syntax (or other) error. * @throws Exception if an error occurs in template initialization * * @since Velocity v1.1 */ public static Template getTemplate(String name, String encoding) throws ResourceNotFoundException, ParseErrorException, Exception { return Runtime.getTemplate( name, encoding ); } /** * Determines if a template is accessable via the currently * configured resource loaders. * <br><br> * Note that the current implementation will <b>not</b> * change the state of the system in any real way - so this * cannot be used to pre-load the resource cache, as the * previous implementation did as a side-effect. * <br><br> * The previous implementation exhibited extreme lazyness and * sloth, and the author has been flogged. * * @param templateName name of the temlpate to search for * @return true if found, false otherwise */ public static boolean templateExists( String templateName ) { return (Runtime.getLoaderNameForResource(templateName) != null); } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Cursor; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; 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.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; 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.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.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 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.plaf.JXLoginPanelAddon; import org.jdesktop.swingx.plaf.LoginPanelUI; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.util.WindowUtils; /** * <p>JXLoginPanel 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>JXLoginPanel</strong> * calls the <code>authenticate</code> method of the <strong>LoginService * </strong>. In order to perform the persistence of the password, * <strong>JXLoginPanel</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 */ public class JXLoginPanel extends JXImagePanel { /** * The Logger */ private static final Logger LOG = Logger.getLogger(JXLoginPanel.class.getName()); /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 3544949969896288564L; /** * UI Class ID */ public final static String uiClassID = "LoginPanelUI"; /** * 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 JXLoginPanel 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 = JXLoginPanel.class.getCanonicalName(); /** * 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 JLabel 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 JXLoginPanel 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; /** * 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..., cancelling 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; /** * Creates a default JXLoginPanel instance */ static { LookAndFeelAddons.contribute(new JXLoginPanelAddon()); } /** * Popuplate UIDefaults with the localizable Strings we will use * in the Login panel. */ private void reinitLocales(Locale l) { ResourceBundle res = ResourceBundle.getBundle("org.jdesktop.swingx.auth.resources.resources", l); Enumeration<String> keys = res.getKeys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); UIManager.put(CLASS_NAME + "." + key, res.getString(key)); } setBannerText(UIManager.getString(CLASS_NAME + ".bannerString")); banner.setImage(createLoginBanner()); errorMessageLabel.setText(UIManager.getString(CLASS_NAME + ".errorMessage")); progressMessageLabel.setText(UIManager.getString(CLASS_NAME + ".pleaseWait")); recreateLoginPanel(); Window w = SwingUtilities.getWindowAncestor(this); if (w instanceof JXLoginFrame) { JXLoginFrame f = (JXLoginFrame) w; f.setTitle(UIManager.getString(CLASS_NAME + ".titleString")); for (Component c : f.getContentPane().getComponents()) { if (c instanceof JXBtnPanel) { JXBtnPanel p = (JXBtnPanel) c; p.getOk().setText(UIManager.getString(CLASS_NAME + ".loginString")); p.getCancel().setText(UIManager.getString(CLASS_NAME + ".cancelString")); int h = p.getOk().getPreferredSize().height; p.getOk().setPreferredSize(null); p.getCancel().setPreferredSize(null); int prefWidth = Math.max(p.getCancel().getPreferredSize().width, p.getOk().getPreferredSize().width); p.getCancel().setPreferredSize(new Dimension(prefWidth, h)); p.getOk().setPreferredSize(new Dimension(prefWidth, p.getOk().getPreferredSize().height)); p.invalidate(); } } } JLabel lbl = (JLabel) passwordField.getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManager.getString(CLASS_NAME + ".passwordString")); } lbl = (JLabel) namePanel.getComponent().getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManager.getString(CLASS_NAME + ".nameString")); } if (serverCombo != null) { lbl = (JLabel) serverCombo.getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManager.getString(CLASS_NAME + ".serverString")); } } saveCB.setText(UIManager.getString(CLASS_NAME + ".rememberPasswordString")); } /** * Create a {@code JXLoginPanel} 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 JXLoginPanel() { this(null); } /** * Create a {@code JXLoginPanel} 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 JXLoginPanel(LoginService service) { this(service, null, null); } /** * Create a {@code JXLoginPanel} 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 JXLoginPanel(LoginService service, PasswordStore passwordStore, UserNameStore userStore) { this(service, passwordStore, userStore, null); } /** * Create a {@code JXLoginPanel} 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 JXLoginPanel(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(); //initLocales(getDefaultLocale()); initComponents(); } /** * {@inheritDoc} */ public LoginPanelUI getUI() { return (LoginPanelUI) super.getUI(); } /** * Sets the look and feel (L&F) object that renders this component. * * @param ui the LoginPanelUI L&F object * @see javax.swing.UIDefaults#getUI */ public void setUI(LoginPanelUI 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 */ @Override public void updateUI() { setUI((LoginPanelUI) LookAndFeelAddons.getUI(this, LoginPanelUI.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(UIManager.getString(CLASS_NAME + ".nameString")); nameLabel.setLabelFor(namePanel.getComponent()); //create the password component passwordField = new JPasswordField("", 15); JLabel passwordLabel = new JLabel(UIManager.getString(CLASS_NAME + ".passwordString")); passwordLabel.setLabelFor(passwordField); //create the server combo box if necessary JLabel serverLabel = new JLabel(UIManager.getString(CLASS_NAME + ".serverString")); 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(UIManager.getString(CLASS_NAME + ".rememberPasswordString")); 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); loginPanel.setLayout(new GridBagLayout()); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, 0, 5, 11); loginPanel.add(nameLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; 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(namePanel.getComponent(), gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, 0, 5, 11); loginPanel.add(passwordLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; 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(passwordField, gridBagConstraints); if (serverCombo != null) { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, 0, 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(6, 0, 0, 0); loginPanel.add(saveCB, 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(6, 0, 0, 0); loginPanel.add(saveCB, 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(); setBannerText(UIManager.getString(CLASS_NAME + ".bannerString")); 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 JLabel(UIManager.getString(CLASS_NAME + ".errorMessage")); errorMessageLabel.setIcon(UIManager.getIcon("JXLoginDialog.error.icon")); errorMessageLabel.setVerticalTextPosition(SwingConstants.TOP); errorMessageLabel.setOpaque(true); errorMessageLabel.setBackground(new Color(255, 215, 215));//TODO get from UIManager errorMessageLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(errorMessageLabel.getBackground().darker()), BorderFactory.createEmptyBorder(5, 7, 5, 5))); //TODO get color from UIManager 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(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(0, 36, 0, 11, contentPanel.getBackground()), errorMessageLabel.getBorder())); contentPanel.add(errorMessageLabel); //create the progress panel progressPanel = new JXPanel(new GridBagLayout()); progressMessageLabel = new JLabel(UIManager.getString(CLASS_NAME + ".pleaseWait")); progressMessageLabel.setFont(progressMessageLabel.getFont().deriveFont(Font.BOLD)); //TODO get from UIManager 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); } /** * 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); } } @Override 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(UIManager.getString(CLASS_NAME + ".pleaseWait")); 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(UIManager.getString(CLASS_NAME + ".cancelWait")); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(false); loginService.cancelAuthentication(); setCursor(oldCursor); } /** * TODO */ protected void savePassword() { if (saveCB.isSelected() && (saveMode == SaveMode.BOTH || saveMode == SaveMode.PASSWORD) && passwordStore != null) { passwordStore.set(getUserName(),getLoginService().getServer(),getPassword()); } } /* 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 JXLoginPanel.startLogin */ private static final class LoginAction extends AbstractActionExt { private JXLoginPanel panel; public LoginAction(JXLoginPanel p) { super(UIManager.getString(CLASS_NAME + ".loginString"), 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 JXLoginPanel panel; public CancelAction(JXLoginPanel p) { 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) { JXLoginPanel panel = new JXLoginPanel(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, JXLoginPanel 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) { JXLoginPanel panel = new JXLoginPanel(svc, ps, us, servers); return showLoginFrame(panel); } public static JXLoginFrame showLoginFrame(JXLoginPanel panel) { return new JXLoginFrame(panel); } public static final class JXLoginDialog extends JDialog { private JXLoginPanel panel; public JXLoginDialog(Frame parent, JXLoginPanel p) { super(parent, true); init(p); } public JXLoginDialog(Dialog parent, JXLoginPanel p) { super(parent, true); init(p); } protected void init(JXLoginPanel p) { setTitle(UIManager.getString(CLASS_NAME + ".titleString")); this.panel = p; initWindow(this, panel); } public JXLoginPanel.Status getStatus() { return panel.getStatus(); } } public static final class JXLoginFrame extends JFrame { private JXLoginPanel panel; public JXLoginFrame(JXLoginPanel p) { super(UIManager.getString(CLASS_NAME + ".titleString")); this.panel = p; initWindow(this, panel); } public JXLoginPanel.Status getStatus() { return panel.getStatus(); } public JXLoginPanel 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 JXLoginPanel.JXLoginDialog). Change to private if JXLoginDialog is * removed. */ static void initWindow(final Window w, final JXLoginPanel 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(UIManager.getString(CLASS_NAME + ".cancelString")); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //change panel status to cancelled! panel.status = JXLoginPanel.Status.CANCELLED; w.setVisible(false); w.dispose(); } }); panel.addPropertyChangeListener("status", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { JXLoginPanel.Status status = (JXLoginPanel.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); } } }); cancelButton.setText(UIManager.getString(CLASS_NAME + ".cancelString")); okButton.setText(UIManager.getString(CLASS_NAME + ".loginString")); int prefWidth = Math.max(cancelButton.getPreferredSize().width, okButton.getPreferredSize().width); cancelButton.setPreferredSize(new Dimension(prefWidth, okButton.getPreferredSize().height)); okButton.setPreferredSize(new Dimension(prefWidth, okButton.getPreferredSize().height)); JXPanel buttonPanel = new JXBtnPanel(new GridBagLayout(), okButton, cancelButton); buttonPanel.add(okButton, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.NONE, new Insets(17, 12, 11, 5), 0, 0)); buttonPanel.add(cancelButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.NONE, new Insets(17, 0, 11, 11), 0, 0)); w.add(buttonPanel, 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 static class JXBtnPanel extends JXPanel { private JButton cancel; private JButton ok; public JXBtnPanel(GridBagLayout layout, JButton okButton, JButton cancelButton) { super(layout); this.ok = okButton; this.cancel = cancelButton; } /** * @return the cancel */ public JButton getCancel() { return cancel; } /** * @return the ok */ public JButton getOk() { return ok; } } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; 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.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.ResourceBundle; 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.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JProgressBar; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.UIManager; 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.LoginService; import org.jdesktop.swingx.auth.PasswordStore; import org.jdesktop.swingx.auth.UserNameStore; import org.jdesktop.swingx.plaf.JXLoginPanelAddon; import org.jdesktop.swingx.plaf.LoginPanelUI; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.util.WindowUtils; /** * <p>JXLoginPanel 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>JXLoginPanel</strong> * calls the <code>authenticate</code> method of the <strong>LoginService * </strong>. In order to perform the persistence of the password, * <strong>JXLoginPanel</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. * * Changes by Shai: * Clarified the save mode a little bit including hiding the save checkbox when there * is no password store. * Changed the class to derive from JXImagePanel to make customization easier (need to * check my ImagePanel which has some technical advantages). * Removed the static keyword from the ok/cancel buttons since this can cause an issue * with more than one login dialogs (yes its an unlikely situation but documenting this * sort of behavior or dealing with one bug resulting from this can be a real pain!). * Allowed the name field to be represented as a text field when there is no password store. * Rewrote the layout code to mostly work with a single container. * Removed additional dialogs for progress and error messages and incorporated their * functionality into the main dialog. * Allowed for an IOException with a message to be thrown by the login code. This message * is displayed to the user when the login is stopped. * Removed repetetive code and moved it to a static block. * i18n converted some of the strings that were not localized. * * @author Bino George * @author Shai Almog * @author rbair */ public class JXLoginPanel extends JXImagePanel { /** * The Logger */ private static final Logger LOG = Logger.getLogger(JXLoginPanel.class.getName()); /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 3544949969896288564L; /** * UI Class ID */ public final static String uiClassID = "LoginPanelUI"; /** * 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 JXLoginPanel 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; /** * 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 = "Login"; /** * 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 JLabel 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 JXLoginPanel has a length greater * than 1. */ private JXComboBox serverCombo; /** * Check box presented if a PasswordStore is used, allowing the user to decide whether to * save their password */ private JCheckBox saveCB; /** * 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..., cancelling 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; /** * Listens to login events on the LoginService. Updates the UI and the * JXLoginPanel.state as appropriate */ private LoginListenerImpl loginListener; /** * Tracks the cursor at the time that authentication was started, and restores to that * cursor after authentication ends, or is cancelled; */ private Cursor oldCursor; /** * Creates a default JXLoginPanel instance */ static { LookAndFeelAddons.contribute(new JXLoginPanelAddon()); // Popuplate UIDefaults with the localizable Strings we will use // in the Login panel. CLASS_NAME = JXLoginPanel.class.getCanonicalName(); String lookup; ResourceBundle res = ResourceBundle.getBundle("org.jdesktop.swingx.auth.resources.resources"); Enumeration<String> keys = res.getKeys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); lookup = CLASS_NAME + "." + key; if (UIManager.getString(lookup) == null) { UIManager.put(lookup, res.getString(key)); } } } /** * Create a new JXLoginPanel */ public JXLoginPanel() { this(null); } /** * Create a new JXLoginPanel * @param service The LoginService to use for logging in */ public JXLoginPanel(LoginService service) { this(service, null, null); } /** * Create a new JXLoginPanel * @param service * @param passwordStore * @param userStore */ public JXLoginPanel(LoginService service, PasswordStore passwordStore, UserNameStore userStore) { this(service, passwordStore, userStore, null); } /** * Create a new JXLoginPanel * @param service * @param passwordStore * @param userStore * @param servers */ public JXLoginPanel(LoginService service, PasswordStore passwordStore, UserNameStore userStore, List<String> servers) { this.loginService = service == null ? new NullLoginService() : service; this.passwordStore = passwordStore == null ? new NullPasswordStore() : passwordStore; this.userNameStore = userStore == null ? new DefaultUserNameStore() : userStore; this.servers = servers == null ? new ArrayList<String>() : 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; } loginListener = new LoginListenerImpl(); this.loginService.addLoginListener(loginListener); updateUI(); initComponents(); } /** * @inheritDoc */ public LoginPanelUI getUI() { return (LoginPanelUI)super.getUI(); } /** * 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(UIManager.getString(CLASS_NAME + ".nameString")); nameLabel.setLabelFor(namePanel.getComponent()); //create the password component passwordField = new JPasswordField("", 15); JLabel passwordLabel = new JLabel(UIManager.getString(CLASS_NAME + ".passwordString")); passwordLabel.setLabelFor(passwordField); //create the server combo box if necessary // JLabel serverLabel = new JLabel(UIManager.getString(CLASS_NAME + ".serverString")); JLabel serverLabel = new JLabel("Server"); if (servers.size() > 1) { serverCombo = new JXComboBox(servers.toArray()); serverLabel.setLabelFor(serverCombo); } else { serverCombo = null; } //create the save check box. By default, it is not selected saveCB = new JCheckBox(UIManager.getString(CLASS_NAME + ".rememberPasswordString")); 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); loginPanel.setLayout(new GridBagLayout()); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = GridBagConstraints.WEST; gridBagConstraints.insets = new Insets(0, 0, 5, 11); loginPanel.add(nameLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 1; gridBagConstraints.anchor = GridBagConstraints.WEST; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(namePanel.getComponent(), gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.WEST; gridBagConstraints.insets = new Insets(0, 0, 5, 11); loginPanel.add(passwordLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 1; gridBagConstraints.anchor = GridBagConstraints.WEST; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(passwordField, gridBagConstraints); if (serverCombo != null) { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = GridBagConstraints.WEST; gridBagConstraints.insets = new Insets(0, 0, 5, 11); loginPanel.add(serverLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 1; gridBagConstraints.anchor = GridBagConstraints.WEST; 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.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(6, 0, 0, 0); loginPanel.add(saveCB, gridBagConstraints); } else { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(6, 0, 0, 0); loginPanel.add(saveCB, gridBagConstraints); } return loginPanel; } /** * 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 JLabel("<html><b>Couldn't log in</b><br><br>" + "Check your user name and password. Check to see if Caps Lock is<br>" + "turned on.</html>"); //TODO i18n errorMessageLabel.setIcon(UIManager.getIcon("JXLoginDialog.error.icon")); errorMessageLabel.setVerticalTextPosition(SwingConstants.TOP); errorMessageLabel.setOpaque(true); errorMessageLabel.setBackground(new Color(255, 215, 215));//TODO get from UIManager errorMessageLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(errorMessageLabel.getBackground().darker()), BorderFactory.createEmptyBorder(5, 7, 5, 5))); //TODO get color from UIManager 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(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(0, 36, 0, 11, contentPanel.getBackground()), errorMessageLabel.getBorder())); contentPanel.add(errorMessageLabel); //create the progress panel progressPanel = new JXPanel(new GridBagLayout()); progressMessageLabel = new JLabel("Please wait, logging in....");//TODO i18n progressMessageLabel.setFont(progressMessageLabel.getFont().deriveFont(Font.BOLD)); //TODO get from UIManager 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.WEST, 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); } /** * 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) { this.saveMode = saveMode; recreateLoginPanel(); } /** * @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) { if (this.servers != servers) { List<String> old = this.servers; this.servers = servers == null ? new ArrayList<String>() : servers; recreateLoginPanel(); firePropertyChange("servers", old, servers); } } /** * Sets the <strong>LoginService</strong> for this panel. * * @param service service */ public void setLoginService(LoginService service) { loginService = service; } /** * 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 = store; } /** * 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 */ public void setBanner(Image img) { banner.setImage(img); } /** * Set the text to use when creating the banner. If a custom banner image * is specified, then this is ignored */ public void setBannerText(String text) { if (text == null) { text = ""; } if (!this.bannerText.equals(text)) { 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); } } /** * 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("Please wait, logging in....");//TODO i18n 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("Cancelling login, please wait....");//TODO i18n getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(false); loginService.cancelAuthentication(); setCursor(oldCursor); } /** * TODO */ protected void savePassword() { if (saveCB.isSelected() && (saveMode == SaveMode.BOTH || saveMode == SaveMode.PASSWORD) && passwordStore != null) { passwordStore.set(getUserName(),getLoginService().getServer(),getPassword()); } } /* 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 && 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 JXLoginPanel.startLogin */ private static final class LoginAction extends AbstractActionExt { private JXLoginPanel panel; public LoginAction(JXLoginPanel p) { super("Login", LOGIN_ACTION_COMMAND); //TODO i18n 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 JXLoginPanel panel; public CancelAction(JXLoginPanel p) { super("Cancel Login", CANCEL_LOGIN_ACTION_COMMAND); //TODO i18n 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; } } /** * 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 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 JXComboBox implements NameComponent { private UserNameStore userNameStore; public ComboNamePanel(final 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(JComponent 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(JComponent 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(JComponent parent, LoginService svc, PasswordStore ps, UserNameStore us, List<String> servers) { JXLoginPanel panel = new JXLoginPanel(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(JComponent parent, JXLoginPanel 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); } 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) { JXLoginPanel panel = new JXLoginPanel(svc, ps, us, servers); return showLoginFrame(panel); } public static JXLoginFrame showLoginFrame(JXLoginPanel panel) { return new JXLoginFrame(panel); } public static final class JXLoginDialog extends JDialog { private JXLoginPanel panel; public JXLoginDialog(Frame parent, JXLoginPanel p) { super(parent, true); init(p); } public JXLoginDialog(Dialog parent, JXLoginPanel p) { super(parent, true); init(p); } protected void init(JXLoginPanel p) { setTitle("Login"); //TODO i18n this.panel = p; initWindow(this, panel); } public JXLoginPanel.Status getStatus() { return panel.getStatus(); } } public static final class JXLoginFrame extends JFrame { private JXLoginPanel panel; public JXLoginFrame(JXLoginPanel p) { super("Login"); //TODO i18n this.panel = p; initWindow(this, panel); } public JXLoginPanel.Status getStatus() { return panel.getStatus(); } public JXLoginPanel 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 JXLoginPanel.JXLoginDialog). Change to private if JXLoginDialog is * removed. */ static void initWindow(final Window w, final JXLoginPanel 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("Close");//TODO i18n cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //change panel status to cancelled! panel.status = JXLoginPanel.Status.CANCELLED; w.setVisible(false); w.dispose(); } }); panel.addPropertyChangeListener("status", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { JXLoginPanel.Status status = (JXLoginPanel.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(); } } }); cancelButton.setText("Close"); int prefWidth = Math.max(cancelButton.getPreferredSize().width, okButton.getPreferredSize().width); cancelButton.setPreferredSize(new Dimension(prefWidth, okButton.getPreferredSize().height)); okButton.setPreferredSize(new Dimension(prefWidth, okButton.getPreferredSize().height)); JXPanel buttonPanel = new JXPanel(new GridBagLayout()); buttonPanel.add(okButton, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(17, 12, 11, 5), 0, 0)); buttonPanel.add(cancelButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(17, 0, 11, 11), 0, 0)); w.add(buttonPanel, 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)); } }
package org.jivesoftware.spark; import org.jivesoftware.MainWindow; import org.jivesoftware.MainWindowListener; import org.jivesoftware.Spark; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smackx.debugger.EnhancedDebuggerWindow; import org.jivesoftware.smackx.packet.DelayInformation; import org.jivesoftware.smackx.packet.VCard; import org.jivesoftware.spark.component.tabbedPane.SparkTabbedPane; import org.jivesoftware.spark.filetransfer.SparkTransferManager; import org.jivesoftware.spark.search.SearchManager; import org.jivesoftware.spark.ui.ChatContainer; import org.jivesoftware.spark.ui.ChatRoom; import org.jivesoftware.spark.ui.ChatRoomNotFoundException; import org.jivesoftware.spark.ui.CommandPanel; import org.jivesoftware.spark.ui.ContactItem; import org.jivesoftware.spark.ui.ContactList; import org.jivesoftware.spark.ui.conferences.ConferenceServices; import org.jivesoftware.spark.ui.status.StatusBar; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.TaskEngine; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.sparkimpl.plugin.alerts.BroadcastPlugin; import org.jivesoftware.sparkimpl.plugin.bookmarks.BookmarkPlugin; import org.jivesoftware.sparkimpl.plugin.gateways.GatewayPlugin; import org.jivesoftware.sparkimpl.plugin.manager.Enterprise; import org.jivesoftware.sparkimpl.plugin.transcripts.ChatTranscriptPlugin; import java.awt.CardLayout; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.util.TimerTask; import javax.swing.AbstractAction; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; /** * The inner Container for Spark. The Workspace is the container for all plugins into the Spark * install. Plugins would use this for the following: * <p/> * <ul> * <li>Add own tab to the main tabbed pane. ex. * <p/> * <p/> * Workspace workspace = SparkManager.getWorkspace(); * JButton button = new JButton("HELLO SPARK USERS"); * workspace.getWorkspacePane().addTab("MyPlugin", button); * </p> * <p/> * <li>Retrieve the ContactList. */ public class Workspace extends JPanel implements PacketListener { private SparkTabbedPane workspacePane; private StatusBar statusBox; private CommandPanel commandPanel; private ContactList contactList; private ConferenceServices conferences; private ChatTranscriptPlugin transcriptPlugin; private GatewayPlugin gatewayPlugin; private BookmarkPlugin bookmarkPlugin; private BroadcastPlugin broadcastPlugin; private static Workspace singleton; private static final Object LOCK = new Object(); private JPanel cardPanel; private CardLayout cardLayout; public static final String WORKSPACE_PANE = "WORKSPACE_PANE"; /** * Returns the singleton instance of <CODE>Workspace</CODE>, * creating it if necessary. * <p/> * * @return the singleton instance of <Code>Workspace</CODE> */ public static Workspace getInstance() { // Synchronize on LOCK to ensure that we don't end up creating // two singletons. synchronized (LOCK) { if (null == singleton) { Workspace controller = new Workspace(); singleton = controller; return controller; } } return singleton; } /** * Creates the instance of the SupportChatWorkspace. */ private Workspace() { final MainWindow mainWindow = SparkManager.getMainWindow(); // Add MainWindow listener mainWindow.addMainWindowListener(new MainWindowListener() { public void shutdown() { final ChatContainer container = SparkManager.getChatManager().getChatContainer(); // Close all Chats. for (ChatRoom chatRoom : container.getChatRooms()) { // Leave ChatRoom container.leaveChatRoom(chatRoom); } conferences.shutdown(); gatewayPlugin.shutdown(); bookmarkPlugin.shutdown(); broadcastPlugin.shutdown(); } public void mainWindowActivated() { } public void mainWindowDeactivated() { } }); // Initialize workspace pane, defaulting the tabs to the bottom. workspacePane = new SparkTabbedPane(JTabbedPane.BOTTOM); workspacePane.setActiveButtonBold(true); // Add Panels. cardLayout = new CardLayout(); cardPanel = new JPanel(cardLayout); cardPanel.setOpaque(false); cardPanel.add(WORKSPACE_PANE, this); statusBox = new StatusBar(); commandPanel = new CommandPanel(); // Build default workspace this.setLayout(new GridBagLayout()); add(workspacePane, new GridBagConstraints(0, 9, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 4, 4, 4), 0, 0)); add(statusBox, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 4, 4, 4), 0, 0)); add(commandPanel, new GridBagConstraints(0, 5, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 4, 0, 4), 0, 0)); this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F12"), "showDebugger"); this.getActionMap().put("showDebugger", new AbstractAction("showDebugger") { public void actionPerformed(ActionEvent evt) { EnhancedDebuggerWindow window = EnhancedDebuggerWindow.getInstance(); window.setVisible(true); } }); // Set background setBackground(Color.white); } /** * Builds the Workspace layout. */ public void buildLayout() { new Enterprise(); // Initialize Contact List contactList = new ContactList(); conferences = new ConferenceServices(); // Init contact list. contactList.initialize(); // Load VCard information for status box statusBox.loadVCard(); // Initialise TransferManager SparkTransferManager.getInstance(); } /** * Starts the Loading of all Spark Plugins. */ public void loadPlugins() { // Add presence and message listeners // we listen for these to force open a 1-1 peer chat window from other operators if // one isn't already open PacketFilter workspaceMessageFilter = new PacketTypeFilter(Message.class); // Add the packetListener to this instance SparkManager.getSessionManager().getConnection().addPacketListener(this, workspaceMessageFilter); // Make presence available to anonymous requests, if from anonymous user in the system. PacketListener workspacePresenceListener = new PacketListener() { public void processPacket(Packet packet) { Presence presence = (Presence)packet; if (presence.getProperty("anonymous") != null) { boolean isAvailable = statusBox.getPresence().getMode() == Presence.Mode.available; Presence reply = new Presence(Presence.Type.available); if (!isAvailable) { reply.setType(Presence.Type.unavailable); } reply.setTo(presence.getFrom()); SparkManager.getSessionManager().getConnection().sendPacket(reply); } } }; SparkManager.getSessionManager().getConnection().addPacketListener(workspacePresenceListener, new PacketTypeFilter(Presence.class)); // Send Available status final Presence presence = SparkManager.getWorkspace().getStatusBar().getPresence(); SparkManager.getSessionManager().changePresence(presence); // Until we have better plugin management, will init after presence updates. gatewayPlugin = new GatewayPlugin(); gatewayPlugin.initialize(); // Load all non-presence related items. conferences.loadConferenceBookmarks(); SearchManager.getInstance(); transcriptPlugin = new ChatTranscriptPlugin(); // Load Broadcast Plugin broadcastPlugin = new BroadcastPlugin(); broadcastPlugin.initialize(); // Load BookmarkPlugin bookmarkPlugin = new BookmarkPlugin(); bookmarkPlugin.initialize(); // Schedule loading of the plugins after two seconds. TaskEngine.getInstance().schedule(new TimerTask() { public void run() { final PluginManager pluginManager = PluginManager.getInstance(); pluginManager.loadPlugins(); pluginManager.initializePlugins(); // Subscriptions are always manual Roster roster = SparkManager.getConnection().getRoster(); roster.setSubscriptionMode(Roster.SubscriptionMode.manual); } }, 2000); // Check URI Mappings SparkManager.getChatManager().handleURIMapping(Spark.ARGUMENTS); } /** * Returns the status box for the User. * * @return the status box for the user. */ public StatusBar getStatusBar() { return statusBox; } /** * This is to handle agent to agent conversations. * * @param packet the smack packet to process. */ public void processPacket(final Packet packet) { SwingUtilities.invokeLater(new Runnable() { public void run() { handleIncomingPacket(packet); } }); } private void handleIncomingPacket(Packet packet) { // We only handle message packets here. if (packet instanceof Message) { final Message message = (Message)packet; boolean isGroupChat = message.getType() == Message.Type.groupchat; // Check if Conference invite. If so, do not handle here. if (message.getExtension("x", "jabber:x:conference") != null) { return; } final String body = message.getBody(); boolean broadcast = message.getProperty("broadcast") != null; // Handle offline message. DelayInformation offlineInformation = (DelayInformation)message.getExtension("x", "jabber:x:delay"); if (offlineInformation != null && (Message.Type.chat == message.getType() || Message.Type.normal == message.getType())) { handleOfflineMessage(message); } if (body == null || isGroupChat || broadcast || message.getType() == Message.Type.normal || message.getType() == Message.Type.headline || message.getType() == Message.Type.error) { return; } // Create new chat room for Agent Invite. final String from = packet.getFrom(); final String host = SparkManager.getSessionManager().getServerAddress(); // Don't allow workgroup notifications to come through here. final String bareJID = StringUtils.parseBareAddress(from); if (host.equalsIgnoreCase(from) || from == null) { return; } ChatRoom room = null; try { room = SparkManager.getChatManager().getChatContainer().getChatRoom(bareJID); } catch (ChatRoomNotFoundException e) { // Ignore } // Check for non-existent rooms. if (room == null) { createOneToOneRoom(bareJID, message); } } } /** * Creates a new room if necessary and inserts an offline message. * * @param message The Offline message. */ private void handleOfflineMessage(Message message) { DelayInformation offlineInformation = (DelayInformation)message.getExtension("x", "jabber:x:delay"); String bareJID = StringUtils.parseBareAddress(message.getFrom()); ContactItem contact = contactList.getContactItemByJID(bareJID); String nickname = StringUtils.parseName(bareJID); if (contact != null) { nickname = contact.getNickname(); } // Create the room if it does not exist. ChatRoom room = SparkManager.getChatManager().createChatRoom(bareJID, nickname, nickname); // Insert offline message room.getTranscriptWindow().insertMessage(nickname, message, ChatManager.FROM_COLOR); room.addToTranscript(message, true); // Send display and notified message back. SparkManager.getMessageEventManager().sendDeliveredNotification(message.getFrom(), message.getPacketID()); SparkManager.getMessageEventManager().sendDisplayedNotification(message.getFrom(), message.getPacketID()); } /** * Creates a new room based on an anonymous user. * * @param bareJID the bareJID of the anonymous user. * @param message the message from the anonymous user. */ private void createOneToOneRoom(String bareJID, Message message) { ContactItem contact = contactList.getContactItemByJID(bareJID); String nickname = StringUtils.parseName(bareJID); if (contact != null) { nickname = contact.getNickname(); } else { // Attempt to load VCard from users who we are not subscribed to. VCard vCard = SparkManager.getVCardManager().getVCard(bareJID); if (vCard != null && vCard.getError() == null) { String firstName = vCard.getFirstName(); String lastName = vCard.getLastName(); String userNickname = vCard.getNickName(); if (ModelUtil.hasLength(userNickname)) { nickname = userNickname; } else if (ModelUtil.hasLength(firstName) && ModelUtil.hasLength(lastName)) { nickname = firstName + " " + lastName; } else if (ModelUtil.hasLength(firstName)) { nickname = firstName; } } } SparkManager.getChatManager().createChatRoom(bareJID, nickname, nickname); try { insertMessage(bareJID, message); } catch (ChatRoomNotFoundException e) { Log.error("Could not find chat room.", e); } } private void insertMessage(final String bareJID, final Message message) throws ChatRoomNotFoundException { ChatRoom chatRoom = SparkManager.getChatManager().getChatContainer().getChatRoom(bareJID); chatRoom.insertMessage(message); int chatLength = chatRoom.getTranscriptWindow().getDocument().getLength(); chatRoom.getTranscriptWindow().setCaretPosition(chatLength); chatRoom.getChatInputEditor().requestFocusInWindow(); } /** * Returns the Workspace TabbedPane. If you wish to add your * component, simply use addTab( name, icon, component ) call. * * @return the workspace JideTabbedPane */ public SparkTabbedPane getWorkspacePane() { return workspacePane; } /** * Returns the <code>ContactList</code> associated with this workspace. * * @return the ContactList associated with this workspace. */ public ContactList getContactList() { return contactList; } public void changeCardLayout(String layout) { cardLayout.show(cardPanel, layout); } public JPanel getCardPanel() { return cardPanel; } /** * Returns the <code>CommandPanel</code> of this Workspace. * * @return the CommandPanel. */ public CommandPanel getCommandPanel() { return commandPanel; } }
package picard.cmdline; import htsjdk.samtools.util.CloserUtil; import htsjdk.samtools.util.CollectionUtil.MultiMap; import htsjdk.samtools.util.StringUtil; import picard.PicardException; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Annotation-driven utility for parsing command-line arguments, checking for errors, and producing usage message. * <p/> * This class supports options of the form KEY=VALUE, plus positional arguments. Positional arguments must not contain * an equal sign lest they be mistaken for a KEY=VALUE pair. * <p/> * The caller must supply an object that both defines the command line and has the parsed options set into it. * For each possible KEY=VALUE option, there must be a public data member annotated with @Option. The KEY name is * the name of the data member. An abbreviated name may also be specified with the shortName attribute of @Option. * If the data member is a List<T>, then the option may be specified multiple times. The type of the data member, * or the type of the List element must either have a ctor T(String), or must be an Enum. List options must * be initialized by the caller with some kind of list. Any other option that is non-null is assumed to have the given * value as a default. If an option has no default value, and does not have the optional attribute of @Option set, * is required. For List options, minimum and maximum number of elements may be specified in the @Option annotation. * <p/> * A single List data member may be annotated with the @PositionalArguments. This behaves similarly to a Option * with List data member: the caller must initialize the data member, the type must be constructable from String, and * min and max number of elements may be specified. If no @PositionalArguments annotation appears in the object, * then it is an error for the command line to contain positional arguments. * <p/> * A single String public data member may be annotated with @Usage. This string, if present, is used to * construct the usage message. Details about the possible options are automatically appended to this string. * If @Usage does not appear, a boilerplate usage message is used. */ public class CommandLineParser { // For formatting option section of usage message. private static final int OPTION_COLUMN_WIDTH = 30; private static final int DESCRIPTION_COLUMN_WIDTH = 90; private static final Boolean[] TRUE_FALSE_VALUES = {Boolean.TRUE, Boolean.FALSE}; private static final String[] PACKAGES_WITH_WEB_DOCUMENTATION = {"picard"}; // Use these if no @Usage annotation private static final String defaultUsagePreamble = "Usage: program [options...]\n"; private static final String defaultUsagePreambleWithPositionalArguments = "Usage: program [options...] [positional-arguments...]\n"; private static final String OPTIONS_FILE = "OPTIONS_FILE"; private static final String PRECEDENCE_SYMBOL = "++"; /** name, shortName, description for options built in to framework */ private static final String[][] FRAMEWORK_OPTION_DOC = { {"--help", "-h", "Displays options specific to this tool."}, {"--stdhelp", "-H", "Displays options specific to this tool AND " + "options common to all Picard command line tools."}, {"--version", null, "Displays program version."} }; private final Set<String> optionsThatCannotBeOverridden = new HashSet<String>(); /** * A typical command line program will call this to get the beginning of the usage message, * and then append a description of the program, like this: * <p/> * \@Usage * public String USAGE = CommandLineParser.getStandardUsagePreamble(getClass()) + "Frobnicates the freebozzle." */ public static String getStandardUsagePreamble(final Class mainClass) { return "USAGE: " + mainClass.getSimpleName() + " [options]\n\n" + (hasWebDocumentation(mainClass) ? "Documentation: http://broadinstitute.github.io/picard/command-line-overview.html mainClass.getSimpleName() + "\n\n" : ""); } /** * Determines if a class has web documentation based on its package name * * @param clazz * @return true if the class has web documentation, false otherwise */ public static boolean hasWebDocumentation(final Class clazz) { for (final String pkg : PACKAGES_WITH_WEB_DOCUMENTATION) { if (clazz.getPackage().getName().startsWith(pkg)) { return true; } } return false; } /** * @return the link to a FAQ */ public static String getFaqLink() { return "To get help, see http://broadinstitute.github.io/picard/index.html#GettingHelp"; } /** * Find all of the members annotated with @NestedOptions. * This is package scope and static so that CommandLineProgram can use it to provide default implementation * of its own getNestedOptions() method. */ static Map<String, Object> getNestedOptions(final Object callerOptions) { // LinkedHashMap so usage message is generated in order of declaration final Map<String, Object> ret = new LinkedHashMap<String, Object>(); final Class<?> clazz = callerOptions.getClass(); for (final Field field : getAllFields(clazz)) { if (field.getAnnotation(NestedOptions.class) != null) { field.setAccessible(true); try { ret.put(field.getName(), field.get(callerOptions)); } catch (final IllegalAccessException e) { throw new RuntimeException("Should never happen.", e); } } } return ret; } // This is the object that the caller has provided that contains annotations, // and into which the values will be assigned. private final Object callerOptions; // For child CommandLineParser, this contains the prefix for the option names, which is needed for generating // the command line. For non-nested, this is the empty string. private final String prefix; // For non-nested, empty string. For nested, prefix + "." private final String prefixDot; // null if no @PositionalArguments annotation private Field positionalArguments; private int minPositionalArguments; private int maxPositionalArguments; // List of all the data members with @Option annotation private final List<OptionDefinition> optionDefinitions = new ArrayList<OptionDefinition>(); // Maps long name, and short name, if present, to an option definition that is // also in the optionDefinitions list. private final Map<String, OptionDefinition> optionMap = new HashMap<String, OptionDefinition>(); // Maps child options prefix to CommandLineParser for the child object. // Key: option prefix. private final Map<String, CommandLineParser> childOptionsMap = new LinkedHashMap<String, CommandLineParser>(); // Holds the command-line arguments for a child option parser. // Key: option prefix. Value: List of arguments for child corresponding to that prefix (with prefix stripped). private final MultiMap<String, ChildOptionArg> childOptionArguments = new MultiMap<String, ChildOptionArg>(); // For printing error messages when parsing command line. private PrintStream messageStream; // In case implementation wants to get at arg for some reason. private String[] argv; private String programVersion = null; // The command line used to launch this program, including non-null default options that // weren't explicitly specified. This is used for logging and debugging. private String commandLine = ""; /** * This attribute is here just to facilitate printing usage for OPTIONS_FILE */ public File IGNORE_THIS_PROPERTY; // The associated program properties using the CommandLineProgramProperties annotation private final CommandLineProgramProperties programProperties; /** * Prepare for parsing command line arguments, by validating annotations. * * @param callerOptions This object contains annotations that define the acceptable command-line options, * and ultimately will receive the settings when a command line is parsed. */ public CommandLineParser(final Object callerOptions) { this(callerOptions, ""); } private String getUsagePreamble() { String usagePreamble = ""; if (null != programProperties) { usagePreamble += programProperties.usage(); } else if (positionalArguments == null) { usagePreamble += defaultUsagePreamble; } else { usagePreamble += defaultUsagePreambleWithPositionalArguments; } if (null != this.programVersion && 0 < this.programVersion.length()) { usagePreamble += "Version: " + getVersion() + "\n"; } return usagePreamble; } /** * @param prefix Non-empty for child options object. */ private CommandLineParser(final Object callerOptions, final String prefix) { this.callerOptions = callerOptions; this.prefix = prefix; if (prefix.isEmpty()) { prefixDot = ""; } else { prefixDot = prefix + "."; } for (final Field field : getAllFields(this.callerOptions.getClass())) { if (field.getAnnotation(PositionalArguments.class) != null) { handlePositionalArgumentAnnotation(field); } if (field.getAnnotation(Option.class) != null) { handleOptionAnnotation(field); } else if (!isCommandLineProgram() && field.getAnnotation(NestedOptions.class) != null) { // If callerOptions is an instance of CommandLineProgram, defer creation of child // CommandLineParsers until after parsing options for this parser, in case CommandLineProgram // wants to do something dynamic based on values for this parser. handleNestedOptionsAnnotation(field); } } this.programProperties = this.callerOptions.getClass().getAnnotation(CommandLineProgramProperties.class); } private boolean isCommandLineProgram() { return callerOptions instanceof CommandLineProgram; } private static List<Field> getAllFields(Class clazz) { final List<Field> ret = new ArrayList<Field>(); do { ret.addAll(Arrays.asList(clazz.getDeclaredFields())); clazz = clazz.getSuperclass(); } while (clazz != null); return ret; } public String getVersion() { return this.callerOptions.getClass().getPackage().getImplementationVersion(); } /** * Print a usage message based on the options object passed to the ctor. * * @param stream Where to write the usage message. */ public void usage(final PrintStream stream, final boolean printCommon) { if (prefix.isEmpty()) { stream.print(getStandardUsagePreamble(callerOptions.getClass()) + getUsagePreamble()); stream.println("\nVersion: " + getVersion()); stream.println("\n\nOptions:\n"); for (final String[] optionDoc : FRAMEWORK_OPTION_DOC) { printOptionParamUsage(stream, optionDoc[0], optionDoc[1], null, optionDoc[2]); } } if (!optionDefinitions.isEmpty()) { for (final OptionDefinition optionDefinition : optionDefinitions) { if (printCommon || !optionDefinition.isCommon) printOptionUsage(stream, optionDefinition); } } if (printCommon) { final Field fileField; try { fileField = getClass().getField("IGNORE_THIS_PROPERTY"); } catch (final NoSuchFieldException e) { throw new PicardException("Should never happen", e); } final OptionDefinition optionsFileOptionDefinition = new OptionDefinition(fileField, OPTIONS_FILE, "", "File of OPTION_NAME=value pairs. No positional parameters allowed. Unlike command-line options, " + "unrecognized options are ignored. " + "A single-valued option set in an options file may be overridden " + "by a subsequent command-line option. " + "A line starting with '#' is considered a comment.", false, true, false, 0, Integer.MAX_VALUE, null, true, new String[0]); printOptionUsage(stream, optionsFileOptionDefinition); } // Generate usage for child parsers. final Collection<CommandLineParser> childClps; childClps = getChildParsersForHelp(); for (final CommandLineParser childClp : childClps) { childClp.usage(stream, printCommon); } } private Collection<CommandLineParser> getChildParsersForHelp() { final Collection<CommandLineParser> childClps; if (isCommandLineProgram()) { childClps = new ArrayList<CommandLineParser>(); for (final Map.Entry<String, Object> entry : ((CommandLineProgram) callerOptions).getNestedOptionsForHelp().entrySet()) { if (entry.getKey().contains(".")) { throw new IllegalArgumentException("Prefix for nested options should not contain period: " + entry.getKey()); } childClps.add(new CommandLineParser(entry.getValue(), prefixDot + entry.getKey())); } } else { childClps = childOptionsMap.values(); } return childClps; } public void htmlUsage(final PrintStream stream, final String programName, final boolean printCommon) { // TODO: Should HTML escape usage preamble and option usage, including line breaks stream.println("<a id=\"" + programName + "\"/>"); stream.println("<h3>" + programName + "</h3>"); stream.println("<section>"); stream.println("<p>" + htmlEscape(getUsagePreamble()) + "</p>"); boolean hasOptions = false; for (final OptionDefinition optionDefinition : optionDefinitions) { if (!optionDefinition.isCommon || printCommon) { hasOptions = true; break; } } if (hasOptions) { htmlPrintOptions(stream, printCommon); } stream.println("</section>"); } public void htmlPrintOptions(final PrintStream stream, final boolean printCommon) { stream.println("<table>"); stream.println("<tr><th>Option</th><th>Description</th></tr>"); if (printCommon) { for (final String[] optionDoc : FRAMEWORK_OPTION_DOC) { stream.println("<tr><td>" + optionDoc[0] + "</td><td>" + htmlEscape(optionDoc[2]) + "</td></tr>"); } } htmlPrintOptionTableRows(stream, printCommon); stream.println("</table>"); } /** * Prints options as rows in an HTML table. * * @param stream * @param printCommon */ private void htmlPrintOptionTableRows(final PrintStream stream, final boolean printCommon) { for (final OptionDefinition optionDefinition : optionDefinitions) { if (!optionDefinition.isCommon || printCommon) { printHtmlOptionUsage(stream, optionDefinition); } } for (final CommandLineParser childParser : getChildParsersForHelp()) { childParser.htmlPrintOptionTableRows(stream, false); } } private static String htmlEscape(String str) { // May need more here str = str.replaceAll("<", "&lt;"); str = str.replaceAll("\n", "\n<p>"); return str; } /** * Parse command-line options, and store values in callerOptions object passed to ctor. * * @param messageStream Where to write error messages. * @param args Command line tokens. * @return true if command line is valid. */ public boolean parseOptions(final PrintStream messageStream, final String[] args) { this.argv = args; this.messageStream = messageStream; if (prefix.isEmpty()) { commandLine = callerOptions.getClass().getName(); } for (int i = 0; i < args.length; ++i) { final String arg = args[i]; if (arg.equals("-h") || arg.equals("--help")) { usage(messageStream, false); return false; } if (arg.equals("-H") || arg.equals("--stdhelp")) { usage(messageStream, true); return false; } if (arg.equals("--version")) { messageStream.println(getVersion()); return false; } final String[] pair = arg.split("=", 2); if (pair.length == 2 && pair[1].length() == 0) { if (i < args.length - 1) { pair[1] = args[++i]; } } if (pair.length == 2) { if (!parseOption(pair[0], pair[1], false)) { messageStream.println(); usage(messageStream, true); return false; } } else if (!parsePositionalArgument(arg)) { messageStream.println(); usage(messageStream, false); return false; } } if (!checkNumArguments()) { messageStream.println(); usage(messageStream, false); return false; } if (!parseChildOptions()) { messageStream.println(); usage(messageStream, false); return false; } return true; } /** * After command line has been parsed, make sure that all required options have values, and that * lists with minimum # of elements have sufficient. * * @return true if valid */ private boolean checkNumArguments() { //Also, since we're iterating over all options and args, use this opportunity to recreate the commandLineString final StringBuilder commandLineString = new StringBuilder(); try { for (final OptionDefinition optionDefinition : optionDefinitions) { final String fullName = prefixDot + optionDefinition.name; final StringBuilder mutextOptionNames = new StringBuilder(); for (final String mutexOption : optionDefinition.mutuallyExclusive) { final OptionDefinition mutextOptionDef = optionMap.get(mutexOption); if (mutextOptionDef != null && mutextOptionDef.hasBeenSet) { mutextOptionNames.append(" ").append(prefixDot).append(mutextOptionDef.name); } } if (optionDefinition.hasBeenSet && mutextOptionNames.length() > 0) { messageStream.println("ERROR: Option '" + fullName + "' cannot be used in conjunction with option(s)" + mutextOptionNames.toString()); return false; } if (optionDefinition.isCollection) { final Collection c = (Collection) optionDefinition.field.get(callerOptions); if (c.size() < optionDefinition.minElements) { messageStream.println("ERROR: Option '" + fullName + "' must be specified at least " + optionDefinition.minElements + " times."); return false; } } else if (!optionDefinition.optional && !optionDefinition.hasBeenSet && !optionDefinition.hasBeenSetFromParent && mutextOptionNames.length() == 0) { messageStream.print("ERROR: Option '" + fullName + "' is required"); if (optionDefinition.mutuallyExclusive.isEmpty()) { messageStream.println("."); } else { messageStream.println(" unless any of " + optionDefinition.mutuallyExclusive + " are specified."); } return false; } } if (positionalArguments != null) { final Collection c = (Collection) positionalArguments.get(callerOptions); if (c.size() < minPositionalArguments) { messageStream.println("ERROR: At least " + minPositionalArguments + " positional arguments must be specified."); return false; } for (final Object posArg : c) { commandLineString.append(" ").append(posArg.toString()); } } //first, append args that were explicitly set for (final OptionDefinition optionDefinition : optionDefinitions) { if (optionDefinition.hasBeenSet) { commandLineString.append(" ").append(prefixDot).append(optionDefinition.name).append("=").append( optionDefinition.field.get(callerOptions)); } } commandLineString.append(" "); //separator to tell the 2 apart //next, append args that weren't explicitly set, but have a default value for (final OptionDefinition optionDefinition : optionDefinitions) { if (!optionDefinition.hasBeenSet && !optionDefinition.defaultValue.equals("null")) { commandLineString.append(" ").append(prefixDot).append(optionDefinition.name).append("=").append( optionDefinition.defaultValue); } } this.commandLine += commandLineString.toString(); return true; } catch (final IllegalAccessException e) { // Should never happen because lack of publicness has already been checked. throw new RuntimeException(e); } } private boolean parsePositionalArgument(final String stringValue) { if (positionalArguments == null) { messageStream.println("ERROR: Invalid argument '" + stringValue + "'."); return false; } final Object value; try { value = constructFromString(getUnderlyingType(positionalArguments), stringValue); } catch (final CommandLineParseException e) { messageStream.println("ERROR: " + e.getMessage()); return false; } final Collection c; try { c = (Collection) positionalArguments.get(callerOptions); } catch (final IllegalAccessException e) { throw new RuntimeException(e); } if (c.size() >= maxPositionalArguments) { messageStream.println("ERROR: No more than " + maxPositionalArguments + " positional arguments may be specified on the command line."); return false; } c.add(value); return true; } private boolean parseOption(final String key, final String stringValue, final boolean optionsFile) { return parseOption(key, stringValue, optionsFile, false); } private boolean parseOption(String key, final String stringValue, final boolean optionsFile, boolean precedenceSet) { key = key.toUpperCase(); if (key.equals(OPTIONS_FILE)) { commandLine += " " + prefix + OPTIONS_FILE + "=" + stringValue; return parseOptionsFile(stringValue); } // Check to see if the precedence symbol was used if (key.startsWith(PRECEDENCE_SYMBOL)) { key = key.substring(PRECEDENCE_SYMBOL.length()); precedenceSet = true; } // Save child options for later processing. final Integer prefixIndex = key.indexOf('.'); if (prefixIndex != -1) { final String prefix = key.substring(0, prefixIndex); final String subKey = key.substring(prefixIndex + 1); if (!subKey.isEmpty()) { childOptionArguments.append(prefix, new ChildOptionArg(subKey, stringValue, optionsFile, precedenceSet)); return true; } else { messageStream.println("ERROR: Unrecognized option: " + key); return false; } } final OptionDefinition optionDefinition = optionMap.get(key); if (optionDefinition == null) { if (optionsFile) { // Silently ignore unrecognized option from options file return true; } messageStream.println("ERROR: Unrecognized option: " + key); return false; } // Check to see if the option has been "fixed" already if (this.optionsThatCannotBeOverridden.contains(optionDefinition.name)) { return true; } else if (precedenceSet) { this.optionsThatCannotBeOverridden.add(optionDefinition.name); } if (!optionDefinition.isCollection) { if (optionDefinition.hasBeenSet && !optionDefinition.hasBeenSetFromOptionsFile) { messageStream.println("ERROR: Option '" + key + "' cannot be specified more than once."); return false; } } final Object value; try { if (stringValue.equals("null")) { //"null" is a special value that allows the user to override any default //value set for this arg. It can only be used for optional args. When //used for a list arg, it will clear the list. if (optionDefinition.optional) { value = null; } else { messageStream.println("ERROR: non-null value must be provided for '" + key + "'."); return false; } } else { value = constructFromString(getUnderlyingType(optionDefinition.field), stringValue); } } catch (final CommandLineParseException e) { messageStream.println("ERROR: " + e.getMessage()); return false; } try { if (optionDefinition.isCollection) { final Collection c = (Collection) optionDefinition.field.get(callerOptions); if (value == null) { //user specified this arg=null which is interpreted as empty list c.clear(); } else if (c.size() >= optionDefinition.maxElements) { messageStream.println("ERROR: Option '" + key + "' cannot be used more than " + optionDefinition.maxElements + " times."); return false; } else { c.add(value); } optionDefinition.hasBeenSet = true; optionDefinition.hasBeenSetFromOptionsFile = optionsFile; } else { //get all fields with this name and set them to the argument. final String fieldName = optionDefinition.field.getName(); final Field[] fields = callerOptions.getClass().getFields(); for (final Field field : fields) { if (field.getName().equals(fieldName)) { field.set(callerOptions, value); optionDefinition.hasBeenSet = true; } } if (!optionDefinition.hasBeenSet) { optionDefinition.field.set(callerOptions, value); optionDefinition.hasBeenSet = true; } optionDefinition.hasBeenSetFromOptionsFile = optionsFile; } } catch (final IllegalAccessException e) { // Should never happen because we only iterate through public fields. throw new RuntimeException(e); } return true; } /** * Parsing of options from file is looser than normal. Any unrecognized options are * ignored, and a single-valued option that is set in a file may be overridden by a * subsequent appearance of that option. * A line that starts with '#' is ignored. * * @param optionsFile * @return false if a fatal error occurred */ private boolean parseOptionsFile(final String optionsFile) { return parseOptionsFile(optionsFile, true); } /** * @param optionFileStyleValidation true: unrecognized options are silently ignored; and a single-valued option may be overridden. * false: standard rules as if the options in the file were on the command line directly. * @return */ public boolean parseOptionsFile(final String optionsFile, final boolean optionFileStyleValidation) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(optionsFile)); String line; while ((line = reader.readLine()) != null) { if (line.startsWith("#") || line.trim().length() == 0) { continue; } final String[] pair = line.split("=", 2); if (pair.length == 2) { if (!parseOption(pair[0], pair[1], optionFileStyleValidation)) { messageStream.println(); usage(messageStream, true); return false; } } else { messageStream.println("Strange line in OPTIONS_FILE " + optionsFile + ": " + line); usage(messageStream, true); return false; } } reader.close(); return true; } catch (final IOException e) { throw new PicardException("I/O error loading OPTIONS_FILE=" + optionsFile, e); } finally { CloserUtil.close(reader); } } private void printHtmlOptionUsage(final PrintStream stream, final OptionDefinition optionDefinition) { final String type = getUnderlyingType(optionDefinition.field).getSimpleName(); final String optionLabel = prefixDot + optionDefinition.name + " (" + type + ")"; stream.println("<tr><td>" + optionLabel + "</td><td>" + htmlEscape(makeOptionDescription(optionDefinition)) + "</td></tr>"); } private void printOptionUsage(final PrintStream stream, final OptionDefinition optionDefinition) { printOptionParamUsage(stream, optionDefinition.name, optionDefinition.shortName, getUnderlyingType(optionDefinition.field).getSimpleName(), makeOptionDescription(optionDefinition)); } private void printOptionParamUsage(final PrintStream stream, final String name, final String shortName, final String type, final String optionDescription) { String optionLabel = prefixDot + name; if (type != null) optionLabel += "=" + type; stream.print(optionLabel); if (shortName != null && shortName.length() > 0) { stream.println(); optionLabel = prefixDot + shortName; if (type != null) optionLabel += "=" + type; stream.print(optionLabel); } int numSpaces = OPTION_COLUMN_WIDTH - optionLabel.length(); if (optionLabel.length() > OPTION_COLUMN_WIDTH) { stream.println(); numSpaces = OPTION_COLUMN_WIDTH; } printSpaces(stream, numSpaces); final String wrappedDescription = StringUtil.wordWrap(optionDescription, DESCRIPTION_COLUMN_WIDTH); final String[] descriptionLines = wrappedDescription.split("\n"); for (int i = 0; i < descriptionLines.length; ++i) { if (i > 0) { printSpaces(stream, OPTION_COLUMN_WIDTH); } stream.println(descriptionLines[i]); } stream.println(); } private String makeOptionDescription(final OptionDefinition optionDefinition) { final StringBuilder sb = new StringBuilder(); if (optionDefinition.doc.length() > 0) { sb.append(optionDefinition.doc); sb.append(" "); } if (optionDefinition.optional) { sb.append("Default value: "); sb.append(optionDefinition.defaultValue); sb.append(". "); if (!optionDefinition.defaultValue.equals("null")) { sb.append("This option can be set to 'null' to clear the default value. "); } } else if (!optionDefinition.isCollection) { sb.append("Required. "); } Object[] enumConstants = getUnderlyingType(optionDefinition.field).getEnumConstants(); if (enumConstants == null && getUnderlyingType(optionDefinition.field) == Boolean.class) { enumConstants = TRUE_FALSE_VALUES; } if (enumConstants != null) { final Boolean isClpEnum = enumConstants.length > 0 && (enumConstants[0] instanceof ClpEnum); sb.append("Possible values: {"); if (isClpEnum) sb.append("\n"); for (int i = 0; i < enumConstants.length; ++i) { if (i > 0 && !isClpEnum) { sb.append(", "); } sb.append(enumConstants[i].toString()); if (isClpEnum) { sb.append(" (").append(((ClpEnum) enumConstants[i]).getHelpDoc()).append(")\n"); } } sb.append("} "); } if (optionDefinition.isCollection) { if (optionDefinition.minElements == 0) { if (optionDefinition.maxElements == Integer.MAX_VALUE) { sb.append("This option may be specified 0 or more times. "); } else { sb.append("This option must be specified no more than ").append(optionDefinition.maxElements).append( " times. "); } } else if (optionDefinition.maxElements == Integer.MAX_VALUE) { sb.append("This option must be specified at least ").append(optionDefinition.minElements).append(" times. "); } else { sb.append("This option may be specified between ").append(optionDefinition.minElements).append( " and ").append(optionDefinition.maxElements).append(" times. "); } if (!optionDefinition.defaultValue.equals("null")) { sb.append("This option can be set to 'null' to clear the default list. "); } } if (!optionDefinition.mutuallyExclusive.isEmpty()) { sb.append(" Cannot be used in conjuction with option(s)"); for (final String option : optionDefinition.mutuallyExclusive) { final OptionDefinition mutextOptionDefinition = optionMap.get(option); if (mutextOptionDefinition == null) { throw new PicardException("Invalid option definition in source code. " + option + " doesn't match any known option."); } sb.append(" ").append(mutextOptionDefinition.name); if (mutextOptionDefinition.shortName.length() > 0) { sb.append(" (").append(mutextOptionDefinition.shortName).append(")"); } } } return sb.toString(); } private void printSpaces(final PrintStream stream, final int numSpaces) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < numSpaces; ++i) { sb.append(" "); } stream.print(sb); } private void handleOptionAnnotation(final Field field) { try { field.setAccessible(true); final Option optionAnnotation = field.getAnnotation(Option.class); final boolean isCollection = isCollectionField(field); if (isCollection) { if (optionAnnotation.maxElements() == 0) { throw new CommandLineParserDefinitionException("@Option member " + field.getName() + "has maxElements = 0"); } if (optionAnnotation.minElements() > optionAnnotation.maxElements()) { throw new CommandLineParserDefinitionException("In @Option member " + field.getName() + ", minElements cannot be > maxElements"); } if (field.get(callerOptions) == null) { createCollection(field, callerOptions, "@Option"); } } if (!canBeMadeFromString(getUnderlyingType(field))) { throw new CommandLineParserDefinitionException("@Option member " + field.getName() + " must have a String ctor or be an enum"); } final OptionDefinition optionDefinition = new OptionDefinition(field, field.getName(), optionAnnotation.shortName(), optionAnnotation.doc(), optionAnnotation.optional() || (field.get(callerOptions) != null), optionAnnotation.overridable(), isCollection, optionAnnotation.minElements(), optionAnnotation.maxElements(), field.get(callerOptions), optionAnnotation.common(), optionAnnotation.mutex()); for (final String option : optionAnnotation.mutex()) { final OptionDefinition mutextOptionDef = optionMap.get(option); if (mutextOptionDef != null) { mutextOptionDef.mutuallyExclusive.add(field.getName()); } } if (!optionDefinition.overridable && optionMap.containsKey(optionDefinition.name)) { throw new CommandLineParserDefinitionException(optionDefinition.name + " has already been used."); } if (optionDefinition.shortName.length() > 0) { if (optionMap.containsKey(optionDefinition.shortName)) { if (!optionDefinition.overridable) { throw new CommandLineParserDefinitionException(optionDefinition.shortName + " has already been used"); } } else { optionMap.put(optionDefinition.shortName, optionDefinition); } } //if we are overridable and we already exist don't add again to the option defs if (!(optionDefinition.overridable && optionMap.containsKey(optionDefinition.name))) { optionDefinitions.add(optionDefinition); optionMap.put(optionDefinition.name, optionDefinition); } //we are overridable but we already exist in the map so we need to update the hidden field value else if (optionMap.containsKey(optionDefinition.name)) { field.set(this.callerOptions, optionMap.get(optionDefinition.name).field.get(callerOptions)); } } catch (final IllegalAccessException e) { throw new CommandLineParserDefinitionException(field.getName() + " must have public visibility to have @Option annotation"); } } private void handlePositionalArgumentAnnotation(final Field field) { if (positionalArguments != null) { throw new CommandLineParserDefinitionException ("@PositionalArguments cannot be used more than once in an option class."); } field.setAccessible(true); positionalArguments = field; if (!isCollectionField(field)) { throw new CommandLineParserDefinitionException("@PositionalArguments must be applied to a Collection"); } if (!canBeMadeFromString(getUnderlyingType(field))) { throw new CommandLineParserDefinitionException("@PositionalParameters member " + field.getName() + "does not have a String ctor"); } final PositionalArguments positionalArgumentsAnnotation = field.getAnnotation(PositionalArguments.class); minPositionalArguments = positionalArgumentsAnnotation.minElements(); maxPositionalArguments = positionalArgumentsAnnotation.maxElements(); if (minPositionalArguments > maxPositionalArguments) { throw new CommandLineParserDefinitionException("In @PositionalArguments, minElements cannot be > maxElements"); } try { if (field.get(callerOptions) == null) { createCollection(field, callerOptions, "@PositionalParameters"); } } catch (final IllegalAccessException e) { throw new CommandLineParserDefinitionException(field.getName() + " must have public visibility to have @PositionalParameters annotation"); } } private void handleNestedOptionsAnnotation(final Field field) { field.setAccessible(true); try { childOptionsMap.put(field.getName(), new CommandLineParser(field.get(this.callerOptions), prefixDot + field.getName())); } catch (final IllegalAccessException e) { throw new CommandLineParserDefinitionException("Should never happen.", e); } } private boolean isCollectionField(final Field field) { try { field.getType().asSubclass(Collection.class); return true; } catch (final ClassCastException e) { return false; } } private void createCollection(final Field field, final Object callerOptions, final String annotationType) throws IllegalAccessException { try { field.set(callerOptions, field.getType().newInstance()); } catch (final Exception ex) { try { field.set(callerOptions, new ArrayList()); } catch (final IllegalArgumentException e) { throw new CommandLineParserDefinitionException("In collection " + annotationType + " member " + field.getName() + " cannot be constructed or auto-initialized with ArrayList, so collection must be initialized explicitly."); } } } /** * Returns the type that each instance of the argument needs to be converted to. In * the case of primitive fields it will return the wrapper type so that String * constructors can be found. */ private Class getUnderlyingType(final Field field) { if (isCollectionField(field)) { final ParameterizedType clazz = (ParameterizedType) (field.getGenericType()); final Type[] genericTypes = clazz.getActualTypeArguments(); if (genericTypes.length != 1) { throw new CommandLineParserDefinitionException("Strange collection type for field " + field.getName()); } return (Class) genericTypes[0]; } else { final Class type = field.getType(); if (type == Byte.TYPE) return Byte.class; if (type == Short.TYPE) return Short.class; if (type == Integer.TYPE) return Integer.class; if (type == Long.TYPE) return Long.class; if (type == Float.TYPE) return Float.class; if (type == Double.TYPE) return Double.class; if (type == Boolean.TYPE) return Boolean.class; return type; } } // True if clazz is an enum, or if it has a ctor that takes a single String argument. private boolean canBeMadeFromString(final Class clazz) { if (clazz.isEnum()) { return true; } try { clazz.getConstructor(String.class); return true; } catch (final NoSuchMethodException e) { return false; } } private Object constructFromString(final Class clazz, final String s) { try { if (clazz.isEnum()) { try { return Enum.valueOf(clazz, s); } catch (final IllegalArgumentException e) { throw new CommandLineParseException("'" + s + "' is not a valid value for " + clazz.getSimpleName() + ".", e); } } final Constructor ctor = clazz.getConstructor(String.class); return ctor.newInstance(s); } catch (final NoSuchMethodException e) { // Shouldn't happen because we've checked for presence of ctor throw new CommandLineParseException("Cannot find string ctor for " + clazz.getName(), e); } catch (final InstantiationException e) { throw new CommandLineParseException("Abstract class '" + clazz.getSimpleName() + "'cannot be used for an option value type.", e); } catch (final IllegalAccessException e) { throw new CommandLineParseException("String constructor for option value type '" + clazz.getSimpleName() + "' must be public.", e); } catch (final InvocationTargetException e) { throw new CommandLineParseException("Problem constructing " + clazz.getSimpleName() + " from the string '" + s + "'.", e.getCause()); } } public String[] getArgv() { return argv; } public interface ClpEnum { String getHelpDoc(); } protected static class OptionDefinition { final Field field; final String name; final String shortName; final String doc; final boolean optional; final boolean overridable; final boolean isCollection; final int minElements; final int maxElements; final String defaultValue; final boolean isCommon; boolean hasBeenSet = false; boolean hasBeenSetFromOptionsFile = false; boolean hasBeenSetFromParent = false; final Set<String> mutuallyExclusive; private OptionDefinition(final Field field, final String name, final String shortName, final String doc, final boolean optional, final boolean overridable, boolean collection, final int minElements, final int maxElements, final Object defaultValue, final boolean isCommon, final String[] mutuallyExclusive) { this.field = field; this.name = name.toUpperCase(); this.shortName = shortName.toUpperCase(); this.doc = doc; this.optional = optional; this.overridable = overridable; isCollection = collection; this.minElements = minElements; this.maxElements = maxElements; if (defaultValue != null) { if (isCollection && ((Collection) defaultValue).isEmpty()) { //treat empty collections the same as uninitialized primitive types this.defaultValue = "null"; } else { //this is an intialized primitive type or a non-empty collection this.defaultValue = defaultValue.toString(); } } else { this.defaultValue = "null"; } this.isCommon = isCommon; this.mutuallyExclusive = new HashSet<String>(Arrays.asList(mutuallyExclusive)); } } /** * Holds a command-line argument that is destined for a child parser. Prefix has been stripped from name. */ private static class ChildOptionArg { final String name; final String value; final boolean fromFile; final boolean precedenceSet; private ChildOptionArg(final String name, final String value, final boolean fromFile, final boolean precedenceSet) { this.name = name; this.value = value; this.fromFile = fromFile; this.precedenceSet = precedenceSet; } } /** * Propagate options from parent to children as appropriate, parse command line options for * children, and then validate that children have been properly initialized. This is done recursively * for any child that itself has a child. * * @return true if parsing is successful. Writes any errors to the message stream. */ private boolean parseChildOptions() { // If callerOptions is not an instance of CommandLineProgram, then the child options are populated // when annotations are processed. if (isCommandLineProgram()) { final CommandLineProgram commandLineProgram = (CommandLineProgram) callerOptions; for (final Map.Entry<String, Object> entry : commandLineProgram.getNestedOptions().entrySet()) { if (entry.getKey().contains(".")) { throw new IllegalArgumentException("Prefix for nested options should not contain period: " + entry.getKey()); } childOptionsMap.put(entry.getKey(), new CommandLineParser(entry.getValue(), prefixDot + entry.getKey())); } } boolean retval = true; // Check for child options for which there is no parser for (final String prefix : childOptionArguments.keySet()) { if (!childOptionsMap.containsKey(prefix)) { messageStream.println("ERROR: Option prefix '" + prefix + "' is not valid."); retval = false; } } try { // Propagate options from this parser to child parsers for (final OptionDefinition optionDefinition : optionDefinitions) { // Handling collection value propagation is confusing, so just don't do it. if (optionDefinition.isCollection) continue; final Object value = optionDefinition.field.get(callerOptions); if (value == null) continue; for (final CommandLineParser childParser : childOptionsMap.values()) { maybePropagateValueToChild(childParser, optionDefinition, value); } } } catch (final IllegalAccessException e) { throw new RuntimeException("Should never happen", e); } for (final Map.Entry<String, CommandLineParser> entry : childOptionsMap.entrySet()) { final String prefix = entry.getKey(); final CommandLineParser childParser = entry.getValue(); childParser.messageStream = this.messageStream; final Collection<ChildOptionArg> childOptionArgs = this.childOptionArguments.get(prefix); if (childOptionArgs != null) { for (final ChildOptionArg arg : childOptionArgs) { childParser.parseOption(arg.name, arg.value, arg.fromFile, arg.precedenceSet); } } if (!childParser.checkNumArguments()) { retval = false; } if (!childParser.parseChildOptions()) { retval = false; } this.commandLine += " " + childParser.getCommandLine(); } return retval; } /** * Propagate value from parent to child if appropriate to do so. */ private void maybePropagateValueToChild(final CommandLineParser childParser, final OptionDefinition optionDefinition, final Object value) { try { final OptionDefinition childOptionDefinition = childParser.optionMap.get(optionDefinition.name); if (childOptionDefinition != null) { final Object childValue = childOptionDefinition.field.get(childParser.callerOptions); if (childValue == null || optionDefinition.hasBeenSet) { childOptionDefinition.field.set(childParser.callerOptions, value); childOptionDefinition.hasBeenSetFromParent = true; childOptionDefinition.hasBeenSetFromOptionsFile = optionDefinition.hasBeenSetFromOptionsFile; } } } catch (final IllegalAccessException e) { throw new RuntimeException("Should never happen", e); } } /** * The commandline used to run this program, including any default args that * weren't necessarily specified. This is used for logging and debugging. * <p/> * NOTE: {@link #parseOptions(PrintStream, String[])} must be called before * calling this method. * * @return The commandline, or null if {@link #parseOptions(PrintStream, String[])} * hasn't yet been called, or didn't complete successfully. */ public String getCommandLine() { return commandLine; } /** * This method is only needed when calling one of the public methods that doesn't take a messageStream argument. */ public void setMessageStream(final PrintStream messageStream) { this.messageStream = messageStream; } public Object getCallerOptions() { return callerOptions; } }
package jlo.model.component; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import org.rejuse.association.Association; import org.rejuse.predicate.TypePredicate; import chameleon.core.declaration.Declaration; import chameleon.core.declaration.Signature; import chameleon.core.declaration.SimpleNameSignature; import chameleon.core.element.Element; import chameleon.core.lookup.Collector; import chameleon.core.lookup.DeclarationCollector; import chameleon.core.lookup.DeclarationContainerSkipper; import chameleon.core.lookup.DeclarationSelector; import chameleon.core.lookup.LocalLookupStrategy; import chameleon.core.lookup.LookupException; import chameleon.core.lookup.LookupStrategy; import chameleon.core.lookup.Skipper; import chameleon.core.lookup.Stub; import chameleon.core.validation.BasicProblem; import chameleon.core.validation.Valid; import chameleon.core.validation.VerificationResult; import chameleon.exception.ChameleonProgrammerException; import chameleon.oo.member.HidesRelation; import chameleon.oo.member.Member; import chameleon.oo.member.MemberImpl; import chameleon.oo.member.MemberRelationSelector; import chameleon.oo.member.OverridesRelation; import chameleon.oo.type.ClassBody; import chameleon.oo.type.DeclarationWithType; import chameleon.oo.type.RegularType; import chameleon.oo.type.Type; import chameleon.oo.type.TypeReference; import chameleon.oo.type.TypeWithBody; import chameleon.oo.type.inheritance.InheritanceRelation; import chameleon.util.Util; import chameleon.util.association.Single; public class ComponentRelation extends MemberImpl implements DeclarationWithType, InheritanceRelation { // private CreationStackTrace _trace; @Override public void disconnect() { super.disconnect(); } public ComponentRelation(SimpleNameSignature signature, TypeReference type) { setSignature(signature); setComponentType(type); setBody(new ClassBody()); // _trace = new CreationStackTrace(); // parentLink().addListener(new AssociationListener() { // @Override // public void notifyElementAdded(Object element) { // ComponentRelation.this._trace = new CreationStackTrace(); // @Override // public void notifyElementRemoved(Object element) { // ComponentRelation.this._trace = new CreationStackTrace(); // @Override // public void notifyElementReplaced(Object oldElement, Object newElement) { // ComponentRelation.this._trace = new CreationStackTrace(); } @Override public ComponentRelation clone() { ComponentRelation result = new ComponentRelation(signature().clone(), componentTypeReference().clone()); ConfigurationBlock configurationBlock = configurationBlock(); if(configurationBlock != null) { result.setConfigurationBlock(configurationBlock.clone()); } ComponentType t = componentTypeDeclaration(); if(t != null) { result.setComponentTypeDeclaration(t.clone()); } return result; } public String toString() { try { try { return componentType().toString(); } catch (LookupException e) { return signature().name(); } } catch(NullPointerException exc) { return ""; } } @Override public VerificationResult verifySelf() { VerificationResult result = Valid.create(); Set<? extends Member> overriddenMembers = null; try { overriddenMembers = overriddenMembers(); } catch(LookupException exc) { result = result.and(new BasicProblem(this, "Cannot determine the (possibly empty) set of subobjects that are refined by this subobject.")); } Type reftype = null; try { reftype = referencedComponentType(); } catch(LookupException exc) { result = result.and(new BasicProblem(this, "Cannot determine the subobject type.")); } if(overriddenMembers != null) { for(Member rel: overriddenMembers) { ComponentRelation overridden = (ComponentRelation) rel; if(reftype != null) { Type overriddenRefType = null; try { overriddenRefType = overridden.referencedComponentType(); } catch(LookupException exc) { result = result.and(new BasicProblem(this, "Cannot determine the type of refined subobject "+overridden.toString())); } if(overriddenRefType != null) { result = result.and(reftype.verifySubtypeOf(overriddenRefType,"the declared subobject type","the declared subobject type of refined subobject "+overridden.toString())); } } } if(overriddenMembers.isEmpty() && componentTypeReference() == null) { result = result.and(new BasicProblem(this, "This subobject does not refine any subobjects and has no explicitly declared subobject type.")); } } return result; } @Override public LookupStrategy lexicalLookupStrategy(Element child) throws LookupException { LookupStrategy result = parent().lexicalLookupStrategy(this); result = new ComponentTypeLookupStrategy(result, nearestAncestor(Type.class)); return result; } //PAPER: customize lookup public static class ComponentTypeLookupStrategy extends LookupStrategy { public ComponentTypeLookupStrategy(LookupStrategy parentStrategy, Type type) { _parentStrategy = parentStrategy; _type = type; } private Type _type; // @Override // public <D extends Declaration> void lookUp(DeclarationCollector<D> selector) throws LookupException { // _parentStrategy.lookUp(new DeclarationContainerSkipper<D>(selector, _type)); private LookupStrategy _parentStrategy; @Override public <D extends Declaration> void lookUp(Collector<D> collector) throws LookupException { DeclarationSelector<D> selector = collector.selector(); DeclarationSelector<D> skipper = new Skipper<D>(selector, _type); collector.setSelector(skipper); _parentStrategy.lookUp(collector); collector.setSelector(selector); // _parentStrategy.lookUp(new DeclarationContainerSkipper<D>(collector, _type)); } } @Override public List<? extends Member> declaredMembers() { return Util.<Member>createSingletonList(this); } private Single<TypeReference> _typeReference = new Single<TypeReference>(this); public TypeReference componentTypeReference() { return _typeReference.getOtherEnd(); } public TypeReference superClassReference() { return componentTypeReference(); } public Type referencedComponentType() throws LookupException { return componentTypeReference().getElement(); } public ComponentType componentType() throws LookupException { ComponentType result = componentTypeDeclaration(); // if(result == null) { // result = referencedComponentType(); return result; } public void setComponentType(TypeReference type) { set(_typeReference,type); } public void setName(String name) { setSignature(new SimpleNameSignature(name)); } public void setSignature(Signature signature) { if(signature instanceof SimpleNameSignature || signature == null) { set(_signature,(SimpleNameSignature)signature); } else { throw new ChameleonProgrammerException("Setting wrong type of signature. Provided: "+(signature == null ? null :signature.getClass().getName())+" Expected SimpleNameSignature"); } } /** * Return the signature of this member. */ public SimpleNameSignature signature() { return _signature.getOtherEnd(); } private Single<SimpleNameSignature> _signature = new Single<SimpleNameSignature>(this); public void setConfigurationBlock(ConfigurationBlock configurationBlock) { set(_configurationBlock, configurationBlock); } /** * Return the ConfigurationBlock of this member. */ public ConfigurationBlock configurationBlock() { return _configurationBlock.getOtherEnd(); } public List<ConfigurationClause> clauses() throws LookupException { List<ConfigurationClause> result; ConfigurationBlock block = configurationBlock(); if(block == null) { result = new ArrayList<ConfigurationClause>(); } else { result = block.clauses(); } Set<ComponentRelation> overridden = (Set<ComponentRelation>) overriddenMembers(); for(ComponentRelation relation: overridden) { result.addAll(relation.configurationBlock().clauses()); } return result; } private Single<ConfigurationBlock> _configurationBlock = new Single<ConfigurationBlock>(this); public LocalLookupStrategy<?> targetContext() throws LookupException { return componentType().targetContext(); } public Type declarationType() throws LookupException { return componentType(); } public boolean complete() { return true; } public Declaration declarator() { return this; } private Single<ComponentType> _componentType = new Single<ComponentType>(this); /** * Set the body of this component relation. */ public void setBody(ClassBody body) { if(body == null) { _componentType.connectTo((Association)createComponentType(new ClassBody()).parentLink()); } else { _componentType.connectTo((Association) createComponentType(body).parentLink()); } } private TypeWithBody createComponentType(ClassBody body) { RegularType anon = new ComponentType(); anon.setBody(body); return anon; } public ComponentType componentTypeDeclaration() { return _componentType.getOtherEnd(); } private void setComponentTypeDeclaration(ComponentType componentType) { if(componentType == null) { _componentType.connectTo(null); } else { _componentType.connectTo((Association) componentType.parentLink()); } } @Override public Type superElement() throws LookupException { return referencedComponentType(); } @Override public <X extends Member> void accumulateInheritedMembers(Class<X> kind, List<X> current) throws LookupException { ConfigurationBlock configurationBlock = configurationBlock(); if(configurationBlock != null) { List<Member> members = configurationBlock.processedMembers(); new TypePredicate(kind).filter(members); current.addAll((Collection<? extends X>) members); } List<Member> members = componentType().processedMembers(); new TypePredicate(kind).filter(members); current.addAll((Collection<? extends X>) members); } @Override public <X extends Member> void accumulateInheritedMembers(DeclarationSelector<X> selector, List<X> current) throws LookupException { ConfigurationBlock configurationBlock = configurationBlock(); final List<X> potential = selector.selection(componentType().processedMembers()); if(configurationBlock != null) { potential.addAll(selector.selection(configurationBlock.processedMembers())); } removeNonMostSpecificMembers(current, potential); } protected <M extends Member> void removeNonMostSpecificMembers(List<M> current, final List<M> potential) throws LookupException { final List<M> toAdd = new ArrayList<M>(); for(M m: potential) { boolean add = true; Iterator<M> iterCurrent = current.iterator(); while(add && iterCurrent.hasNext()) { M alreadyInherited = iterCurrent.next(); // Remove the already inherited member if potentially inherited member m overrides or hides it. if((alreadyInherited.sameAs(m) || alreadyInherited.overrides(m) || alreadyInherited.canImplement(m) || alreadyInherited.hides(m))) { add = false; } else if((!alreadyInherited.sameAs(m)) && (m.overrides(alreadyInherited) || m.canImplement(alreadyInherited) || m.hides(alreadyInherited))) { iterCurrent.remove(); } } if(add == true) { toAdd.add(m); } } current.addAll(toAdd); } public List<? extends Member> getIntroducedMembers() throws LookupException { List<Member> result = new ArrayList<Member>(); result.add(this); return result; } public List<? extends Member> exportedMembers() throws LookupException { return componentType().processedMembers(); } @Override public <D extends Member> List<D> membersDirectlyOverriddenBy(MemberRelationSelector<D> selector) throws LookupException { ConfigurationBlock configurationBlock = configurationBlock(); List<D> result = new ArrayList<D>(); if(selector.declaration() != this) { if(configurationBlock != null) { result = configurationBlock.membersDirectlyOverriddenBy(selector); } for(Export member: componentType().directlyDeclaredElements(Export.class)) { result.addAll(member.membersDirectlyOverriddenBy(selector)); } } return result; } @Override public <D extends Member> List<D> membersDirectlyAliasedBy(MemberRelationSelector<D> selector) throws LookupException { ConfigurationBlock configurationBlock = configurationBlock(); List<D> result = new ArrayList<D>(); if(configurationBlock != null) { result = configurationBlock.membersDirectlyAliasedBy(selector); } for(Export member: componentType().directlyDeclaredElements(Export.class)) { result.addAll(member.membersDirectlyAliasedBy(selector)); } return result; } public <D extends Member> List<D> membersDirectlyAliasing(MemberRelationSelector<D> selector) throws LookupException { ConfigurationBlock configurationBlock = configurationBlock(); List<D> result = new ArrayList<D>(); if(configurationBlock != null) { result = configurationBlock.membersDirectlyAliasing(selector); } for(Export member: componentType().directlyDeclaredElements(Export.class)) { result.addAll(member.membersDirectlyAliasing(selector)); } return result; } /** * Return a clone of the given member that is 'incorporated' into the component type of this component * relation. The parent of the result is a ComponentStub that is unidirectionally connected to the * component type, and whose generator is set to this. * * @param toBeIncorporated * The member that must be incorporated into the component type. */ /*@ @ public behavior @ @ pre toBeIncorporated != null; @ @ post \result != null; @ post \result == toBeIncorporated.clone(); @ post \result.parent() instanceof ComponentStub; @ post ((ComponentStub)\result.parent()).parent() == componentType(); @ post ((ComponentStub)\result.parent()).generator() == this; @*/ public <M extends Member> M incorporatedIntoComponentType(M toBeIncorporated) throws LookupException { return incorporatedInto(toBeIncorporated, componentType()); } /** * Return a clone of the given member that is 'incorporated' into the type containing this component * relation. The parent of the result is a ComponentStub that is unidirectionally connected to the * containing type, and whose generator is set to this. * * @param toBeIncorporated * The member that must be incorporated into the containing type. */ /*@ @ public behavior @ @ pre toBeIncorporated != null; @ @ post \result != null; @ post \result == toBeIncorporated.clone(); @ post \result.parent() instanceof ComponentStub; @ post ((ComponentStub)\result.parent()).parent() == nearestAncestor(Type.class); @ post ((ComponentStub)\result.parent()).generator() == this; @*/ public <M extends Member> M incorporatedIntoContainerType(M toBeIncorporated) throws LookupException { return incorporatedInto(toBeIncorporated, nearestAncestor(Type.class)); } /** * Return a clone of the given member that is 'incorporated' into the given type. * The parent of the result is a ComponentStub that is unidirectionally connected to the * given type, and whose generator is set to this. * * @param toBeIncorporated * The member that must be incorporated into the containing type. */ /*@ @ public behavior @ @ pre toBeIncorporated != null; @ @ post \result != null; @ post \result == toBeIncorporated.clone(); @ post \result.parent() instanceof ComponentStub; @ post ((ComponentStub)\result.parent()).parent() == type; @ post ((ComponentStub)\result.parent()).generator() == this; @*/ protected <M extends Member> M incorporatedInto(M toBeIncorporated, Type incorporatingType) throws LookupException { M result = (M) toBeIncorporated.clone(); result.setOrigin(toBeIncorporated); Stub redirector = new ComponentStub(this, result); redirector.setUniParent(incorporatingType); return result; } // public String toString() { // Type nearestAncestor = nearestAncestor(Type.class); // return (nearestAncestor != null ? nearestAncestor.getFullyQualifiedName() + "." + signature().name() : signature().name()); public MemberRelationSelector<ComponentRelation> overridesSelector() { return new MemberRelationSelector<ComponentRelation>(ComponentRelation.class,this,_overridesSelector); } public OverridesRelation<? extends ComponentRelation> overridesRelation() { return _overridesSelector; } private static OverridesRelation<ComponentRelation> _overridesSelector = new OverridesRelation<ComponentRelation>(ComponentRelation.class) { @Override public boolean containsBasedOnRest(ComponentRelation first, ComponentRelation second) throws LookupException { return true; } @Override public boolean containsBasedOnName(Signature first, Signature second) throws LookupException { return first.sameAs(second); } }; public HidesRelation<? extends ComponentRelation> hidesRelation() { return _hidesSelector; } private static HidesRelation<ComponentRelation> _hidesSelector = new HidesRelation<ComponentRelation>(ComponentRelation.class) { public boolean containsBasedOnRest(ComponentRelation first, ComponentRelation second) throws LookupException { return true; } }; public List<Type> typesOfOverriddenSubobjects() throws LookupException { Set<ComponentRelation> superSubobjectRelations = (Set)overriddenMembers(); List<Type> result = new ArrayList<Type>(); for(ComponentRelation superSubobjectRelation: superSubobjectRelations) { result.add(superSubobjectRelation.componentType()); } return result; } @Override public Type superType() throws LookupException { return null; } }
package org.apache.juddi.v3.client.embed; import java.lang.reflect.Method; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.juddi.v3.client.ClassUtil; public class JUDDIRegistry implements EmbeddedRegistry { private Log logger = LogFactory.getLog(this.getClass()); public void start() { try { Class<?> juddiRegistry = ClassUtil.forName("org.apache.juddi.Registry", JUDDIRegistry.class); Method startMethod = juddiRegistry.getDeclaredMethod("start"); startMethod.invoke(juddiRegistry); } catch (Exception e) { logger.error(e.getMessage(),e); } } public void stop() { try { Class<?> juddiRegistry = ClassUtil.forName("org.apache.juddi.Registry", JUDDIRegistry.class); Method stopMethod = juddiRegistry.getDeclaredMethod("stop"); stopMethod.invoke(juddiRegistry); } catch (Exception e) { logger.error(e.getMessage(),e); } } }
package com.fsck.k9.mail.transport; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.AuthType; import com.fsck.k9.mail.ConnectionSecurity; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.ServerSettings; import com.fsck.k9.mail.filter.Base64; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.ssl.TrustedSocketFactory; import com.fsck.k9.mail.store.StoreConfig; import com.fsck.k9.mail.transport.mockServer.MockSmtpServer; import com.fsck.k9.mail.transport.mockServer.TestMessage; import com.fsck.k9.testHelpers.TestTrustedSocketFactory; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE, sdk = 21) public class SmtpTransportTest { private String host; private int port; private ConnectionSecurity connectionSecurity; private AuthType authenticationType; private String username; private String password; private String clientCertificateAlias; private List<String> extensions; private StoreConfig storeConfig = mock(StoreConfig.class); private TrustedSocketFactory socketFactory; @Before public void before() { socketFactory = new TestTrustedSocketFactory(); resetConnectionParameters(); } private void resetConnectionParameters() { host = null; port = -1; username = null; password = null; authenticationType = null; clientCertificateAlias = null; connectionSecurity = null; extensions = new ArrayList<>(); } private SmtpTransport startServerAndCreateSmtpTransport(MockSmtpServer server) throws IOException, MessagingException { server.start(); host = server.getHost(); port = server.getPort(); String uri = SmtpTransport.createUri(new ServerSettings( ServerSettings.Type.SMTP, host, port, connectionSecurity, authenticationType, username, password, clientCertificateAlias)); when(storeConfig.getTransportUri()).thenReturn(uri); return createSmtpTransport(storeConfig, socketFactory); } private SmtpTransport createSmtpTransport( StoreConfig storeConfig, TrustedSocketFactory socketFactory) throws MessagingException { return new SmtpTransport(storeConfig, socketFactory); } private void setupConnectAndPlainAuthentication(MockSmtpServer server) { username = "user"; password = "password"; authenticationType = AuthType.PLAIN; connectionSecurity = ConnectionSecurity.NONE; server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250-SIZE 1000000"); for (String extension: extensions) { server.output("250-"+extension); } server.output("250 AUTH LOGIN PLAIN CRAM-MD5"); server.expect("AUTH PLAIN AHVzZXIAcGFzc3dvcmQ="); server.output("235 2.7.0 Authentication successful"); } @Test public void SmtpTransport_withValidUri_canBeCreated() throws MessagingException { StoreConfig storeConfig = mock(StoreConfig.class); when(storeConfig.getTransportUri()).thenReturn( "smtp://user:password:CRAM_MD5@server:123456"); TrustedSocketFactory trustedSocketFactory = mock(TrustedSocketFactory.class); new SmtpTransport(storeConfig, trustedSocketFactory); } @Test(expected = MessagingException.class) public void SmtpTransport_withInvalidUri_throwsMessagingException() throws MessagingException { StoreConfig storeConfig = mock(StoreConfig.class); when(storeConfig.getTransportUri()).thenReturn("smpt: TrustedSocketFactory trustedSocketFactory = mock(TrustedSocketFactory.class); new SmtpTransport(storeConfig, trustedSocketFactory); } @Test public void open_withNoSecurityPlainAuth_connectsToServer() throws MessagingException, IOException, InterruptedException { username = "user"; password = "password"; authenticationType = AuthType.PLAIN; connectionSecurity = ConnectionSecurity.NONE; MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250-SIZE 1000000"); server.output("250 AUTH LOGIN PLAIN CRAM-MD5"); server.expect("AUTH PLAIN AHVzZXIAcGFzc3dvcmQ="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_withNoSecurityCramMd5Auth_connectsToServer() throws MessagingException, IOException, InterruptedException { username = "user"; password = "password"; authenticationType = AuthType.CRAM_MD5; connectionSecurity = ConnectionSecurity.NONE; MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250-SIZE 1000000"); server.output("250 AUTH LOGIN PLAIN CRAM-MD5"); server.expect("AUTH CRAM-MD5"); server.output(Base64.encode("<24609.1047914046@localhost>")); server.expect("dXNlciA3NmYxNWEzZmYwYTNiOGI1NzcxZmNhODZlNTcyMDk2Zg=="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_withNoSecurityExternalAuth_connectsToServer() throws MessagingException, IOException, InterruptedException { username = "user"; password = "password"; authenticationType = AuthType.EXTERNAL; connectionSecurity = ConnectionSecurity.NONE; MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250-SIZE 1000000"); server.output("250 AUTH EXTERNAL"); server.expect("AUTH EXTERNAL dXNlcg=="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void sendMessage_withNoAddressToSendTo_doesntOpenConnection() throws MessagingException, IOException, InterruptedException { MimeMessage message = new MimeMessage(); MockSmtpServer server = new MockSmtpServer(); setupConnectAndPlainAuthentication(server); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.sendMessage(message); server.verifyConnectionNeverCreated(); } @Test public void sendMessage_withToAddressToSendTo_opensConnection() throws MessagingException, IOException, InterruptedException { TestMessage message = new TestMessage(); message.setFrom(new Address("user@localhost")); message.setRecipients(Message.RecipientType.TO, new Address[]{new Address("user2@localhost")}); MockSmtpServer server = new MockSmtpServer(); setupConnectAndPlainAuthentication(server); server.expect("MAIL FROM:<user@localhost>"); server.output("250 OK"); server.expect("RCPT TO:<user2@localhost>"); server.output("250 OK"); server.expect("DATA"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect(""); server.expect("."); server.output("250 OK: queued as 12345"); server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.sendMessage(message); } @Test public void sendMessage_with8BitEncoding_usesEncoding() throws MessagingException, IOException, InterruptedException { extensions.add("8BITMIME"); TestMessage message = new TestMessage(); message.setFrom(new Address("user@localhost")); message.setRecipients(Message.RecipientType.TO, new Address[]{new Address("user2@localhost")}); MockSmtpServer server = new MockSmtpServer(); setupConnectAndPlainAuthentication(server); server.expect("MAIL FROM:<user@localhost> BODY=8BITMIME"); server.output("250 OK"); server.expect("RCPT TO:<user2@localhost>"); server.output("250 OK"); server.expect("DATA"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect(""); server.expect("."); server.output("250 OK: queued as 12345"); server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.sendMessage(message); } }
package kikaha.core.modules.security; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import kikaha.config.Config; import kikaha.core.cdi.CDI; import kikaha.core.cdi.helpers.TinyList; import lombok.Getter; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; @Slf4j @Getter @Accessors( fluent = true ) public class AuthenticationRuleMatcher { final Config authConfig; final CDI provider; final SecurityContextFactory securityContextFactory; final Map<String, AuthenticationMechanism> mechanisms; final Map<String, IdentityManager> identityManagers; final List<AuthenticationRule> rules; final DefaultAuthenticationConfiguration defaultAuthenticationConfiguration; public AuthenticationRuleMatcher( final CDI provider, final Config authConfig, final DefaultAuthenticationConfiguration defaultAuthenticationConfiguration) { this.authConfig = authConfig; this.provider = provider; mechanisms = instantiateMechanismsFoundOnConfig(); identityManagers = instantiateIdentityManagersFoundOnConfig(); securityContextFactory = instantiateSecurityContextFactory( authConfig ); rules = readRulesFromConfig(); this.defaultAuthenticationConfiguration = defaultAuthenticationConfiguration; } private SecurityContextFactory instantiateSecurityContextFactory( final Config authConfig ) { final String className = authConfig.getString( "security-context-factory" ); final SecurityContextFactory factory = instantiate( className, SecurityContextFactory.class ); log.debug("Found SecurityContextFactory: " + factory); return factory; } private Map<String, AuthenticationMechanism> instantiateMechanismsFoundOnConfig() { final Map<String, Object> values = authConfig.getConfig("auth-mechanisms").toMap(); final Map<String, AuthenticationMechanism> mechanisms = convert( values, o->instantiate( (String)o, AuthenticationMechanism.class ) ); log.debug("Found Authentication Mechanisms: " + mechanisms); return mechanisms; } private Map<String, IdentityManager> instantiateIdentityManagersFoundOnConfig() { final Map<String, Object> values = authConfig.getConfig("identity-managers").toMap(); final Map<String, IdentityManager> identityManagers = convert( values, o->instantiate( (String)o, IdentityManager.class ) ); log.debug( "Found Identity Managers: " + identityManagers ); return identityManagers; } private <V,N> Map<String,N> convert( Map<String, V> original, Function<V,N> converter ) { final Map<String,N> newMap = new HashMap<>(); for ( Map.Entry<String,V> entry : original.entrySet() ) { final N converted = converter.apply( entry.getValue() ); newMap.put( entry.getKey(), converted ); } return newMap; } @SuppressWarnings({"unused", "unchecked"}) private <T> T instantiate( String className, final Class<T> targetClazz ) { try { Class<T> clazz = (Class<T>) Class.forName( className ); return provider.load( clazz ); } catch ( Throwable cause ) { throw new IllegalStateException( "Can't load " + className, cause); } } private List<AuthenticationRule> readRulesFromConfig() { return authConfig.getConfigList("rules").stream() .map(this::convertConfToRule) .collect(Collectors.toList()); } private AuthenticationRule convertConfToRule( final Config ruleConf ) { final List<String> defaultIdentityManagersAndAuthMechanisms = Collections.singletonList("default"); final List<String> defaultExcludedPatterns = authConfig.getStringList("default-excluded-patterns"); final List<IdentityManager> identityManagers = getIdentityManagerFor( ruleConf, defaultIdentityManagersAndAuthMechanisms ); log.warn("identityManagers="+identityManagers); final List<AuthenticationMechanism> mechanisms = extractNeededMechanisms( ruleConf.getStringList("auth-mechanisms", defaultIdentityManagersAndAuthMechanisms) ); return new AuthenticationRule( ruleConf.getString( "pattern" ), identityManagers, mechanisms, ruleConf.getStringList( "expected-roles", Collections.emptyList() ), ruleConf.getStringList( "exclude-patterns", defaultExcludedPatterns ) ); } private List<IdentityManager> getIdentityManagerFor( Config ruleConf, List<String> defaultIdentityManagersAndAuthMechanisms ) { List<String> identityManagers = ruleConf.getStringList("identity-manager"); if ( identityManagers != null && !identityManagers.isEmpty() ) { log.warn("The 'identity-manager' entry is deprecated."); log.warn("Consider use 'identity-managers'."); } else identityManagers = ruleConf.getStringList("identity-managers", defaultIdentityManagersAndAuthMechanisms ); return getIdentityManagerFor( identityManagers ); } private List<IdentityManager> getIdentityManagerFor( final List<String> identityManagers ) { final List<IdentityManager> ims = new TinyList<>(); for ( final String name : identityManagers ){ final IdentityManager identityManager = identityManagers().get( name ); if ( identityManager == null ) throw new IllegalArgumentException("No IdentityManager registered for " + name ); ims.add( identityManager ); } return ims; } private List<AuthenticationMechanism> extractNeededMechanisms( final List<String> authMechanisms ) { return authMechanisms.stream() .map(mechanism -> mechanisms().get(mechanism)) .collect(Collectors.toList()); } public AuthenticationRule retrieveAuthenticationRuleForUrl( final String url ) { for ( final AuthenticationRule rule : rules ) if ( rule.matches( url ) ) return rule; return null; } }
package org.jetbrains.kotlin.ui.launch; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationType; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.debug.ui.ILaunchShortcut; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.plugin.JetFileType; import org.jetbrains.kotlin.core.builder.KotlinPsiManager; import org.jetbrains.kotlin.core.log.KotlinLogger; import org.jetbrains.kotlin.core.utils.ProjectUtils; import org.jetbrains.kotlin.ui.editors.KotlinEditor; public class KotlinLaunchShortcut implements ILaunchShortcut { private static final String launchConfigurationTypeId = "org.jetbrains.kotlin.core.launch.launchConfigurationType"; @Override public void launch(ISelection selection, String mode) { if (!(selection instanceof IStructuredSelection)) { return; } IStructuredSelection structuredSelection = (IStructuredSelection) selection; List<IFile> files = new ArrayList<IFile>(); for (Object object : structuredSelection.toList()) { if (object instanceof IAdaptable) { IResource resource = (IResource) ((IAdaptable) object).getAdapter(IResource.class); addFiles(files, resource); } } IFile mainClass = ProjectUtils.getMainClass(files); if (mainClass == null) { launchProject(files.get(0).getProject(), mode); return; } launchWithMainClass(mainClass, mode); } @Override public void launch(IEditorPart editor, String mode) { if (editor instanceof KotlinEditor) { IEditorInput editorInput = editor.getEditorInput(); if (!(editorInput instanceof IFileEditorInput)) { return; } IFile file = ((IFileEditorInput) editorInput).getFile(); if (ProjectUtils.hasMain(file)) { launchWithMainClass(file, mode); return; } launchProject(file.getProject(), mode); } } private void launchProject(IProject project, String mode) { IFile mainClass = ProjectUtils.getMainClass(KotlinPsiManager.INSTANCE.getFilesByProject(project)); if (mainClass != null) { launchWithMainClass(mainClass, mode); } } private void launchWithMainClass(IFile mainClass, String mode) { ILaunchConfiguration configuration = findLaunchConfiguration(getLaunchConfigurationType(), mainClass); if (configuration == null) { configuration = createConfiguration(mainClass); } if (configuration == null) { return; } DebugUITools.launch(configuration, mode); } public static ILaunchConfiguration createConfiguration(IFile file) { ILaunchConfiguration configuration = null; ILaunchConfigurationWorkingCopy configWC = null; ILaunchConfigurationType configurationType = getLaunchConfigurationType(); try { configWC = configurationType.newInstance(null, "Config - " + file.getName()); configWC.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, ProjectUtils.createPackageClassName(file).toString()); configWC.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, file.getProject().getName()); configuration = configWC.doSave(); } catch (CoreException e) { KotlinLogger.logAndThrow(e); } return configuration; } @Nullable private ILaunchConfiguration findLaunchConfiguration(ILaunchConfigurationType configurationType, IFile mainClass) { try { ILaunchConfiguration[] configs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(configurationType); String mainClassName = ProjectUtils.createPackageClassName(mainClass).toString(); for (ILaunchConfiguration config : configs) { if (config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, (String)null).equals(mainClassName) && config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String)null).equals(mainClass.getProject().getName())) { return config; } } } catch (CoreException e) { KotlinLogger.logAndThrow(e); } return null; } private void addFiles(List<IFile> files, IResource resource) { switch (resource.getType()) { case IResource.FILE: IFile file = (IFile) resource; if (resource.getFileExtension().equals(JetFileType.INSTANCE.getDefaultExtension())) { files.add(file); } break; case IResource.FOLDER: case IResource.PROJECT: IContainer container = (IContainer) resource; try { for (IResource child : container.members()) { addFiles(files, child); } } catch (CoreException e) { KotlinLogger.logAndThrow(e); } break; } } private static ILaunchConfigurationType getLaunchConfigurationType() { return DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(launchConfigurationTypeId); } }
package org.sagebionetworks.repo.model.jdo; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import org.sagebionetworks.repo.model.DatastoreException; /** * This particular implementation of KeyFactory expects string keys from the * model layer and numeric keys in the persistence layer. It is similar to * com.google.appengine.api.datastore.KeyFactory. * * @author deflaux * */ public class KeyFactory { /** * Synapse keys sent to the repo svc may be optionally prefixed with this * string. All keys leaving the repo svc should have this prefix. */ public static final String SYNAPSE_ID_PREFIX = "syn"; /** * Converts a Long into a websafe string. * * @param key * @return a web-safe string representation of a key */ public static String keyToString(Long key) { if (key==null) return null; return SYNAPSE_ID_PREFIX + key.toString(); } /** * Converts a String-representation of a Long into the Long instance it * represents. * * @param id * @return the decoded key * @throws DatastoreException */ public static Long stringToKey(String id) throws DatastoreException { try { String decodedId = URLDecoder.decode(id, "UTF-8").trim().toLowerCase(); if (decodedId.startsWith(SYNAPSE_ID_PREFIX)) { decodedId = decodedId.substring(SYNAPSE_ID_PREFIX.length()); } return new Long(decodedId); } catch (NumberFormatException e) { throw new DatastoreException(e); } catch (UnsupportedEncodingException e) { throw new DatastoreException(e); } } }
package org.sagebionetworks.logging; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.aspectj.lang.reflect.MethodSignature; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; public class SynapseLoggingUtils { private static final Pattern DATE_PATTERN = Pattern.compile("^(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3})"); private static final Pattern LEVEL_PATTERN = Pattern.compile(" \\[\\w+\\] - | \\w+ \\[ *[-\\w]+ *\\] \\[ *[.\\w]+ *\\] - "); private static final Pattern CONTROLLER_METHOD_PATTERN = Pattern.compile("(\\w+)/(\\w+)"); private static final Pattern PROPERTIES_PATTERN = Pattern.compile("\\?((?:\\w+=[\\w%.\\-*_+]+&?)+)$"); public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss,SSS").withZone(DateTimeZone.UTC); public static SynapseEvent parseSynapseEvent(String line) throws UnsupportedEncodingException { int lastEnd = 0; DateTime timeStamp; Matcher dateMatcher = DATE_PATTERN.matcher(line); if (dateMatcher.find(lastEnd)) { timeStamp = DATE_FORMATTER.parseDateTime(dateMatcher.group(1)); lastEnd = dateMatcher.end(); } else { throw new IllegalArgumentException( "Pattern incorrect: failed to find a date:\n\t" + line.substring(lastEnd)); } Matcher levelMatcher = LEVEL_PATTERN.matcher(line); if (!levelMatcher.find(lastEnd)) { throw new IllegalArgumentException( "Pattern incorrect: failed to find a log-level:\n\t" + line.substring(lastEnd)); } Matcher controllerMatcher = CONTROLLER_METHOD_PATTERN.matcher(line); String controller, methodName; if (controllerMatcher.find(lastEnd)) { controller = controllerMatcher.group(1); methodName = controllerMatcher.group(2); lastEnd = controllerMatcher.end(); } else { throw new IllegalArgumentException( "Pattern incorrect: failed to find controller/method-name:\n\t" + line.substring(lastEnd)); } Matcher propMatcher = PROPERTIES_PATTERN.matcher(line); int latency; HashMap<String, String> properties; if (propMatcher.find()) { String[] propertiesArray = propMatcher.group(1).split("&"); properties = new HashMap<String, String>(); for (String property : propertiesArray) { String[] keyAndVal = property.split("=", 2); properties.put(keyAndVal[0], URLDecoder.decode(keyAndVal[1], "UTF-8")); } if (properties.containsKey("latency")) { latency = Integer.parseInt(properties.get("latency")); properties.remove("latency"); } else { latency = -1; } } else { throw new IllegalArgumentException( "Pattern incorrect: failed to find a property string:\n\t" + line.substring(lastEnd)); } return new SynapseEvent(timeStamp, controller, methodName, latency, properties); } /** * Method for returning a coherent arg string from the relevant information. * @param sig method signature from the join point * @param args list of actual arguments to be passed to the join point * @return * @throws UnsupportedEncodingException */ public static String makeArgString(MethodSignature sig, Object[] args) throws UnsupportedEncodingException { Method method = sig.getMethod(); if (method == null) { return Arrays.toString(args); } String[] parameterNames = sig.getParameterNames(); // Using LinkedHashMap makes the testing easier because we don't have to account for // the normal unreliable ordering of hashmaps Map<String, String> properties = new LinkedHashMap<String, String>(); for (int i = 0; i < args.length; i++) { properties.put(parameterNames[i], (args[i]!=null?args[i].toString():"null")); } return makeArgString(properties); } public static String makeArgString(Map<String, String> properties) throws UnsupportedEncodingException { String encoding = "UTF-8"; String argSep = ""; StringBuilder argString = new StringBuilder(); for (Entry<String, String> entry : properties.entrySet()) { argString.append(argSep); argString.append(entry.getKey()); argString.append("="); argString.append(URLEncoder.encode(entry.getValue().toString(), encoding)); // Set the argSep after the first time through so that we // separate all the pairs with it, but don't have a leading // or trailing "&" argSep = "&"; } return argString.toString(); } public static String makeLogString(String simpleClassName, String methodName, long latencyMS, String args) { return String.format("%s/%s?latency=%d&%s", simpleClassName, methodName, latencyMS, args); } public static String makeLogString(SynapseEvent event) throws UnsupportedEncodingException { return makeLogString(event.getController(), event.getMethodName(), event.getLatency(), makeArgString(event.getProperties())); } }
package com.novoda.downloadmanager.lib; import android.os.Environment; import com.novoda.downloadmanager.Download; import java.util.List; class DownloadReadyChecker { private final SystemFacade systemFacade; private final NetworkChecker networkChecker; private final DownloadClientReadyChecker downloadClientReadyChecker; private final PublicFacingDownloadMarshaller downloadMarshaller; DownloadReadyChecker(SystemFacade systemFacade, NetworkChecker networkChecker, DownloadClientReadyChecker downloadClientReadyChecker, PublicFacingDownloadMarshaller downloadMarshaller) { this.systemFacade = systemFacade; this.networkChecker = networkChecker; this.downloadClientReadyChecker = downloadClientReadyChecker; this.downloadMarshaller = downloadMarshaller; } public boolean canDownload(DownloadBatch downloadBatch) { if (isDownloadManagerReadyToDownload(downloadBatch)) { Download download = downloadMarshaller.marshall(downloadBatch); return downloadClientReadyChecker.isAllowedToDownload(download); } return false; } private boolean isDownloadManagerReadyToDownload(DownloadBatch downloadBatch) { List<FileDownloadInfo> downloads = downloadBatch.getDownloads(); if (isThereAPausedDownload(downloads)) { return false; } switch (downloadBatch.getStatus()) { case 0: // status hasn't been initialized yet, this is a new download case DownloadStatus.QUEUED_DUE_CLIENT_RESTRICTIONS: case DownloadStatus.SUBMITTED: case DownloadStatus.PENDING: // download is explicit marked as ready to start case DownloadStatus.RUNNING: // download interrupted (process killed etc) while // running, without a chance to update the database return true; case DownloadStatus.WAITING_FOR_NETWORK: case DownloadStatus.QUEUED_FOR_WIFI: return isThereADownloadThatCanUseNetwork(downloads); case DownloadStatus.WAITING_TO_RETRY: // download was waiting for a delayed restart long now = systemFacade.currentTimeMillis(); return isThereARetryDownloadThatCanRestart(downloads, now); case DownloadStatus.DEVICE_NOT_FOUND_ERROR: // is the media mounted? return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); case DownloadStatus.INSUFFICIENT_SPACE_ERROR: // avoids repetition of retrying download return false; default: return false; } } private boolean isThereAPausedDownload(List<FileDownloadInfo> downloadBatch) { for (FileDownloadInfo download : downloadBatch) { if (download.getControl() == DownloadsControl.CONTROL_PAUSED) { return true; } } return false; } private boolean isThereADownloadThatCanUseNetwork(List<FileDownloadInfo> downloadBatch) { for (FileDownloadInfo download : downloadBatch) { if (networkChecker.checkCanUseNetwork(download) == FileDownloadInfo.NetworkState.OK) { return true; } } return false; } private boolean isThereARetryDownloadThatCanRestart(List<FileDownloadInfo> downloadBatch, long now) { for (FileDownloadInfo download : downloadBatch) { if (download.restartTime(now) <= now) { return true; } } return false; } }
package com.salesforce.androidsdk; import android.content.Context; import com.salesforce.androidsdk.rest.ApiVersionStrings; import com.salesforce.androidsdk.tests.R; /** * Authentication credentials used to make live server calls in tests * * Use web app to figure out login/instance urls, orgId, userId, username and clientId * * For refresh token, edit RestClient.java toString() to print out refresh token and use "print info" button in RestExplorer. * Attaching a debugger to the RestExplorer and having a break point in RestClient.java toString() is probably the easiest way to go. */ public class TestCredentials { public static String API_VERSION; public static String ACCOUNT_TYPE; public static String ORG_ID; public static String USERNAME; public static String ACCOUNT_NAME; public static String USER_ID; public static String LOGIN_URL; public static String INSTANCE_URL; public static String COMMUNITY_URL; public static String IDENTITY_URL; public static String CLIENT_ID; public static String REFRESH_TOKEN; public static void init(Context ctx) { API_VERSION = ApiVersionStrings.getVersionNumber(ctx); ACCOUNT_TYPE = ctx.getString(R.string.account_type); ORG_ID = ctx.getString(R.string.org_id); USERNAME = ctx.getString(R.string.username); ACCOUNT_NAME = ctx.getString(R.string.account_name); USER_ID = ctx.getString(R.string.user_id); LOGIN_URL = ctx.getString(R.string.login_url); INSTANCE_URL = ctx.getString(R.string.instance_url); COMMUNITY_URL = ctx.getString(R.string.community_url); IDENTITY_URL = ctx.getString(R.string.identity_url); CLIENT_ID = ctx.getString(R.string.remoteAccessConsumerKey); REFRESH_TOKEN = ctx.getString(R.string.oauth_refresh_token); } }
/* @java.file.header */ package org.gridgain.grid.kernal; import org.gridgain.grid.*; import org.gridgain.grid.compute.*; import org.gridgain.grid.events.*; import org.gridgain.grid.lang.*; import org.gridgain.grid.messaging.*; import org.gridgain.grid.service.*; import org.gridgain.grid.util.typedef.*; import org.gridgain.grid.util.typedef.internal.*; import org.jetbrains.annotations.*; import java.io.*; import java.util.*; import static org.gridgain.grid.kernal.GridNodeAttributes.*; public class GridProjectionAdapter implements GridProjectionEx, Externalizable { private static final long serialVersionUID = 0L; /** Kernal context. */ protected transient GridKernalContext ctx; /** Parent projection. */ private transient GridProjection parent; /** Compute. */ private transient GridComputeImpl compute; /** Messaging. */ private transient GridMessagingImpl messaging; /** Events. */ private transient GridEvents evts; /** Services. */ private transient GridServices svcs; /** Grid name. */ private String gridName; /** Subject ID. */ private UUID subjId; /** Projection predicate. */ protected GridPredicate<GridNode> p; /** Node IDs. */ private Set<UUID> ids; /** * Required by {@link Externalizable}. */ public GridProjectionAdapter() { // No-op. } /** * @param parent Parent of this projection. * @param ctx Grid kernal context. * @param p Predicate. */ protected GridProjectionAdapter(@Nullable GridProjection parent, @Nullable GridKernalContext ctx, @Nullable UUID subjId, @Nullable GridPredicate<GridNode> p) { this.parent = parent; if (ctx != null) setKernalContext(ctx); this.subjId = subjId; this.p = p; ids = null; } /** * @param parent Parent of this projection. * @param ctx Grid kernal context. * @param ids Node IDs. */ protected GridProjectionAdapter(@Nullable GridProjection parent, @Nullable GridKernalContext ctx, @Nullable UUID subjId, Set<UUID> ids) { this.parent = parent; if (ctx != null) setKernalContext(ctx); assert ids != null; this.subjId = subjId; this.ids = ids; p = F.nodeForNodeIds(ids); } /** * @param parent Parent of this projection. * @param ctx Grid kernal context. * @param p Predicate. * @param ids Node IDs. */ private GridProjectionAdapter(@Nullable GridProjection parent, @Nullable GridKernalContext ctx, @Nullable UUID subjId, @Nullable GridPredicate<GridNode> p, Set<UUID> ids) { this.parent = parent; if (ctx != null) setKernalContext(ctx); this.subjId = subjId; this.p = p; this.ids = ids; if (p == null && ids != null) this.p = F.nodeForNodeIds(ids); } /** * <tt>ctx.gateway().readLock()</tt> */ protected void guard() { assert ctx != null; ctx.gateway().readLock(); } /** * <tt>ctx.gateway().readUnlock()</tt> */ protected void unguard() { assert ctx != null; ctx.gateway().readUnlock(); } /** * <tt>ctx.gateway().lightCheck()</tt> */ protected void lightCheck() { assert ctx != null; ctx.gateway().lightCheck(); } /** * Sets kernal context. * * @param ctx Kernal context to set. */ protected void setKernalContext(GridKernalContext ctx) { assert ctx != null; assert this.ctx == null; this.ctx = ctx; if (parent == null) parent = ctx.grid(); gridName = ctx.gridName(); } /** {@inheritDoc} */ @Override public final Grid grid() { assert ctx != null; guard(); try { return ctx.grid(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public final GridCompute compute() { if (compute == null) { assert ctx != null; compute = new GridComputeImpl(ctx, this, subjId); } return compute; } /** {@inheritDoc} */ @Override public final GridMessaging message() { if (messaging == null) { assert ctx != null; messaging = new GridMessagingImpl(ctx, this); } return messaging; } /** {@inheritDoc} */ @Override public final GridEvents events() { if (evts == null) { assert ctx != null; evts = new GridEventsImpl(ctx, this); } return evts; } /** {@inheritDoc} */ @Override public GridServices services() { if (svcs == null) { assert ctx != null; svcs = new GridServicesImpl(ctx, this); } return svcs; } /** {@inheritDoc} */ @Override public final GridProjectionMetrics metrics() throws GridException { guard(); try { if (nodes().isEmpty()) throw U.emptyTopologyException(); return new GridProjectionMetricsImpl(this); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<GridNode> nodes() { guard(); try { if (ids != null) { if (ids.isEmpty()) return Collections.emptyList(); else if (ids.size() == 1) { GridNode node = ctx.discovery().node(F.first(ids)); return node != null ? Collections.singleton(node) : Collections.<GridNode>emptyList(); } else { Collection<GridNode> nodes = new ArrayList<>(ids.size()); for (UUID id : ids) { GridNode node = ctx.discovery().node(id); if (node != null) nodes.add(node); } return nodes; } } else { Collection<GridNode> all = ctx.discovery().allNodes(); return p != null ? F.view(all, p) : all; } } finally { unguard(); } } /** {@inheritDoc} */ @Override public final GridNode node(UUID id) { A.notNull(id, "id"); guard(); try { if (ids != null) return ids.contains(id) ? ctx.discovery().node(id) : null; else { GridNode node = ctx.discovery().node(id); return node != null && (p == null || p.apply(node)) ? node : null; } } finally { unguard(); } } /** {@inheritDoc} */ @Override public GridNode node() { return F.first(nodes()); } /** {@inheritDoc} */ @Override public final GridPredicate<GridNode> predicate() { return p != null ? p : F.<GridNode>alwaysTrue(); } /** {@inheritDoc} */ @Override public final GridProjection forPredicate(GridPredicate<GridNode> p) { A.notNull(p, "p"); guard(); try { return new GridProjectionAdapter(this, ctx, subjId, this.p != null ? F.and(p, this.p) : p); } finally { unguard(); } } /** {@inheritDoc} */ @Override public final GridProjection forAttribute(String name, @Nullable final String val) { A.notNull(name, "n"); return forPredicate(new AttributeFilter(name, val)); } /** {@inheritDoc} */ @Override public final GridProjection forNode(GridNode node, GridNode... nodes) { A.notNull(node, "node"); guard(); try { Set<UUID> nodeIds; if (F.isEmpty(nodes)) nodeIds = contains(node) ? Collections.singleton(node.id()) : Collections.<UUID>emptySet(); else { nodeIds = new HashSet<>(nodes.length + 1); for (GridNode n : nodes) if (contains(n)) nodeIds.add(n.id()); if (contains(node)) nodeIds.add(node.id()); } return new GridProjectionAdapter(this, ctx, subjId, nodeIds); } finally { unguard(); } } /** {@inheritDoc} */ @Override public final GridProjection forNodes(Collection<? extends GridNode> nodes) { A.notEmpty(nodes, "nodes"); guard(); try { Set<UUID> nodeIds = new HashSet<>(nodes.size()); for (GridNode n : nodes) if (contains(n)) nodeIds.add(n.id()); return new GridProjectionAdapter(this, ctx, subjId, nodeIds); } finally { unguard(); } } /** {@inheritDoc} */ @Override public final GridProjection forNodeId(UUID id, UUID... ids) { A.notNull(id, "id"); guard(); try { Set<UUID> nodeIds; if (F.isEmpty(ids)) nodeIds = contains(id) ? Collections.singleton(id) : Collections.<UUID>emptySet(); else { nodeIds = new HashSet<>(ids.length + 1); for (UUID id0 : ids) { if (contains(id)) nodeIds.add(id0); } if (contains(id)) nodeIds.add(id); } return new GridProjectionAdapter(this, ctx, subjId, nodeIds); } finally { unguard(); } } /** {@inheritDoc} */ @Override public final GridProjection forNodeIds(Collection<UUID> ids) { A.notEmpty(ids, "ids"); guard(); try { Set<UUID> nodeIds = new HashSet<>(ids.size()); for (UUID id : ids) { if (contains(id)) nodeIds.add(id); } return new GridProjectionAdapter(this, ctx, subjId, nodeIds); } finally { unguard(); } } /** {@inheritDoc} */ @Override public final GridProjection forOthers(GridNode node, GridNode... nodes) { A.notNull(node, "node"); return forOthers(F.concat(false, node.id(), F.nodeIds(Arrays.asList(nodes)))); } /** {@inheritDoc} */ @Override public GridProjection forOthers(GridProjection prj) { A.notNull(prj, "prj"); if (ids != null) { guard(); try { Set<UUID> nodeIds = new HashSet<>(ids.size()); for (UUID id : ids) { GridNode n = node(id); if (n != null && !prj.predicate().apply(n)) nodeIds.add(id); } return new GridProjectionAdapter(this, ctx, subjId, nodeIds); } finally { unguard(); } } else return forPredicate(F.not(prj.predicate())); } /** {@inheritDoc} */ @Override public final GridProjection forRemotes() { return forOthers(Collections.singleton(ctx.localNodeId())); } /** * @param excludeIds Node IDs. * @return New projection. */ private GridProjection forOthers(Collection<UUID> excludeIds) { assert excludeIds != null; if (ids != null) { guard(); try { Set<UUID> nodeIds = new HashSet<>(ids.size()); for (UUID id : ids) { if (!excludeIds.contains(id)) nodeIds.add(id); } return new GridProjectionAdapter(this, ctx, subjId, nodeIds); } finally { unguard(); } } else return forPredicate(new OthersFilter(excludeIds)); } /** {@inheritDoc} */ @Override public final GridProjection forCache(@Nullable String cacheName, @Nullable String... cacheNames) { return forPredicate(new CachesFilter(cacheName, cacheNames)); } /** {@inheritDoc} */ @Override public final GridProjection forStreamer(@Nullable String streamerName, @Nullable String... streamerNames) { return forPredicate(new StreamersFilter(streamerName, streamerNames)); } /** {@inheritDoc} */ @Override public final GridProjection forHost(GridNode node) { A.notNull(node, "node"); String macs = node.attribute(ATTR_MACS); assert macs != null; return forAttribute(ATTR_MACS, macs); } /** {@inheritDoc} */ @Override public final GridProjection forDaemons() { return forPredicate(new DaemonFilter()); } /** {@inheritDoc} */ @Override public final GridProjection forRandom() { return ids != null ? forNodeId(F.rand(ids)) : forNode(F.rand(nodes())); } /** {@inheritDoc} */ @Override public GridProjection forOldest() { return new AgeProjection(this, true); } /** {@inheritDoc} */ @Override public GridProjection forYoungest() { return new AgeProjection(this, false); } /** {@inheritDoc} */ @Override public GridProjectionEx forSubjectId(UUID subjId) { if (subjId == null) return this; guard(); try { return ids != null ? new GridProjectionAdapter(this, ctx, subjId, ids) : new GridProjectionAdapter(this, ctx, subjId, p); } finally { unguard(); } } /** * @param n Node. * @return Whether node belongs to this projection. */ private boolean contains(GridNode n) { assert n != null; return ids != null ? ids.contains(n.id()) : p == null || p.apply(n); } /** * @param id Node ID. * @return Whether node belongs to this projection. */ private boolean contains(UUID id) { assert id != null; if (ids != null) return ids.contains(id); else { GridNode n = ctx.discovery().node(id); return n != null && (p == null || p.apply(n)); } } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, gridName); U.writeUuid(out, subjId); out.writeBoolean(ids != null); if (ids != null) out.writeObject(ids); else out.writeObject(p); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { gridName = U.readString(in); subjId = U.readUuid(in); if (in.readBoolean()) ids = (Set<UUID>)in.readObject(); else p = (GridPredicate<GridNode>)in.readObject(); } /** * Reconstructs object on unmarshalling. * * @return Reconstructed object. * @throws ObjectStreamException Thrown in case of unmarshalling error. */ protected Object readResolve() throws ObjectStreamException { try { GridKernal g = GridGainEx.gridx(gridName); return ids != null ? new GridProjectionAdapter(g, g.context(), subjId, ids) : p != null ? new GridProjectionAdapter(g, g.context(), subjId, p) : g; } catch (IllegalStateException e) { throw U.withCause(new InvalidObjectException(e.getMessage()), e); } } private static class CachesFilter implements GridPredicate<GridNode> { private static final long serialVersionUID = 0L; /** Cache name. */ private final String cacheName; /** Cache names. */ private final String[] cacheNames; /** * @param cacheName Cache name. * @param cacheNames Cache names. */ private CachesFilter(@Nullable String cacheName, @Nullable String[] cacheNames) { this.cacheName = cacheName; this.cacheNames = cacheNames; } /** {@inheritDoc} */ @Override public boolean apply(GridNode n) { if (!U.hasCache(n, cacheName)) return false; if (!F.isEmpty(cacheNames)) for (String cn : cacheNames) if (!U.hasCache(n, cn)) return false; return true; } } private static class StreamersFilter implements GridPredicate<GridNode> { private static final long serialVersionUID = 0L; /** Streamer name. */ private final String streamerName; /** Streamer names. */ private final String[] streamerNames; /** * @param streamerName Streamer name. * @param streamerNames Streamer names. */ private StreamersFilter(@Nullable String streamerName, @Nullable String[] streamerNames) { this.streamerName = streamerName; this.streamerNames = streamerNames; } /** {@inheritDoc} */ @Override public boolean apply(GridNode n) { if (!U.hasStreamer(n, streamerName)) return false; if (!F.isEmpty(streamerNames)) for (String sn : streamerNames) if (!U.hasStreamer(n, sn)) return false; return true; } } private static class AttributeFilter implements GridPredicate<GridNode> { private static final long serialVersionUID = 0L; /** Name. */ private final String name; /** Value. */ private final String val; /** * @param name Name. * @param val Value. */ private AttributeFilter(String name, String val) { this.name = name; this.val = val; } /** {@inheritDoc} */ @Override public boolean apply(GridNode n) { return val == null ? n.attributes().containsKey(name) : val.equals(n.attribute(name)); } } private static class DaemonFilter implements GridPredicate<GridNode> { private static final long serialVersionUID = 0L; /** {@inheritDoc} */ @Override public boolean apply(GridNode n) { return n.isDaemon(); } } private static class OthersFilter implements GridPredicate<GridNode> { private static final long serialVersionUID = 0L; private final Collection<UUID> nodeIds; /** * @param nodeIds Node IDs. */ private OthersFilter(Collection<UUID> nodeIds) { this.nodeIds = nodeIds; } /** {@inheritDoc} */ @Override public boolean apply(GridNode n) { return !nodeIds.contains(n.id()); } } /** * Age-based projection. */ private static class AgeProjection extends GridProjectionAdapter { /** Serialization version. */ private static final long serialVersionUID = 0L; /** Oldest flag. */ private boolean isOldest; /** Selected node. */ private volatile GridNode node; /** Last topology version. */ private volatile long lastTopVer; /** * Required for {@link Externalizable}. */ public AgeProjection() { // No-op. } /** * @param prj Parent projection. * @param isOldest Oldest flag. */ private AgeProjection(GridProjectionAdapter prj, boolean isOldest) { super(prj.parent, prj.ctx, prj.subjId, prj.p, prj.ids); this.isOldest = isOldest; reset(); } /** * Resets node. */ private synchronized void reset() { guard(); try { lastTopVer = ctx.discovery().topologyVersion(); this.node = isOldest ? U.oldest(super.nodes(), null) : U.youngest(super.nodes(), null); } finally { unguard(); } } /** {@inheritDoc} */ @Override public GridNode node() { if (ctx.discovery().topologyVersion() != lastTopVer) reset(); return node; } /** {@inheritDoc} */ @Override public Collection<GridNode> nodes() { if (ctx.discovery().topologyVersion() != lastTopVer) reset(); GridNode node = this.node; return node == null ? Collections.<GridNode>emptyList() : Collections.singletonList(node); } } }
package net.powermatcher.core.concentrator; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import net.powermatcher.api.AgentEndpoint; import net.powermatcher.api.MatcherEndpoint; import net.powermatcher.api.Session; import net.powermatcher.api.TimeService; import net.powermatcher.api.data.Bid; import net.powermatcher.api.data.Price; import net.powermatcher.api.monitoring.IncomingBidEvent; import net.powermatcher.api.monitoring.IncomingPriceEvent; import net.powermatcher.api.monitoring.ObservableAgent; import net.powermatcher.api.monitoring.OutgoingBidEvent; import net.powermatcher.api.monitoring.OutgoingPriceEvent; import net.powermatcher.api.monitoring.Qualifier; import net.powermatcher.core.BaseAgent; import net.powermatcher.core.BidCache; import net.powermatcher.core.BidCacheSnapshot; import net.powermatcher.core.auctioneer.Auctioneer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import aQute.bnd.annotation.component.Activate; import aQute.bnd.annotation.component.Component; import aQute.bnd.annotation.component.Deactivate; import aQute.bnd.annotation.component.Reference; import aQute.bnd.annotation.metatype.Configurable; import aQute.bnd.annotation.metatype.Meta; /** * <p> * This class represents a {@link Concentrator} component where several instances can be created. * </p> * * <p> * The {@link Concentrator} receives {@link Bid} from the agents and forwards this in an aggregate {@link Bid} up in the * hierarchy to a {@link Concentrator} or to the {@link Auctioneer}. It will receive price updates from the * {@link Auctioneer} and forward them to its connected agents. * * @author FAN * @version 1.0 * */ @Component(designateFactory = Concentrator.Config.class, immediate = true, provide = { ObservableAgent.class, MatcherEndpoint.class, AgentEndpoint.class }) public class Concentrator extends BaseAgent implements MatcherEndpoint, AgentEndpoint { private static final Logger LOGGER = LoggerFactory.getLogger(Concentrator.class); @Meta.OCD public static interface Config { @Meta.AD(deflt = "auctioneer") String desiredParentId(); @Meta.AD(deflt = "600", description = "Nr of seconds before a bid becomes invalidated") int bidTimeout(); @Meta.AD(deflt = "60", description = "Number of seconds between bid updates") long bidUpdateRate(); @Meta.AD(deflt = "concentrator") String agentId(); } /** * TimeService that is used for obtaining real or simulated time. */ private TimeService timeService; /** * Scheduler that can schedule commands to run after a given delay, or to execute periodically. */ private ScheduledExecutorService scheduler; /** * A delayed result-bearing action that can be cancelled. */ private ScheduledFuture<?> scheduledFuture; /** * {@link Session} object for connecting to matcher */ private Session sessionToMatcher; /** * The {@link Bid} cache maintains an aggregated {@link Bid}, where bids can be added and removed explicitly. */ private BidCache aggregatedBids; /** * Holds the sessions from the agents. */ private Set<Session> sessionToAgents = new HashSet<Session>(); /** * OSGI configuration meta type with info about the concentrator. */ private Config config; @Reference public void setTimeService(TimeService timeService) { this.timeService = timeService; } @Reference public void setExecutorService(ScheduledExecutorService scheduler) { this.scheduler = scheduler; } @Activate public void activate(final Map<String, Object> properties) { config = Configurable.createConfigurable(Config.class, properties); this.setAgentId(config.agentId()); this.setDesiredParentId(config.desiredParentId()); this.aggregatedBids = new BidCache(this.timeService, config.bidTimeout()); scheduledFuture = this.scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { doBidUpdate(); } catch (IllegalStateException | IllegalArgumentException e) { LOGGER.error("doBidUpate failed for Concentrator " + config.agentId(), e); } } }, 0, config.bidUpdateRate(), TimeUnit.SECONDS); LOGGER.info("Agent [{}], activated", config.agentId()); } @Deactivate public void deactivate() { scheduledFuture.cancel(false); LOGGER.info("Agent [{}], deactivated", config.agentId()); } @Override public synchronized void connectToMatcher(Session session) { this.sessionToMatcher = session; setClusterId(session.getClusterId()); } @Override public synchronized void matcherEndpointDisconnected(Session session) { for (Session agentSession : sessionToAgents.toArray(new Session[sessionToAgents.size()])) { agentSession.disconnect(); } setClusterId(null); this.sessionToMatcher = null; } @Override public synchronized boolean connectToAgent(Session session) { if (this.sessionToMatcher == null) { return false; } this.sessionToAgents.add(session); session.setMarketBasis(this.sessionToMatcher.getMarketBasis()); session.setClusterId(this.sessionToMatcher.getClusterId()); this.aggregatedBids.updateBid(session.getAgentId(), new Bid(this.sessionToMatcher.getMarketBasis())); LOGGER.info("Agent connected with session [{}]", session.getSessionId()); return true; } @Override public synchronized void agentEndpointDisconnected(Session session) { // Find session if (!sessionToAgents.remove(session)) { return; } this.aggregatedBids.removeAgent(session.getSessionId()); LOGGER.info("Agent disconnected with session [{}]", session.getSessionId()); } @Override public synchronized void updateBid(Session session, Bid newBid) throws IllegalStateException, IllegalArgumentException { if (!sessionToAgents.contains(session)) { throw new IllegalStateException("No session found"); } if (!newBid.getMarketBasis().equals(this.sessionToMatcher.getMarketBasis())) { throw new IllegalArgumentException("Marketbasis new bid differs from marketbasis auctioneer"); } this.publishEvent(new IncomingBidEvent(session.getClusterId(), config.agentId(), session.getSessionId(), timeService.currentDate(), "agentId", newBid, Qualifier.AGENT)); // Update agent in aggregatedBids this.aggregatedBids.updateBid(session.getAgentId(), newBid); LOGGER.info("Received from session [{}] bid update [{}] ", session.getSessionId(), newBid); } @Override public void updatePrice(Price newPrice) { if (newPrice == null) { LOGGER.error("Price cannot be null"); return; } LOGGER.debug("Received price update [{}]", newPrice); this.publishEvent(new IncomingPriceEvent(sessionToMatcher.getClusterId(), this.config.agentId(), this.sessionToMatcher.getSessionId(), timeService.currentDate(), newPrice, Qualifier.AGENT)); // Find bidCacheSnapshot belonging to the newly received price update BidCacheSnapshot bidCacheSnapshot = this.aggregatedBids.getMatchingSnapshot(newPrice.getBidNumber()); if (bidCacheSnapshot == null) { // ignore price and log warning LOGGER.warn("Received a price update for a bid that I never sent, id: {}", newPrice.getBidNumber()); return; } // Publish new price to connected agents for (Session session : this.sessionToAgents) { Integer originalAgentBid = bidCacheSnapshot.getBidNumbers().get(session.getAgentId()); if (originalAgentBid == null) { // ignore price for this agent and log warning continue; } Price agentPrice = new Price(newPrice.getMarketBasis(), newPrice.getCurrentPrice(), originalAgentBid); session.updatePrice(agentPrice); this.publishEvent(new OutgoingPriceEvent(session.getClusterId(), this.config.agentId(), session.getSessionId(), timeService .currentDate(), newPrice, Qualifier.MATCHER)); } } /** * sends the aggregatedbids to the matcher this method has temporarily been made public due to issues with the * scheduler. TODO fix this asap */ public synchronized void doBidUpdate() { if (sessionToMatcher != null) { Bid aggregatedBid = this.aggregatedBids.getAggregatedBid(this.sessionToMatcher.getMarketBasis()); this.sessionToMatcher.updateBid(aggregatedBid); publishEvent(new OutgoingBidEvent(sessionToMatcher.getClusterId(), config.agentId(), sessionToMatcher.getSessionId(), timeService.currentDate(), aggregatedBid, Qualifier.MATCHER)); LOGGER.debug("Updating aggregated bid [{}]", aggregatedBid); } } }
package it.unibz.krdb.obda.parser; import it.unibz.krdb.obda.model.OBDADataFactory; import it.unibz.krdb.obda.model.Variable; import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl; import it.unibz.krdb.sql.DBMetadata; import it.unibz.krdb.sql.DataDefinition; import it.unibz.krdb.sql.api.Attribute; import it.unibz.krdb.sql.api.ParsedSQLQuery; import net.sf.jsqlparser.expression.Alias; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.select.*; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * This visitor class remove * in select clause and substitute it with the columns name * Gets the column names or aliases also from the subclasses. * */ public class PreprocessProjection implements SelectVisitor, SelectItemVisitor, FromItemVisitor { private List<SelectItem> columns = new ArrayList<>(); private boolean selectAll = false; private boolean subselect = false; private String aliasSubselect ; final private DBMetadata metadata; private Set<Variable> variables; private static final OBDADataFactory fac = OBDADataFactoryImpl.getInstance(); public PreprocessProjection(DBMetadata metadata) throws SQLException { //use the metadata to get the column names this.metadata = metadata; } /** * Method to substitute * from the select query. It add the columns name that are used in the mapping * @param select the query with or without * * @param variables the variables used in the mapping, this are the needed columns for our select query * @return the query with columns or functions in the projection part */ public String getMappingQuery(Select select, Set<Variable> variables) { this.variables = variables; if (select.getWithItemsList() != null) { for (WithItem withItem : select.getWithItemsList()) { withItem.accept(this); } } select.getSelectBody().accept(this); return select.toString(); } /* Create a set of selectItem (columns) if * add all selectItems obtained by the metadata or the subselect clause */ @Override public void visit(PlainSelect plainSelect) { List<SelectItem> columnNames = new ArrayList<SelectItem>(); //get the from clause (can have subselect) FromItem table = plainSelect.getFromItem(); FromItem joinTable = null; //get the join clause (can have subselect) if (plainSelect.getJoins() != null) { for (Join join : plainSelect.getJoins()) { joinTable = join.getRightItem(); } } // look at the projection clause for (SelectItem expr : plainSelect.getSelectItems()) { //create a set of selectItem (columns) //if * add all selectItems obtained by the metadata or the subselect clause if (isSelectAll(expr)) { if(joinTable!=null){ joinTable.accept(this); columnNames.addAll(columns); columns.clear(); } if(table!=null){ table.accept(this); columnNames.addAll(columns); columns.clear(); } } // else add only the column else { if(!subselect) { columnNames.add(expr); } else { //in case of subselects //see if there is an alias Table tableName; if(aliasSubselect != null){ tableName= new Table(aliasSubselect); } else { //use the alias if present if (table.getAlias() != null) { tableName = new Table(table.getAlias().getName()); } else { tableName = (Table)table; } } Alias aliasName = ((SelectExpressionItem) expr).getAlias(); if (aliasName != null) { String aliasString = aliasName.getName(); SelectExpressionItem columnAlias; if(ParsedSQLQuery.pQuotes.matcher(aliasString).matches()) { columnAlias = new SelectExpressionItem(new Column(tableName, aliasString)); } else{ columnAlias = new SelectExpressionItem(new Column(tableName, "\"" + aliasString + "\"")); } //construct a column from alias name if (variables.contains(fac.getVariable(aliasString)) || variables.contains(fac.getVariable(aliasString.toLowerCase())) || variables.contains(fac.getVariable(columnAlias.toString())) || variables.contains(fac.getVariable(aliasString.toString().toLowerCase()))) { columnNames.add(columnAlias); } } else { //when there are no alias add the columns that are used in the mappings String columnName = ((Column)((SelectExpressionItem) expr).getExpression()).getColumnName(); SelectExpressionItem column; if(ParsedSQLQuery.pQuotes.matcher(columnName).matches()) { column = new SelectExpressionItem(new Column(tableName, columnName)); } else{ column = new SelectExpressionItem(new Column(tableName, "\"" + columnName + "\"")); } if (variables.contains(fac.getVariable(columnName)) || variables.contains(fac.getVariable(columnName.toLowerCase())) || variables.contains(fac.getVariable(column.toString())) || variables.contains(fac.getVariable(columnName.toString().toLowerCase()))) { columnNames.add(column); } } } } } if(!subselect) { if(!columnNames.isEmpty()) plainSelect.setSelectItems(columnNames); } else{ columns.addAll(columnNames); } } @Override public void visit(SetOperationList setOpList) { } @Override public void visit(WithItem withItem) { } @Override public void visit(AllColumns allColumns) { selectAll=true; } @Override public void visit(AllTableColumns allTableColumns) { selectAll=true; } @Override public void visit(SelectExpressionItem selectExpressionItem) { } @Override public void visit(Table tableName) { //obtain the column names from the metadata obtainColumnsFromMetadata(tableName); } @Override public void visit(SubSelect subSelect) { subselect = true; aliasSubselect = subSelect.getAlias().getName(); subSelect.getSelectBody().accept(this); subselect = false; aliasSubselect = null; } @Override public void visit(SubJoin subjoin) { } @Override public void visit(LateralSubSelect lateralSubSelect) { } @Override public void visit(ValuesList valuesList) { } /* Flag for the presence of the * in the query */ private boolean isSelectAll(SelectItem expr){ expr.accept(this); boolean result =selectAll; selectAll = false; return result; } /** From a table, obtain all its columns using the metadata information @return List<SelectItem> list of columns in JSQL SelectItem class the column is rewritten as tableName.columnName or aliasName.columnName */ private void obtainColumnsFromMetadata(Table table) { String tableFullName= table.getFullyQualifiedName(); if (ParsedSQLQuery.pQuotes.matcher(tableFullName).matches()) { tableFullName = tableFullName.substring(1, tableFullName.length()-1); } DataDefinition tableDefinition = metadata.getDefinition(tableFullName); if (tableDefinition == null) throw new RuntimeException("Definition not found for table '" + table + "'."); Table tableName; if (aliasSubselect != null) { tableName= new Table(aliasSubselect); } else if (table.getAlias() != null) { //use the alias if present tableName = new Table(table.getAlias().getName()); } else { tableName = table; } for (Attribute att : tableDefinition.getAttributes()) { String columnFromMetadata = att.getName(); SelectExpressionItem columnName; if(ParsedSQLQuery.pQuotes.matcher(columnFromMetadata).matches()){ columnName = new SelectExpressionItem(new Column(tableName, columnFromMetadata )); } else { columnName = new SelectExpressionItem(new Column(tableName, "\"" + columnFromMetadata + "\"")); } //construct a column as table.column if (variables.contains(fac.getVariable(columnFromMetadata)) || variables.contains(fac.getVariable(columnFromMetadata.toLowerCase())) || variables.contains(fac.getVariable(columnName.toString())) || variables.contains(fac.getVariable(columnName.toString().toLowerCase()))) { columns.add(columnName); } } } }
package com.jraska.falcon; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Build; import android.os.Looper; import android.util.Log; import android.view.View; import android.view.WindowManager.LayoutParams; import java.io.*; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import static android.graphics.Bitmap.Config.ARGB_8888; import static android.view.WindowManager.LayoutParams.FLAG_DIM_BEHIND; /** * Utility class to take screenshots of activity screen */ public final class Falcon { //region Constants private static final String TAG = "Falcon"; //endregion //region Public API /** * Takes screenshot of provided activity and saves it to provided file. * File content will be overwritten if there is already some content. * * @param activity Activity of which the screenshot will be taken. * @param toFile File where the screenshot will be saved. * If there is some content it will be overwritten * @throws UnableToTakeScreenshotException When there is unexpected error during taking screenshot */ public static void takeScreenshot(Activity activity, final File toFile) { if (activity == null) { throw new IllegalArgumentException("Parameter activity cannot be null."); } if (toFile == null) { throw new IllegalArgumentException("Parameter toFile cannot be null."); } Bitmap bitmap = null; try { bitmap = takeBitmapUnchecked(activity); writeBitmap(bitmap, toFile); } catch (Exception e) { String message = "Unable to take screenshot to file " + toFile.getAbsolutePath() + " of activity " + activity.getClass().getName(); Log.e(TAG, message, e); throw new UnableToTakeScreenshotException(message, e); } finally { if (bitmap != null) { bitmap.recycle(); } } Log.d(TAG, "Screenshot captured to " + toFile.getAbsolutePath()); } /** * Takes screenshot of provided activity and puts it into bitmap. * * @param activity Activity of which the screenshot will be taken. * @return Bitmap of what is displayed in activity. * @throws UnableToTakeScreenshotException When there is unexpected error during taking screenshot */ public static Bitmap takeScreenshotBitmap(Activity activity) { if (activity == null) { throw new IllegalArgumentException("Parameter activity cannot be null."); } try { return takeBitmapUnchecked(activity); } catch (Exception e) { String message = "Unable to take screenshot to bitmap of activity " + activity.getClass().getName(); Log.e(TAG, message, e); throw new UnableToTakeScreenshotException(message, e); } } //endregion //region Methods private static Bitmap takeBitmapUnchecked(Activity activity) throws InterruptedException { final List<ViewRootData> viewRoots = getRootViews(activity); View main = activity.getWindow().getDecorView(); final Bitmap bitmap = Bitmap.createBitmap(main.getWidth(), main.getHeight(), ARGB_8888); // We need to do it in main thread if (Looper.myLooper() == Looper.getMainLooper()) { drawRootsToBitmap(viewRoots, bitmap); } else { final CountDownLatch latch = new CountDownLatch(1); activity.runOnUiThread(new Runnable() { @Override public void run() { try { drawRootsToBitmap(viewRoots, bitmap); } finally { latch.countDown(); } } }); latch.await(); } return bitmap; } private static void drawRootsToBitmap(List<ViewRootData> viewRoots, Bitmap bitmap) { for (ViewRootData rootData : viewRoots) { drawRootToBitmap(rootData, bitmap); } } private static void drawRootToBitmap(ViewRootData config, Bitmap bitmap) { // now only dim supported if ((config._layoutParams.flags & FLAG_DIM_BEHIND) == FLAG_DIM_BEHIND) { Canvas dimCanvas = new Canvas(bitmap); int alpha = (int) (255 * config._layoutParams.dimAmount); dimCanvas.drawARGB(alpha, 0, 0, 0); } Canvas canvas = new Canvas(bitmap); canvas.translate(config._winFrame.left, config._winFrame.top); config._view.draw(canvas); } private static void writeBitmap(Bitmap bitmap, File toFile) throws IOException { OutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(toFile)); bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); } finally { if (outputStream != null) { outputStream.close(); } } } @SuppressWarnings("unchecked") // no way to check private static List<ViewRootData> getRootViews(Activity activity) { List<ViewRootData> rootViews = new ArrayList<>(); Object globalWindowManager; if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { globalWindowManager = getFieldValue("mWindowManager", activity.getWindowManager()); } else { globalWindowManager = getFieldValue("mGlobal", activity.getWindowManager()); } Object rootObjects = getFieldValue("mRoots", globalWindowManager); Object paramsObject = getFieldValue("mParams", globalWindowManager); Object[] roots; LayoutParams[] params; // There was a change to ArrayList implementation in 4.4 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { roots = ((List) rootObjects).toArray(); List<LayoutParams> paramsList = (List<LayoutParams>) paramsObject; params = paramsList.toArray(new LayoutParams[paramsList.size()]); } else { roots = (Object[]) rootObjects; params = (LayoutParams[]) paramsObject; } for (int i = 0; i < roots.length; i++) { Object root = roots[i]; Object attachInfo = getFieldValue("mAttachInfo", root); int top = (int) getFieldValue("mWindowTop", attachInfo); int left = (int) getFieldValue("mWindowLeft", attachInfo); Rect winFrame = (Rect) getFieldValue("mWinFrame", root); Rect area = new Rect(left, top, left + winFrame.width(), top + winFrame.height()); View view = (View) getFieldValue("mView", root); rootViews.add(new ViewRootData(view, area, params[i])); } return rootViews; } private static Object getFieldValue(String fieldName, Object target) { try { return getFieldValueUnchecked(fieldName, target); } catch (Exception e) { throw new RuntimeException(e); } } private static Object getFieldValueUnchecked(String fieldName, Object target) throws NoSuchFieldException, IllegalAccessException { Field field = findField(fieldName, target.getClass()); field.setAccessible(true); return field.get(target); } private static Field findField(String name, Class clazz) throws NoSuchFieldException { Class currentClass = clazz; while (currentClass != Object.class) { for (Field field : currentClass.getDeclaredFields()) { if (name.equals(field.getName())) { return field; } } currentClass = currentClass.getSuperclass(); } throw new NoSuchFieldException("Field " + name + " not found for class " + clazz); } //endregion //region Constructors // No instances private Falcon() { } //endregion //region Nested classes /** * Custom exception thrown if there is some exception thrown during * screenshot capturing to enable better client code exception handling. */ public static class UnableToTakeScreenshotException extends RuntimeException { private UnableToTakeScreenshotException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } } private static class ViewRootData { private final View _view; private final Rect _winFrame; private final LayoutParams _layoutParams; public ViewRootData(View view, Rect winFrame, LayoutParams layoutParams) { _view = view; _winFrame = winFrame; _layoutParams = layoutParams; } } //endregion }
package org.mwc.debrief.dis.diagnostics; import java.io.*; import java.net.*; import java.util.*; import edu.nps.moves.dis.*; import edu.nps.moves.disutil.CoordinateConversions; import edu.nps.moves.disutil.DisTime; /** * Creates and sends ESPDUs in IEEE binary format. * * @author DMcG */ public class CustomEspduSender { public enum NetworkMode { UNICAST, MULTICAST, BROADCAST }; /** default multicast group we send on */ public static final String DEFAULT_MULTICAST_GROUP = "239.1.2.3"; /** Port we send on */ public static final int PORT = 62040; private static boolean _terminate; public static void main(String args[]) { /** an entity state pdu */ EntityStatePdu espdu = new EntityStatePdu(); MulticastSocket socket = null; DisTime disTime = DisTime.getInstance(); // origin of path double lat = 50.1; double lon = -1.877000; double courseRads = Math.toRadians(80d); // Default settings. These are used if no system properties are set. // If system properties are passed in, these are over ridden. int port = PORT; @SuppressWarnings("unused") NetworkMode mode = NetworkMode.MULTICAST; InetAddress destinationIp = null; try { destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); } catch (Exception e) { System.out.println(e + " Cannot create multicast address"); System.exit(0); } // All system properties, passed in on the command line via -Dattribute=value Properties systemProperties = System.getProperties(); // IP address we send to String destinationIpString = systemProperties.getProperty("destinationIp"); // Port we send to, and local port we open the socket on String portString = systemProperties.getProperty("port"); // Network mode: unicast, multicast, broadcast String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast // or broadcast // Set up a socket to send information try { // Port we send to if (portString != null) port = Integer.parseInt(portString); socket = new MulticastSocket(port); // Where we send packets to, the destination IP address if (destinationIpString != null) { destinationIp = InetAddress.getByName(destinationIpString); } // Type of transport: unicast, broadcast, or multicast if (networkModeString != null) { if (networkModeString.equalsIgnoreCase("unicast")) mode = NetworkMode.UNICAST; else if (networkModeString.equalsIgnoreCase("broadcast")) mode = NetworkMode.BROADCAST; else if (networkModeString.equalsIgnoreCase("multicast")) { mode = NetworkMode.MULTICAST; if (!destinationIp.isMulticastAddress()) { throw new RuntimeException( "Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); } socket.joinGroup(destinationIp); } } // end networkModeString } catch (Exception e) { System.out.println("Unable to initialize networking. Exiting."); System.out.println(e); System.exit(-1); } // Initialize values in the Entity State PDU object. The exercise ID is // a way to differentiate between different virtual worlds on one network. // Note that some values (such as the PDU type and PDU family) are set // automatically when you create the ESPDU. espdu.setExerciseID((short) 1); // The EID is the unique identifier for objects in the world. This // EID should match up with the ID for the object specified in the // VMRL/x3d/virtual world. EntityID eid = espdu.getEntityID(); eid.setSite(0); eid.setApplication(1); eid.setEntity(2); // Set the entity type. SISO has a big list of enumerations, so that by // specifying various numbers we can say this is an M1A2 American tank, // the USS Enterprise, and so on. We'll make this a tank. There is a // separate project elsehwhere in this project that implements DIS // enumerations in C++ and Java, but to keep things simple we just use // numbers here. EntityType entityType = espdu.getEntityType(); entityType.setEntityKind((short) 1); // Platform (vs lifeform, munition, sensor, etc.) entityType.setCountry(225); // USA entityType.setDomain((short) 1); // Land (vs air, surface, subsurface, space) entityType.setCategory((short) 1); // Tank entityType.setSubcategory((short) 1); // M1 Abrams entityType.setSpec((short) 3); // M1A2 Abrams // Loop through sending 100 ESPDUs try { _terminate = false; System.out.println("Sending 100 ESPDU packets to " + destinationIp.toString()); for (int idx = 0; idx < 100; idx++) { // just check if we're being terminated early if (_terminate) { break; } // DIS time is a pain in the ass. DIS time units are 2^31-1 units per // hour, and time is set to DIS time units from the top of the hour. // This means that if you start sending just before the top of the hour // the time units can roll over to zero as you are sending. The receivers // (escpecially homegrown ones) are often not able to detect rollover // and may start discarding packets as dupes or out of order. We use // an NPS timestamp here, hundredths of a second since the start of the // year. The DIS standard for time is often ignored in the wild; I've seen // people use Unix time (seconds since 1970) and more. Or you can // just stuff idx into the timestamp field to get something that is monotonically // increasing. // Note that timestamp is used to detect duplicate and out of order packets. // That means if you DON'T change the timestamp, many implementations will simply // discard subsequent packets that have an identical timestamp. Also, if they // receive a PDU with an timestamp lower than the last one they received, they // may discard it as an earlier, out-of-order PDU. So it is a good idea to // update the timestamp on ALL packets sent. // espdu.setTimestamp(disTime.getNpsTimestamp()); // An alterative approach: actually follow the standard. It's a crazy concept, // but it might just work. int ts = disTime.getDisAbsoluteTimestamp(); espdu.setTimestamp(ts); // Set the position of the entity in the world. DIS uses a cartesian // coordinate system with the origin at the center of the earth, the x // axis out at the equator and prime meridian, y out at the equator and // 90 deg east, and z up and out the north pole. To place an object on // the earth's surface you also need a model for the shape of the earth // (it's not a sphere.) All the fancy math necessary to do this is in // the SEDRIS SRM package. There are also some one-off formulas for // doing conversions from, for example, lat/lon/altitude to DIS coordinates. // Here we use those one-off formulas. // Modify the position of the object. This will send the object a little // due east by adding some to the longitude every iteration. Since we // are on the Pacific coast, this sends the object east. Assume we are // at zero altitude. In other worlds you'd use DTED to determine the // local ground altitude at that lat/lon, or you'd just use ground clamping. // The x and y values will change, but the z value should not. double dLat = Math.cos(courseRads) * ((double) idx / 1000d); double dLon = Math.sin(courseRads) * ((double) idx / 1000d); lon = lon + dLon; lat = lat + dLat; if ((idx % 10) == 0) { final double newCourse = ((int) (Math.random() * 360d)) * 360d; courseRads = Math.toRadians(newCourse); } // lon = lon + (double) ((double) idx / 1000.0); double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 0.0); Vector3Double location = espdu.getEntityLocation(); location.setX(disCoordinates[0]); location.setY(disCoordinates[1]); location.setZ(disCoordinates[2]); // Optionally, we can do some rotation of the entity /* * Orientation orientation = espdu.getEntityOrientation(); float psi = orientation.getPsi(); * psi = psi + idx; orientation.setPsi(psi); * orientation.setTheta((float)(orientation.getTheta() + idx /2.0)); */ // You can set other ESPDU values here, such as the velocity, acceleration, // and so on. // Marshal out the espdu object to a byte array, then send a datagram // packet with that data in it. ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); espdu.marshal(dos); // The byte array here is the packet in DIS format. We put that into a // datagram and send it. byte[] data = baos.toByteArray(); DatagramPacket packet = new DatagramPacket(data, data.length, destinationIp, PORT); socket.send(packet); // Send every 1 sec. Otherwise this will be all over in a fraction of a second. Thread.sleep(1000); location = espdu.getEntityLocation(); System.out.print("Espdu #" + idx + " EID=[" + eid.getSite() + "," + eid.getApplication() + "," + eid.getEntity() + "]"); System.out.print(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); double c[] = {location.getX(), location.getY(), location.getZ()}; double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); } } catch (Exception e) { System.out.println(e); } } public static void terminate() { _terminate = true; } }
package org.mwc.debrief.dis.diagnostics; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import edu.nps.moves.dis.CollisionPdu; import edu.nps.moves.dis.DetonationPdu; import edu.nps.moves.dis.EntityID; import edu.nps.moves.dis.EntityStatePdu; import edu.nps.moves.dis.EntityType; import edu.nps.moves.dis.EventReportPdu; import edu.nps.moves.dis.FirePdu; import edu.nps.moves.dis.OneByteChunk; import edu.nps.moves.dis.Pdu; import edu.nps.moves.dis.StopFreezePdu; import edu.nps.moves.dis.VariableDatum; import edu.nps.moves.dis.Vector3Double; import edu.nps.moves.dis.Vector3Float; import edu.nps.moves.disutil.CoordinateConversions; /** * Creates and sends ESPDUs in IEEE binary format. * * @author DMcG */ public class CustomEspduSender { private static final short STOP_PDU_TERMINATED = 2; public enum NetworkMode { UNICAST, MULTICAST, BROADCAST }; /** default multicast group we send on */ public static final String DEFAULT_MULTICAST_GROUP = "239.1.2.3"; /** Port we send on */ public static final int PORT = 62040; private boolean _terminate; private MulticastSocket socket; private InetAddress destinationIp; private short exerciseId; private class Participant { private Participant(final int id, double oLat, double oLong, double range) { this.id = id; latVal = oLat + Math.random() * range; longVal = oLong + Math.random() * range; courseRads = Math.toRadians(((int) (Math.random() * 36d)) * 10d); } final int id; double latVal; double longVal; double courseRads; /** * if this participant has a target that it aims for * */ public int targetId = -1; public void update(Map<Integer, Participant> states, double distStep, int idx, long lastTime, EntityID sampleId) { // hmm, do we have a target? if (targetId != -1) { Participant myTarget = null; // does this target exist Participant[] parts = states.values().toArray(new Participant[] {null}); for (int i = 0; i < parts.length; i++) { final Participant thisP = parts[i]; // hey, don't look at ourselves... if (thisP.id == id) { // skip to the next loop continue; } // hmm, see if we're very close to this one double dLon = thisP.longVal - longVal; double dLat = thisP.latVal - latVal; double range = Math.sqrt(dLon * dLon + dLat * dLat); if (range < 0.01) { if (thisP.id == targetId) { sendDetonation(this, thisP.id, sampleId, states, lastTime); } else { sendCollision(this, thisP.id, sampleId, states, lastTime); } } if (thisP.id == targetId) { double bearing = Math.atan2(dLon, dLat); courseRads = bearing; myTarget = thisP; // target lost, forget about it // final String theMsg = // "platform:" + id + " turned towards:" + targetId; // sendMessage(exerciseId, lastTime, 12, sampleId, theMsg); } } // did we find it? if (myTarget != null) { } else { // target lost, forget about it final String theMsg = "target for:" + id + " was lost, was:" + targetId; sendMessage(exerciseId, lastTime, 12, sampleId, theMsg); System.out.println(theMsg); targetId = -1; } } // ok, handle the movement double dLat = Math.cos(courseRads) * distStep; double dLon = Math.sin(courseRads) * distStep; longVal += dLon; latVal += dLat; // see if we're going to do a random turn if (Math.random() > 0.8 && targetId == -1) { final double newCourse = ((int) (Math.random() * 36d)) * 10d; courseRads = Math.toRadians(newCourse); } } } public static void main(String args[]) { CustomEspduSender sender = new CustomEspduSender(); sender.run(args); } public void run(String args[]) { /** an entity state pdu */ EntityStatePdu espdu = new EntityStatePdu(); // DisTime disTime = DisTime.getInstance(); // declare the states final Map<Integer, Participant> states = new HashMap<Integer, Participant>(); // sort out the runtime arguments long stepMillis = 500; long numParts = 1; int numMessages = 1000; // try to extract the step millis from the args if (args.length >= 1 && args[0].length() > 1) { stepMillis = Long.parseLong(args[0]); } if (args.length >= 2) { numParts = Long.parseLong(args[1]); } if (args.length >= 3) { numMessages = Integer.parseInt(args[2]); } // Default settings. These are used if no system properties are set. // If system properties are passed in, these are over ridden. int port = PORT; @SuppressWarnings("unused") NetworkMode mode = NetworkMode.MULTICAST; destinationIp = null; try { destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); } catch (Exception e) { System.out.println(e + " Cannot create multicast address"); System.exit(0); } // All system properties, passed in on the command line via // -Dattribute=value Properties systemProperties = System.getProperties(); // IP address we send to String destinationIpString = systemProperties.getProperty("destinationIp"); // Port we send to, and local port we open the socket on String portString = systemProperties.getProperty("port"); // Network mode: unicast, multicast, broadcast String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast // Set up a socket to send information try { // Port we send to if (portString != null) port = Integer.parseInt(portString); socket = new MulticastSocket(port); // Where we send packets to, the destination IP address if (destinationIpString != null) { destinationIp = InetAddress.getByName(destinationIpString); } // Type of transport: unicast, broadcast, or multicast if (networkModeString != null) { if (networkModeString.equalsIgnoreCase("unicast")) mode = NetworkMode.UNICAST; else if (networkModeString.equalsIgnoreCase("broadcast")) mode = NetworkMode.BROADCAST; else if (networkModeString.equalsIgnoreCase("multicast")) { mode = NetworkMode.MULTICAST; if (!destinationIp.isMulticastAddress()) { throw new RuntimeException( "Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); } socket.joinGroup(destinationIp); } } // end networkModeString } catch (Exception e) { System.out.println("Unable to initialize networking. Exiting."); System.out.println(e); System.exit(-1); } // Initialize values in the Entity State PDU object. The exercise ID is // a way to differentiate between different virtual worlds on one network. // Note that some values (such as the PDU type and PDU family) are set // automatically when you create the ESPDU. exerciseId = (short) (Math.random() * 1000d); espdu.setExerciseID(exerciseId); // The EID is the unique identifier for objects in the world. This // EID should match up with the ID for the object specified in the // VMRL/x3d/virtual world. EntityID eid = espdu.getEntityID(); eid.setSite(0); eid.setApplication(1); int entityId = 2; eid.setEntity(entityId); // Set the entity type. SISO has a big list of enumerations, so that by // specifying various numbers we can say this is an M1A2 American tank, // the USS Enterprise, and so on. We'll make this a tank. There is a // separate project elsehwhere in this project that implements DIS // enumerations in C++ and Java, but to keep things simple we just use // numbers here. EntityType entityType = espdu.getEntityType(); entityType.setEntityKind((short) 1); // Platform (vs lifeform, munition, // sensor, etc.) entityType.setCountry(225); // USA entityType.setDomain((short) 1); // Land (vs air, surface, subsurface, // space) entityType.setCategory((short) 1); // Tank entityType.setSubcategory((short) 1); // M1 Abrams entityType.setSpec((short) 3); // M1A2 Abrams int randomHour = (int) (2 + Math.random() * 20); @SuppressWarnings("deprecation") long lastTime = new Date(2015, 1, 1, randomHour, 0).getTime(); // Loop through sending 100 ESPDUs try { _terminate = false; System.out.println("Sending " + numMessages + " ESPDU packets to " + destinationIp.toString()); final double startX = 50.1; final double startY = -1.87; final double startZ = 0.01; // generate the inital states for (int i = 0; i < numParts; i++) { int eId = i + 1;// 1 + (int) (Math.random() * 20d); Participant newS = new Participant(eId, startX, startY, startZ); states.put(eId, newS); } // generate correct number of messages for (int idx = 0; idx < numMessages; idx++) { // just check if we're being terminated early if (_terminate) { break; } // increment time lastTime += 5 * 60 * 1000; espdu.setTimestamp(lastTime); // get an array of participants. we don't use an interator, // to avoid concurrent modification Participant[] parts = states.values().toArray(new Participant[] {null}); for (int i = 0; i < parts.length; i++) { Participant thisS = parts[i]; eid.setEntity(thisS.id); final double distStep = 0.01; // get the subject to move forward thisS.update(states, distStep, idx, lastTime, eid); double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(thisS.latVal, thisS.longVal, 0.0); Vector3Double location = espdu.getEntityLocation(); location.setX(disCoordinates[0]); location.setY(disCoordinates[1]); location.setZ(disCoordinates[2]); // and send it sendPdu(espdu); location = espdu.getEntityLocation(); } // put in a random event double thisR = Math.random(); if ((states.size() > 1) && (thisR >= 0.6)) { // // build up the PDU // EventReportPdu dp = new EventReportPdu(); // dp.setExerciseID(espdu.getExerciseID()); // dp.setTimestamp(lastTime); // dp.setEventType((long) (Math.random() * 50)); // // produce random participant. // int partId = randomEntity(states.values()).id; // eid.setEntity(partId); // dp.setOriginatingEntityID(eid); // sendMessage(espdu.getExerciseID(), lastTime, 12, eid, "some message"); } // put in a random launch if (Math.random() >= 0.92) { System.out.println("===== LAUNCH ===== "); final int launchId = randomEntity(states.values()).id; final int newId = (int) (1000 + (Math.random() * 1000d)); Participant newS = new Participant(newId, startX, startY, startZ); // try to give the new vehicle a target Participant targetId = randomEntity(states.values()); newS.targetId = targetId.id; // and remember it states.put(newId, newS); // also send out the "fired" message FirePdu fire = new FirePdu(); fire.setExerciseID(espdu.getExerciseID()); fire.setTimestamp(lastTime); eid.setEntity(newId); fire.setFiringEntityID(eid); // and the location Participant launcher = states.get(launchId); Vector3Double wLoc = new Vector3Double(); wLoc.setX(launcher.longVal); wLoc.setY(launcher.latVal); wLoc.setZ(startZ); fire.setLocationInWorldCoordinates(wLoc); // ok, send it out sendPdu(fire); System.out.println(": launch of:" + newId + " from:" + launchId + " aiming for:" + targetId.id); } // Send every 1 sec. Otherwise this will be all over in a fraction of a // second. Thread.sleep(stepMillis); } // ok, data complete. send stop PDU // The byte array here is the packet in DIS format. We put that into a // datagram and send it. StopFreezePdu stopPdu = new StopFreezePdu(); stopPdu.setReason(STOP_PDU_TERMINATED); // and send it sendPdu(stopPdu); System.out.println("COMPLETE SENT!"); } catch (Exception e) { System.out.println(e); } } private void sendPdu(final Pdu pdu) throws IOException { // Marshal out the espdu object to a byte array, then send a datagram // packet with that data in it. ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); pdu.marshal(dos); // The byte array here is the packet in DIS format. We put that into a // datagram and send it. byte[] data = baos.toByteArray(); DatagramPacket packet = new DatagramPacket(data, data.length, destinationIp, PORT); socket.send(packet); } private void sendMessage(short exerciseID, long lastTime, long eventType, EntityID eid, String msg) { // build up the PDU EventReportPdu dp = new EventReportPdu(); dp.setExerciseID(exerciseID); dp.setTimestamp(lastTime); dp.setEventType(eventType); // produce random participant. dp.setOriginatingEntityID(eid); // INSERTING TEXT STRING VariableDatum d = new VariableDatum(); byte[] theBytes = msg.getBytes(); List<OneByteChunk> chunks = new ArrayList<OneByteChunk>(); for (int i = 0; i < theBytes.length; i++) { byte thisB = theBytes[i]; OneByteChunk chunk = new OneByteChunk(); chunk.setOtherParameters(new byte[] {thisB}); chunks.add(chunk); } d.setVariableData(chunks); d.setVariableDatumLength(theBytes.length); d.setVariableDatumID(lastTime); List<VariableDatum> datums = new ArrayList<VariableDatum>(); datums.add(d); dp.setVariableDatums(datums); // and send it try { sendPdu(dp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private Participant randomEntity(Collection<Participant> collection) { int index = (int) (Math.random() * (double) collection.size()); Iterator<Participant> sIter2 = collection.iterator(); Participant res = null; for (int i = 0; i <= index; i++) { res = sIter2.next(); } return res; } public void terminate() { _terminate = true; } private void sendDetonation(Participant firingPlatform, int recipientId, EntityID eid, Map<Integer, Participant> states, long lastTime) { // store the id of the firing platform eid.setEntity(firingPlatform.id); // and remove the recipient states.remove(firingPlatform.id); // hmm, also remove the detonating platform states.remove(recipientId); // build up the PDU DetonationPdu dp = new DetonationPdu(); dp.setExerciseID(exerciseId); dp.setFiringEntityID(eid); dp.setTimestamp(lastTime); // and the location double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(firingPlatform.latVal, firingPlatform.longVal, 0.0); Vector3Float location = new Vector3Float(); location.setX((float) disCoordinates[0]); location.setY((float) disCoordinates[1]); location.setZ((float) disCoordinates[2]); dp.setLocationInEntityCoordinates(location); Vector3Double wLoc = new Vector3Double(); wLoc.setX(firingPlatform.longVal); wLoc.setY(firingPlatform.latVal); wLoc.setZ(0); dp.setLocationInWorldCoordinates(wLoc); // and send it try { sendPdu(dp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(": " + firingPlatform.id + " destroyed " + recipientId); } private void sendCollision(Participant movingPlatform, int recipientId, EntityID movingId, Map<Integer, Participant> states, long lastTime) { EntityID victimE = new EntityID(); victimE.setApplication(movingId.getApplication()); victimE.setEntity(recipientId); victimE.setSite(movingId.getSite()); // store the id of the firing platform movingId.setEntity(movingPlatform.id); // build up the PDU CollisionPdu coll = new CollisionPdu(); coll.setExerciseID(exerciseId); movingId.setEntity(recipientId); coll.setCollidingEntityID(movingId); coll.setTimestamp(lastTime); // and the location double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(movingPlatform.latVal, movingPlatform.longVal, 0.0); Vector3Float location = new Vector3Float(); location.setX((float) disCoordinates[0]); location.setY((float) disCoordinates[1]); location.setZ((float) disCoordinates[2]); coll.setLocation(location); // and send it try { sendPdu(coll); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(": " + movingPlatform.id + " collided with " + recipientId); } }
// $RCSfile: ImportTimeText.java,v $ // @version $Revision: 1.3 $ // $Log: ImportTimeText.java,v $ // Revision 1.3 2005/12/13 09:04:39 Ian.Mayo // Tidying - as recommended by Eclipse // Revision 1.2 2004/11/25 10:24:20 Ian.Mayo // Switch to Hi Res dates // Revision 1.1.1.2 2003/07/21 14:47:53 Ian.Mayo // Re-import Java files to keep correct line spacing // Revision 1.3 2003-03-19 15:37:49+00 ian_mayo // improvements according to IntelliJ inspector // Revision 1.2 2002-05-28 12:28:19+01 ian_mayo // after update // Revision 1.1 2002-05-28 09:12:08+01 ian_mayo // Initial revision // Revision 1.1 2002-04-23 12:29:41+01 ian_mayo // Initial revision // Revision 1.1 2002-02-26 16:36:48+00 administrator // DateFormat object in ImportReplay isn't public, access via static method // Revision 1.0 2001-07-17 08:41:32+01 administrator // Initial revision // Revision 1.3 2001-01-24 11:36:57+00 novatech // setString has changed to setLabel in label // Revision 1.2 2001-01-17 13:23:46+00 novatech // reflect use of -1 as null time, rather than 0 // Revision 1.1 2001-01-03 13:40:46+00 novatech // Initial revision // Revision 1.1.1.1 2000/12/12 20:47:24 ianmayo // initial import of files // Revision 1.2 2000-10-09 13:37:35+01 ian_mayo // Switch stackTrace to go to file // Revision 1.1 2000-09-26 10:57:52+01 ian_mayo // Initial revision package Debrief.ReaderWriter.Replay; import java.util.StringTokenizer; import junit.framework.TestCase; import org.junit.Test; import Debrief.Wrappers.LabelWrapper; import Debrief.Wrappers.Formatters.CoreFormatItemListener; import MWC.GUI.Properties.AttributeTypePropertyEditor; import MWC.Utilities.ReaderWriter.AbstractPlainLineImporter; /** * class to parse a label from a line of text */ final class ImportFixFormatter extends AbstractPlainLineImporter { /* * example: ;FORMAT_FIX: 10_sec_sym SYMBOL NULL NULL TRUE 600000 */ /** * the type for this string */ private final String _myType = ";FORMAT_FIX:"; /** * read in this string and return a Label */ public final Object readThisLine(final String theLine) { // get a stream from the string final StringTokenizer st = new StringTokenizer(theLine); // declare local variables String formatName; String trackName; String symbology; boolean regularTimes; int interval; String attributeType; // skip the comment identifier st.nextToken(); formatName = checkForQuotedName(st).trim(); attributeType = st.nextToken(); // do processing for track name in quotes // trouble - the track name may have been quoted, in which case we will // pull in the remaining fields aswell trackName = checkForQuotedName(st).trim(); // bit of tidying if (trackName.equals("NULL")) { trackName = null; } symbology = st.nextToken(); // bit of tidying if (symbology.equals("NULL")) { symbology = null; } regularTimes = Boolean.parseBoolean(st.nextToken()); interval = Integer.parseInt(st.nextToken()); AttributeTypePropertyEditor pe = new AttributeTypePropertyEditor(); pe.setAsText(attributeType); int attType = (int) pe.getValue(); CoreFormatItemListener cif = new CoreFormatItemListener(formatName, trackName, symbology, interval, regularTimes, attType, true); return cif; } /** * determine the identifier returning this type of annotation */ public final String getYourType() { return _myType; } /** * export the specified shape as a string * * @return the shape in String form * @param theWrapper * the Shape we are exporting */ public final String exportThis(final MWC.GUI.Plottable theWrapper) { final LabelWrapper theLabel = (LabelWrapper) theWrapper; String line = null; line = _myType + " BB "; line = line + MWC.Utilities.TextFormatting.DebriefFormatLocation .toString(theLabel.getLocation()); line = line + theLabel.getLabel(); return line; } /** * indicate if you can export this type of object * * @param val * the object to test * @return boolean saying whether you can do it */ public final boolean canExportThis(final Object val) { boolean res = false; if (val instanceof LabelWrapper) { // also see if there is just the start time specified final LabelWrapper lw = (LabelWrapper) val; if ((lw.getStartDTG() != null) && (lw.getEndDTG() == null)) { // yes, this is a label with only the start time specified, // we can export it res = true; } } return res; } public static class TestMe extends TestCase { @Test public void testRead() { /* * example: */ ImportFixFormatter iff = new ImportFixFormatter(); CoreFormatItemListener res = (CoreFormatItemListener) iff .readThisLine(";FORMAT_FIX: 10_sec_sym SYMBOL NULL NULL TRUE 600000"); assertNotNull(res); assertNull("No track", res.getLayerName()); assertNull("no sym", res.getSymbology()); assertTrue("active", res.getVisible()); assertNotNull("has name", res.getName()); assertEquals("has correct attr", 1, res.getAttributeType()); assertEquals("has correct freq", 600000, res.getInterval().getDate().getTime()); assertTrue("regular intervals", res.getRegularIntervals()); res = (CoreFormatItemListener) iff .readThisLine(";FORMAT_FIX: 10_sec_sym ARROW \"Track One\" @A FALSE 100000"); assertNotNull(res); assertEquals("No track", "Track One", res.getLayerName()); assertNotNull("sym", res.getSymbology()); assertTrue("active", res.getVisible()); assertNotNull("has name", res.getName()); assertEquals("has correct attr", 0, res.getAttributeType()); assertEquals("has correct freq", 100000, res.getInterval().getDate().getTime()); assertFalse("regular intervals", res.getRegularIntervals()); res = (CoreFormatItemListener) iff .readThisLine(";FORMAT_FIX: \"10 arrow\" ARROW \"Track One\" BB FALSE 100000"); assertNotNull(res); assertEquals("No track", "Track One", res.getLayerName()); assertNotNull("sym", res.getSymbology()); assertEquals("correct sym", "BB", res.getSymbology()); assertTrue("active", res.getVisible()); assertNotNull("has name", res.getName()); } } }
package ProjetoPOO.entidades; import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Aluno { private long idBDAluno; private String nome; private int idade; private String telefone; private String rua; private String bairro; private String cidade; private long numMatricula; private String senha; private List<Treino> treinoAlunos; private List<Avaliacao> avaliacaoAlunos; //os relacionamentos MANY TO ONE, recebe tambem o comando: fetch = FetchType.EAGER ??? public Aluno() { } public Aluno(String nome, int idade, String telefone, String rua, String bairro, String cidade, long numMatricula, String senha, List<Avaliacao> avaliacaoAlunos, List<Treino> treinoAlunos) { this.nome = nome; this.idade = idade; this.telefone = telefone; this.rua = rua; this.bairro = bairro; this.cidade = cidade; this.numMatricula = numMatricula; this.senha = senha; this.avaliacaoAlunos = avaliacaoAlunos; this.treinoAlunos = treinoAlunos; } @Id public long getIdBDAluno() { return idBDAluno; } public void setIdBDAluno(long idBDAluno) { this.idBDAluno = idBDAluno; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public int getIdade() { return idade; } public void setIdade(int idade) { this.idade = idade; } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } public String getRua() { return rua; } public void setRua(String rua) { this.rua = rua; } public String getBairro() { return bairro; } public void setBairro(String bairro) { this.bairro = bairro; } public String getCidade() { return cidade; } public void setCidade(String cidade) { this.cidade = cidade; } public long getNumMatricula() { return numMatricula; } public void setNumMatricula(long numMatricula) { this.numMatricula = numMatricula; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } //fetch = FetchType.EAGER -> ele ja pre recarrega os elementos @OneToMany(mappedBy = "aluno", fetch = FetchType.EAGER) public List<Avaliacao> getAvaliacaoAlunos() { return avaliacaoAlunos; } public void setAvaliacaoAlunos(List<Avaliacao> avaliacaoAlunos) { this.avaliacaoAlunos = avaliacaoAlunos; } @OneToMany(mappedBy = "aluno", fetch = FetchType.EAGER) public List<Treino> getTreinoAlunos() { return treinoAlunos; } public void setTreinoAlunos(List<Treino> treinoAlunos) { this.treinoAlunos = treinoAlunos; } }
package cyber.dojo; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class CountCoinsTest { //[1, 5, 10, 25] @Test public void should_return_1_when_count_given_1() { //given int input = 1; //when int result = CountCoins.count(input); int expected = 1; //then assertThat(result, is(expected)); } @Test public void should_return_1_when_count_given_3() { //given int input = 3; //when int result = CountCoins.count(input); int expected = 1; //then assertThat(result, is(expected)); } @Test public void should_return_2_when_count_given_5() { //given int input = 5; //when int result = CountCoins.count(input); int expected = 2; //then assertThat(result, is(expected)); } @Test public void should_return_2_when_count_given_7() { //given int input = 7; //when int result = CountCoins.count(input); int expected = 2; //then assertThat(result, is(expected)); } @Test public void should_return_4_when_count_given_10() { //given int input = 10; //when int result = CountCoins.count(input); int expected = 4; //then assertThat(result, is(expected)); } @Test public void should_return_4_when_count_given_13() { //given int input = 13; //when int result = CountCoins.count(input); int expected = 4; //then assertThat(result, is(expected)); } @Test public void should_return_6_when_count_given_15() { //given int input = 15; //when int result = CountCoins.count(input); int expected = 6; //then assertThat(result, is(expected)); } @Test public void should_return_9_when_count_given_20() { //given int input = 20; //when int result = CountCoins.count(input); int expected = 9; //then assertThat(result, is(expected)); } @Test public void should_return_13_when_count_given_25() { //given int input = 25; //when int result = CountCoins.count(input); int expected = 13; //then assertThat(result, is(expected)); } @Test public void should_return_18_when_count_given_30() { //given int input = 30; //when int result = CountCoins.count(input); int expected = 18; //then assertThat(result, is(expected)); } @Test public void should_return_24_when_count_given_35() { //given int input = 35; //when int result = CountCoins.count(input); int expected = 24; //then assertThat(result, is(expected)); } @Test public void printResult_given_100() { System.out.println(CountCoins.count(100)); } @Test public void result_test() { List<Integer> numbers = Arrays.asList(1, 5, 7, 10, 15, 17, 20, 25, 30, 33, 35, 40); for (Integer integer : numbers) { int count = 0; for (int a = 0; a <= 50; a++) { for (int b = 0; b <= 50; b++) { for (int c = 0; c <= 50; c++) { for (int d = 0; d <= 50; d++) { if (a + b * 5 + c * 10 + d * 25 == integer) { count++; } } } } } System.out.println("number=" + integer + ":=" + count); } } }
package innovimax.mixthem; import innovimax.mixthem.arguments.Rule; import java.util.List; /** * @author Innovimax * @version 1.0 */ public class RuleRun { final private int testId; final private List<String> params; public RuleRun(List<String> params) { this(-1, params); } public RuleRun(int testId, List<String> params) { this.testId = testId; this.params = params; } public boolean accept(int testId) { if (this.testId == -1) { return true; } else { return this.testId == testId; } } public List<String> getParams() { return this.params; } }
package org.takes.misc; import java.util.ArrayList; import java.util.List; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; /** * Test case for {@link Concat}. * * @author Jason Wong (super132j@yahoo.com) * @version $Id$ * @since 0.15.2 */ public final class ConcatTest { /** * Concat can concatenate. */ @Test public void concatenates() { final List<String> alist = new ArrayList<String>(2); final String aone = "a1"; final String atwo = "a2"; alist.add(aone); alist.add(atwo); final List<String> blist = new ArrayList<String>(2); final String bone = "b1"; final String btwo = "b2"; blist.add(bone); blist.add(btwo); MatcherAssert.assertThat( new Concat<String>(alist, blist), Matchers.hasItems(aone, atwo, bone, btwo) ); } /** * Concat can concatenate with empty list. */ @Test public void concatenatesWithEmptyList() { final List<String> alist = new ArrayList<String>(2); final String aone = "an1"; final String atwo = "an2"; alist.add(aone); alist.add(atwo); final List<String> blist = new ArrayList<String>(0); MatcherAssert.assertThat( new Concat<String>(alist, blist), Matchers.hasItems(aone, atwo) ); MatcherAssert.assertThat( new Concat<String>(alist, blist), Matchers.not(Matchers.hasItems("")) ); MatcherAssert.assertThat( new Concat<String>(blist, blist), Matchers.emptyIterable() ); } }
package test.blog.distrib; import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.Set; import org.junit.Test; import blog.common.Util; import blog.common.numerical.MatrixFactory; import blog.common.numerical.MatrixLib; import blog.distrib.GEM; public class TestGEM { private double lambda; private int truncation, truncation2; private HashMap<MatrixLib, Double> probVals; private final double ERROR = 10e-5; public TestGEM() { // Create a GEM with a parameter lambda and a stop point parameter lambda = 2.0; truncation = 3; truncation2 = 100; // Compute the pdf of this GEM at particular points probVals = new HashMap<MatrixLib, Double>(); probVals.put( MatrixFactory.fromArray(new double[][] { { 0.4 }, { 0.3 }, { 0.3 } }), 2.0); probVals.put( MatrixFactory.fromArray(new double[][] { { 0.5 }, { 0.2 }, { 0.3 } }), 2.4); } public void testGEM(GEM gem) { Set<MatrixLib> points = probVals.keySet(); for (MatrixLib point : points) { assertEquals(probVals.get(point), gem.getProb(point), ERROR); assertEquals(Math.log(probVals.get(point)), gem.getLogProb(point), ERROR); } } /* * PDF test: lambda = 2.0, truncation = 3; */ @Test public void testPDF1() { GEM gem = new GEM(); gem.setParams(lambda, truncation); testGEM(gem); } @Test(expected = IllegalArgumentException.class) public void testInsufficientArguments() { GEM gem = new GEM(); gem.setParams(lambda, null); gem.sampleVal(); } @Test(expected = IllegalArgumentException.class) public void testInsufficientArguments2() { GEM gem = new GEM(); gem.setParams(null, truncation); gem.sampleVal(); } /* * Generate 10 samples with lambda = 2.0 and truncation = 100. */ @Test public void testSample() { Util.initRandom(false); GEM gem = new GEM(); gem.setParams(lambda, truncation2); for (int i = 0; i < 10; i++) System.out.println(gem.sample_value()); } }
package org.xnap.commons.i18n; import java.util.Locale; import java.util.MissingResourceException; import junit.framework.TestCase; import org.xnap.commons.i18n.testpackage.MockResourceBundle; /** * @author Steffen Pingel * @author Felix Berger */ public class I18nTest extends TestCase { public static final String BASENAME = "org.xnap.commons.i18n.Messages"; private I18n i18nDE; private I18n i18nEN; protected void setUp() throws Exception { try { i18nDE = new I18n(BASENAME, Locale.GERMAN, getClass().getClassLoader()); } catch (MissingResourceException e) { throw new RuntimeException( "Please make sure you run 'mvn org.xnap.commons:maven-gettext-plugin:dist' before executing tests"); } i18nEN = new I18n(BASENAME, Locale.ENGLISH, getClass().getClassLoader()); } protected void tearDown() throws Exception { } public void testTr() { assertEquals("Haus", i18nDE.tr("house")); assertEquals("Maus", i18nDE.tr("mouse")); assertEquals("Automatisch", i18nDE.tr("Automatic")); assertEquals("Erg\u00e4nzung", i18nDE.tr("Completion")); } public void testTr1() { assertEquals("House Nr. 2 ", i18nEN.tr("House Nr. {0} ", new Integer(2))); assertEquals("0", i18nEN.tr("{0}", "0")); } public void testTr2() { assertEquals("Foo bar foo", i18nEN.tr("Foo {1} {0}", "foo", "bar")); assertEquals("Foo foo bar", i18nEN.tr("Foo {0} {1}", "foo", "bar")); } public void testTr3() { assertEquals("Foo bar baz foo", i18nEN.tr("Foo {1} {2} {0}", "foo", "bar", "baz")); assertEquals("Foo foo bar baz", i18nEN.tr("Foo {0} {1} {2}", "foo", "bar", "baz")); } public void testTr4() { assertEquals("Foo bar baz boing foo", i18nEN.tr("Foo {1} {2} {3} {0}", "foo", "bar", "baz", "boing")); assertEquals("Foo foo bar baz boing", i18nEN.tr("Foo {0} {1} {2} {3}", "foo", "bar", "baz", "boing")); } public void testMarktr() { assertEquals(I18n.marktr("Foo"), "Foo"); } public void testTrc() { assertEquals("chat", i18nEN.trc("noun", "chat")); assertEquals("chat", i18nEN.trc("verb", "chat")); assertEquals("Chat", i18nDE.trc("noun", "chat")); assertEquals("Chatten", i18nDE.trc("verb", "chat")); } public void testSetLocale() { I18n i18n = new I18n(new MockResourceBundle()); assertFalse(i18n.setLocale(Locale.FRENCH)); i18n.setResources(MockResourceBundle.class.getName(), Locale.GERMAN, MockResourceBundle.class.getClassLoader()); assertTrue(i18n.setLocale(Locale.FRENCH)); } public void testSetResources() { try { new I18n(null); fail("NullPointerException expected"); } catch (NullPointerException npe) {} String baseName = MockResourceBundle.class.getName(); try { i18nDE.setResources(null, Locale.GERMAN, MockResourceBundle.class.getClassLoader()); fail("NullPointerException expected"); } catch (NullPointerException npe) {} try { i18nDE.setResources(baseName, null, MockResourceBundle.class.getClassLoader()); fail("NullPointerException expected"); } catch (NullPointerException npe) {} try { i18nDE.setResources(baseName, Locale.GERMAN, null); fail("NullPointerException expected"); } catch (NullPointerException npe) {} } public void testSetSourceCodeLocale() { i18nDE.setSourceCodeLocale(Locale.GERMAN); assertEquals("chat", i18nDE.trc("verb", "chat")); i18nDE.setSourceCodeLocale(Locale.ENGLISH); assertEquals("Chatten", i18nDE.trc("verb", "chat")); try { i18nDE.setSourceCodeLocale(null); fail("null pointer exception expected"); } catch (NullPointerException npe) {} } public void testTrnEN() { assertEquals("Foo", i18nEN.trn("Foo", "{0} Bars", 1)); assertEquals("{0} Bars", i18nEN.trn("Foo", "{0} Bars", 2)); assertEquals("2 Bars", i18nEN.trn("Foo", "{0} Bars", 2, new Integer(2))); } public void testTrnDE() { assertEquals("Datei", i18nDE.trn("File", "{0} Files", 1, new Integer(1))); assertEquals("2 Dateien", i18nDE.trn("File", "{0} Files", 2, new Integer(2))); } public void testTrn1() { assertEquals("Foo foo ", i18nEN.trn("Foo {0} ", "Foos {0}", 1, "foo")); } public void testTrn2() { assertEquals("Foo bar foo", i18nEN.trn("Foo {1} {0}", "Foos", 1, "foo", "bar")); assertEquals("Foo foo bar", i18nEN.trn("Foo {0} {1}", "Foos", 1, "foo", "bar")); } public void testTrn3() { assertEquals("Foo bar baz foo", i18nEN.trn("Foo {1} {2} {0}", "Foos", 1, "foo", "bar", "baz")); assertEquals("Foo foo bar baz", i18nEN.trn("Foo {0} {1} {2}", "Foos", 1, "foo", "bar", "baz")); } public void testTrn4() { assertEquals("Foo bar baz boing foo", i18nEN .trn("Foo {1} {2} {3} {0}", "Foos", 1, "foo", "bar", "baz", "boing")); assertEquals("Foo foo bar baz boing", i18nEN .trn("Foo {0} {1} {2} {3}", "Foos", 1, "foo", "bar", "baz", "boing")); } public void testSetEmptyResources() { // this should load the empty resource bundle // we have to set the default to italian too, so // ResourceBundle.getBundle(...) doesn't fall back on the default locale // which might be there Locale.setDefault(Locale.ITALIAN); assertTrue(i18nDE.setLocale(Locale.ITALIAN)); assertEquals("value", i18nDE.tr("value")); } public void testTrcReturnsTextWhenTranslationNotFound() { assertEquals("baobab", i18nDE.trc("dont translate to German", "baobab")); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tonegod.gui.controls.buttons; import com.jme3.font.BitmapFont; import com.jme3.font.BitmapText; import com.jme3.font.LineWrapMode; import com.jme3.font.Rectangle; import com.jme3.input.KeyInput; import com.jme3.input.event.KeyInputEvent; import com.jme3.input.event.MouseButtonEvent; import com.jme3.input.event.MouseMotionEvent; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector2f; import com.jme3.math.Vector4f; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Spatial; import com.jme3.scene.control.Control; import com.jme3.texture.Texture; import tonegod.gui.core.Element; import tonegod.gui.core.Screen; import tonegod.gui.core.utils.BitmapTextUtil; import tonegod.gui.effects.Effect; import tonegod.gui.listeners.KeyboardListener; import tonegod.gui.listeners.MouseButtonListener; import tonegod.gui.listeners.MouseFocusListener; import tonegod.gui.listeners.TabFocusListener; /** * * @author t0neg0d */ public abstract class Button extends Element implements Control, MouseButtonListener, MouseFocusListener, KeyboardListener, TabFocusListener { String hoverSound, pressedSound; boolean useHoverSound, usePressedSound; float hoverSoundVolume, pressedSoundVolume; protected Element icon; protected Texture hoverImg = null, pressedImg = null; protected ColorRGBA hoverFontColor = null, pressedFontColor = null; protected boolean isToggleButton = false; protected boolean isToggled = false; private Spatial spatial; protected boolean isStillPressed = false; private boolean useInterval = false; private float intervalsPerSecond = 4; protected float trackInterval = (4/1000), currentTrack = 0; protected boolean initClickPause = false; protected float initClickInterval = 0.25f, currentInitClickTrack = 0; protected RadioButtonGroup radioButtonGroup = null; protected boolean isRadioButton = false; private boolean isEnabled = true; private ColorRGBA originalFontColor; /** * Creates a new instance of the Button control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element */ public Button(Screen screen, String UID, Vector2f position) { this(screen, UID, position, screen.getStyle("Button").getVector2f("defaultSize"), screen.getStyle("Button").getVector4f("resizeBorders"), screen.getStyle("Button").getString("defaultImg") ); } /** * Creates a new instance of the Button control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element */ public Button(Screen screen, String UID, Vector2f position, Vector2f dimensions) { this(screen, UID, position, dimensions, screen.getStyle("Button").getVector4f("resizeBorders"), screen.getStyle("Button").getString("defaultImg") ); } /** * Creates a new instance of the Button control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element * @param resizeBorders A Vector4f containg the border information used when resizing the default image (x = N, y = W, z = E, w = S) * @param defaultImg The default image to use for the Slider's track */ public Button(Screen screen, String UID, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String defaultImg) { super(screen, UID, position, dimensions, resizeBorders, defaultImg); this.setScaleNS(false); this.setScaleEW(false); this.setFontSize(screen.getStyle("Button").getFloat("fontSize")); this.setFontColor(screen.getStyle("Button").getColorRGBA("fontColor")); this.setTextVAlign(BitmapFont.VAlign.valueOf(screen.getStyle("Button").getString("textVAlign"))); this.setTextAlign(BitmapFont.Align.valueOf(screen.getStyle("Button").getString("textAlign"))); this.setTextWrap(LineWrapMode.valueOf(screen.getStyle("Button").getString("textWrap"))); this.setMinDimensions(dimensions.clone()); if (screen.getStyle("Button").getString("hoverImg") != null) { setButtonHoverInfo( screen.getStyle("Button").getString("hoverImg"), screen.getStyle("Button").getColorRGBA("hoverColor") ); } if (screen.getStyle("Button").getString("pressedImg") != null) { setButtonPressedInfo( screen.getStyle("Button").getString("pressedImg"), screen.getStyle("Button").getColorRGBA("pressedColor") ); } originalFontColor = fontColor.clone(); hoverSound = screen.getStyle("Button").getString("hoverSound"); useHoverSound = screen.getStyle("Button").getBoolean("useHoverSound"); hoverSoundVolume = screen.getStyle("Button").getFloat("hoverSoundVolume"); pressedSound = screen.getStyle("Button").getString("pressedSound"); usePressedSound = screen.getStyle("Button").getBoolean("usePressedSound"); pressedSoundVolume = screen.getStyle("Button").getFloat("pressedSoundVolume"); populateEffects("Button"); } public void setIsEnabled(boolean isEnabled) { this.isEnabled = isEnabled; if (!isEnabled) { Effect effect = getEffect(Effect.EffectEvent.Press); if (effect != null) { effect.setBlendImage(pressedImg); screen.getEffectManager().applyEffect(effect); } if (pressedFontColor != null) { setFontColor(pressedFontColor); } } else { Effect effect = getEffect(Effect.EffectEvent.Press); if (effect != null) { effect.setBlendImage(getElementTexture()); screen.getEffectManager().applyEffect(effect); } if (originalFontColor != null) { setFontColor(originalFontColor); } } } public boolean getIsEnabled() { return this.isEnabled; } /** * Clears current hover and pressed images set by Style defines */ public void clearAltImages() { setButtonHoverInfo(null, null); setButtonPressedInfo(null, null); } /** * Sets if the button is to interact as a Toggle Button * Click once to activate / Click once to deactivate * * @param isToggleButton boolean */ public void setIsToggleButton(boolean isToggleButton) { this.isToggleButton = isToggleButton; } /** * Returns if the Button is flagged as a Toggle Button * * @return boolean isToggleButton */ public boolean getIsToggleButton() { return this.isToggleButton; } /** * Sets if the button is to interact as a Radio Button * Click once to activate - stays active * * @param isRadioButton boolean */ public void setIsRadioButton(boolean isRadioButton) { this.isRadioButton = isRadioButton; } /** * Returns if the Button is flagged as a Toggle Button * * @return boolean isRadioButton */ public boolean getIsRadioButton() { return this.isRadioButton; } /** * Set a toggle button state to toggled/untoggled * @param isToggled boolean */ public void setIsToggled(boolean isToggled) { this.isToggled = isToggled; if (pressedImg != null && isToggled) { Effect effect = getEffect(Effect.EffectEvent.Press); if (effect != null) { effect.setBlendImage(pressedImg); screen.getEffectManager().applyEffect(effect); } if (pressedFontColor != null) { setFontColor(pressedFontColor); } } else { Effect effect = getEffect(Effect.EffectEvent.Press); if (effect != null) { effect.setBlendImage(getElementTexture()); screen.getEffectManager().applyEffect(effect); } if (originalFontColor != null) { setFontColor(originalFontColor); } } MouseButtonEvent evtd = new MouseButtonEvent(0,true,0,0); MouseButtonEvent evtu = new MouseButtonEvent(0,false,0,0); onButtonMouseLeftDown(evtd, isToggled); onButtonMouseLeftUp(evtu, isToggled); if (radioButtonGroup != null) { if (isToggled) radioButtonGroup.setSelected(this); } evtu.setConsumed(); evtd.setConsumed(); } /** * Returns the current toggle state of the Button if the Button has been flagged as * isToggle * @return boolean isToggle */ public boolean getIsToggled() { return this.isToggled; } /** * Sets the texture image path and color to use when the button has mouse focus * @param pathHoverImg String path to image for mouse focus event * @param hoverFontColor ColorRGBA to use for mouse focus event */ public final void setButtonHoverInfo(String pathHoverImg, ColorRGBA hoverFontColor) { if (pathHoverImg != null) { this.hoverImg = app.getAssetManager().loadTexture(pathHoverImg); this.hoverImg.setMinFilter(Texture.MinFilter.BilinearNoMipMaps); this.hoverImg.setMagFilter(Texture.MagFilter.Nearest); this.hoverImg.setWrap(Texture.WrapMode.Repeat); } if (hoverFontColor != null) { this.hoverFontColor = hoverFontColor; } } /** * Returns the Texture used when button has mouse focus * * @return Texture */ public Texture getButtonHoverImg() { return this.hoverImg; } /** * Sets the image and font color to use when the button is depressed * @param pathPressedImg Path to the image for pressed state * @param pressedFontColor ColorRGBA to use for pressed state */ public final void setButtonPressedInfo(String pathPressedImg, ColorRGBA pressedFontColor) { if (pathPressedImg != null) { this.pressedImg = app.getAssetManager().loadTexture(pathPressedImg); this.pressedImg.setMinFilter(Texture.MinFilter.BilinearNoMipMaps); this.pressedImg.setMagFilter(Texture.MagFilter.Nearest); this.pressedImg.setWrap(Texture.WrapMode.Repeat); } if (pressedFontColor != null) { this.pressedFontColor = pressedFontColor; } } /** * Returns the texture to be used when the button is depressed * * @return Texture */ public Texture getButtonPressedImg() { return this.pressedImg; } /** * If called, an overlay icon is added to the button. This icon is centered by default * * @param width width to display icon * @param height to display icon * @param texturePath The path of the image to use as the icon overlay */ public void setButtonIcon(float width, float height, String texturePath) { if (icon != null) { if (icon.getParent() != null) { elementChildren.remove(icon.getUID()); icon.removeFromParent(); } } // Texture tex = app.getAssetManager().loadTexture(texturePath); // float imgWidth = tex.getImage().getWidth(); // tex = null; icon = new Element( screen, this.getUID() + ":btnIcon", new Vector2f((getWidth()/2)-(width/2),(getHeight()/2)-(height/2)), new Vector2f(width,height), new Vector4f(0,0,0,0), texturePath ); icon.setIgnoreMouse(true); icon.setDockS(true); icon.setDockS(true); icon.setScaleEW(false); icon.setScaleNS(false); this.addChild(icon); } @Override public void onMouseLeftPressed(MouseButtonEvent evt) { if (isEnabled) { if (isToggleButton) { if (isToggled) { if (!isRadioButton) isToggled = false; } else { isToggled = true; } } if (pressedImg != null) { Effect effect = getEffect(Effect.EffectEvent.Press); if (effect != null) { if (usePressedSound && screen.getUseUIAudio()) { effect.setAudioFile(pressedSound); effect.setAudioVolume(pressedSoundVolume); } effect.setBlendImage(pressedImg); screen.getEffectManager().applyEffect(effect); } } if (pressedFontColor != null) { setFontColor(pressedFontColor); } isStillPressed = true; initClickPause = true; currentInitClickTrack = 0; onButtonMouseLeftDown(evt, isToggled); } evt.setConsumed(); } @Override public void onMouseLeftReleased(MouseButtonEvent evt) { if (isEnabled) { if (!isToggleButton) { if (getHasFocus()) { Effect effect = getEffect(Effect.EffectEvent.LoseFocus); if (effect != null) { effect.setBlendImage(getElementTexture()); screen.getEffectManager().applyEffect(effect); } if (hoverImg != null) { // screen.getEffectManager().removeEffect(this); Effect effect2 = getEffect(Effect.EffectEvent.Hover); if (effect2 != null) { effect2.setBlendImage(hoverImg); screen.getEffectManager().applyEffect(effect2); } } if (hoverFontColor != null) { setFontColor(hoverFontColor); } } else { Effect effect = getEffect(Effect.EffectEvent.LoseFocus); if (effect != null) { effect.setBlendImage(getElementTexture()); screen.getEffectManager().applyEffect(effect); } if (originalFontColor != null) { setFontColor(originalFontColor); } } } else { if (!isToggled) { if (hoverImg != null) { Effect effect = getEffect(Effect.EffectEvent.LoseFocus); if (effect != null) { effect.setBlendImage(getElementTexture()); screen.getEffectManager().applyEffect(effect); } Effect effect2 = getEffect(Effect.EffectEvent.Hover); if (effect2 != null) { effect2.setBlendImage(hoverImg); screen.getEffectManager().applyEffect(effect2); } } if (hoverFontColor != null) { setFontColor(hoverFontColor); } } } isStillPressed = false; initClickPause = false; currentInitClickTrack = 0; onButtonMouseLeftUp(evt, isToggled); if (radioButtonGroup != null) radioButtonGroup.setSelected(this); } evt.setConsumed(); } public void setRadioButtonGroup(RadioButtonGroup radioButtonGroup) { this.radioButtonGroup = radioButtonGroup; this.isToggleButton = true; this.isRadioButton = true; } @Override public void onMouseRightPressed(MouseButtonEvent evt) { if (isEnabled) { onButtonMouseRightDown(evt, isToggled); if (screen.getUseToolTips()) { if (getToolTipText() != null) { // screen.setToolTip(null); } } } evt.setConsumed(); } @Override public void onMouseRightReleased(MouseButtonEvent evt) { if (isEnabled) { onButtonMouseRightUp(evt, isToggled); } evt.setConsumed(); } @Override public void onGetFocus(MouseMotionEvent evt) { if (isEnabled) { if (!getHasFocus()) { if (!isToggled) { if (hoverImg != null) { Effect effect = getEffect(Effect.EffectEvent.Hover); if (effect != null) { if (useHoverSound && screen.getUseUIAudio()) { effect.setAudioFile(hoverSound); effect.setAudioVolume(hoverSoundVolume); } effect.setBlendImage(hoverImg); screen.getEffectManager().applyEffect(effect); } } if (hoverFontColor != null) { setFontColor(hoverFontColor); } } screen.setCursor(Screen.CursorType.HAND); onButtonFocus(evt); if (screen.getUseToolTips()) { if (getToolTipText() != null) { // screen.setToolTip(getToolTipText()); } } } setHasFocus(true); } } @Override public void onLoseFocus(MouseMotionEvent evt) { if (isEnabled) { if (getHasFocus()) { if (!isToggled) { Effect effect = getEffect(Effect.EffectEvent.LoseFocus); if (effect != null) { effect.setBlendImage(getElementTexture()); screen.getEffectManager().applyEffect(effect); } setFontColor(originalFontColor); } screen.setCursor(Screen.CursorType.POINTER); onButtonLostFocus(evt); /* if (screen.getUseToolTips()) { if (getToolTipText() != null) { screen.setToolTip(null); } } */ } setHasFocus(false); } } /** * Enables/disbale hover effect sound * @param useHoverSound */ public void setUseButtonHoverSound(boolean useHoverSound) { this.useHoverSound = useHoverSound; } /** * Enable/disable pressed effect sound * @param usePressedSound */ public void setUseButtonPressedSound(boolean usePressedSound) { this.usePressedSound = usePressedSound; } public abstract void onButtonMouseLeftDown(MouseButtonEvent evt, boolean toggled); public abstract void onButtonMouseRightDown(MouseButtonEvent evt, boolean toggled); public abstract void onButtonMouseLeftUp(MouseButtonEvent evt, boolean toggled); public abstract void onButtonMouseRightUp(MouseButtonEvent evt, boolean toggled); public abstract void onButtonFocus(MouseMotionEvent evt); public abstract void onButtonLostFocus(MouseMotionEvent evt); /** * Abstract method for handling interval updates while the button is still pressed * * NOTE: This is only called if the button's setInterval method has been previously called */ public void onButtonStillPressedInterval() { } /** * Returns if the button is still pressed * @return boolean */ public boolean getIsStillPressed() { return this.isStillPressed; } @Override public Control cloneForSpatial(Spatial spatial) { return this; } @Override public void setSpatial(Spatial spatial) { this.spatial = spatial; } @Override public void render(RenderManager rm, ViewPort vp) { } @Override public void update(float tpf) { if (isEnabled) { if (useInterval && isStillPressed) { if (initClickPause) { currentInitClickTrack += tpf; if (currentInitClickTrack >= initClickInterval) { initClickPause = false; currentInitClickTrack = 0; } } else { currentTrack += tpf; if (currentTrack >= trackInterval) { onButtonStillPressedInterval(); currentTrack = 0; } } } } } /** * This method registers the button as a JME Control creating an interval event to be * processed every time the interval limit has been reached. * * See onButtonStillPressedInterval() * * @param intervalsPerSecond The number of calls to onButtonStillPressedInterval per second. */ public void setInterval(float intervalsPerSecond) { if (intervalsPerSecond > 0) { this.useInterval = true; this.intervalsPerSecond = intervalsPerSecond; this.trackInterval = (float)(1/intervalsPerSecond); this.addControl(this); } else { this.useInterval = false; this.intervalsPerSecond = intervalsPerSecond; this.removeControl(Button.class); } } // Tab focus @Override public void setTabFocus() { screen.setKeyboardElemeent(this); Effect effect = getEffect(Effect.EffectEvent.TabFocus); if (effect != null) { // System.out.println(getUID() + ": Effect Found"); effect.setColor(ColorRGBA.DarkGray); screen.getEffectManager().applyEffect(effect); } } @Override public void resetTabFocus() { screen.setKeyboardElemeent(null); Effect effect = getEffect(Effect.EffectEvent.LoseTabFocus); if (effect != null) { effect.setColor(ColorRGBA.White); screen.getEffectManager().applyEffect(effect); } } // Default keyboard interaction @Override public void onKeyPress(KeyInputEvent evt) { if (evt.getKeyCode() == KeyInput.KEY_SPACE) { onMouseLeftPressed(new MouseButtonEvent(0,true,0,0)); } } @Override public void onKeyRelease(KeyInputEvent evt) { if (evt.getKeyCode() == KeyInput.KEY_SPACE) { onMouseLeftReleased(new MouseButtonEvent(0,false,0,0)); } } @Override public void setText(String text) { this.text = text; if (textElement == null) { textElement = new BitmapText(font, false); textElement.setBox(new Rectangle(0,0,getDimensions().x,getDimensions().y)); } textElement.setLineWrapMode(textWrap); textElement.setAlignment(textAlign); textElement.setVerticalAlignment(textVAlign); textElement.setSize(fontSize); textElement.setColor(fontColor); if (textVAlign == BitmapFont.VAlign.Center) { textElement.setVerticalAlignment(BitmapFont.VAlign.Top); centerTextVertically(text); } textElement.setText(text); updateTextElement(); if (textElement.getParent() == null) { this.attachChild(textElement); // textElement.move(0,0,getNextZOrder()); } } /** * Fix for BitmapFont.VAlign * @param text */ private void centerTextVertically(String text) { float height = BitmapTextUtil.getTextLineHeight(this, text); setTextPosition(getTextPosition().x, getHeight()/2-((height-(height*.1f))/2)); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tonegod.gui.controls.text; import com.jme3.font.BitmapFont; import com.jme3.font.BitmapText; import com.jme3.font.LineWrapMode; import com.jme3.font.Rectangle; import com.jme3.input.KeyInput; import com.jme3.input.event.KeyInputEvent; import com.jme3.input.event.MouseMotionEvent; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.FastMath; import com.jme3.math.Vector2f; import com.jme3.math.Vector4f; import java.util.ArrayList; import java.util.List; import tonegod.gui.core.Element; import tonegod.gui.core.Screen; import tonegod.gui.core.utils.BitmapTextUtil; import tonegod.gui.effects.Effect; import tonegod.gui.listeners.KeyboardListener; import tonegod.gui.listeners.MouseFocusListener; import tonegod.gui.listeners.TabFocusListener; /** * * @author t0neg0d */ public class TextField extends Element implements KeyboardListener, TabFocusListener, MouseFocusListener { public static enum Type { DEFAULT, ALPHA, ALPHA_NOSPACE, NUMERIC, ALPHANUMERIC, ALPHANUMERIC_NOSPACE, EXCLUDE_SPECIAL, EXCLUDE_CUSTOM, INCLUDE_CUSTOM }; private String validateAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "; private String validateAlphaNoSpace = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private String validateNumeric = "0123456789."; private String validateSpecChar = "`~!@ private String validateCustom = ""; private String testString = "Gg|/X"; private Element caret; private Material caretMat; protected int caretIndex = 0, head = 0, tail = 0, rangeHead = -1, rangeTail = -1; protected List<String> textFieldText = new ArrayList(); protected String finalText = "", visibleText = "", textRangeText = ""; protected BitmapText widthTest; private boolean hasTabFocus = false; protected float caretX = 0; private char searchStr = ' '; private Type type = Type.DEFAULT; private boolean ctrl = false, shift = false, alt = false; private boolean isEnabled = true; /** * Creates a new instance of the TextField control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element */ public TextField(Screen screen, String UID, Vector2f position) { this(screen, UID, position, screen.getStyle("TextField").getVector2f("defaultSize"), screen.getStyle("TextField").getVector4f("resizeBorders"), screen.getStyle("TextField").getString("defaultImg") ); } /** * Creates a new instance of the TextField control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element */ public TextField(Screen screen, String UID, Vector2f position, Vector2f dimensions) { this(screen, UID, position, dimensions, screen.getStyle("TextField").getVector4f("resizeBorders"), screen.getStyle("TextField").getString("defaultImg") ); } /** * Creates a new instance of the TextField control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element * @param resizeBorders A Vector4f containg the border information used when resizing the default image (x = N, y = W, z = E, w = S) * @param defaultImg The default image to use for the Slider's track */ public TextField(Screen screen, String UID, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String defaultImg) { super(screen, UID, position, dimensions, resizeBorders, defaultImg); this.setScaleEW(true); this.setScaleNS(false); this.setDockN(true); this.setDockW(true); float padding = screen.getStyle("TextField").getFloat("textPadding"); this.setFontSize(screen.getStyle("TextField").getFloat("fontSize")); this.setTextPadding(padding); this.setTextWrap(LineWrapMode.valueOf(screen.getStyle("TextField").getString("textWrap"))); this.setTextAlign(BitmapFont.Align.valueOf(screen.getStyle("TextField").getString("textAlign"))); this.setTextVAlign(BitmapFont.VAlign.valueOf(screen.getStyle("TextField").getString("textVAlign"))); this.setMinDimensions(dimensions.clone()); caret = new Element(screen, UID + ":Caret", new Vector2f(padding,padding), new Vector2f(dimensions.x-(padding*2), dimensions.y-(padding*2)), new Vector4f(0,0,0,0), null); caretMat = caret.getMaterial().clone(); caretMat.setBoolean("IsTextField", true); caretMat.setTexture("ColorMap", null); caretMat.setColor("Color", getFontColor()); caret.setLocalMaterial(caretMat); caret.setIgnoreMouse(true); // caret.setlockToParentBounds(true); caret.setScaleEW(true); caret.setScaleNS(false); caret.setDockS(true); caret.setDockW(true); setTextFieldFontColor(screen.getStyle("TextField").getColorRGBA("fontColor")); this.addChild(caret); this.setText(""); populateEffects("TextField"); } // Validation public void setType(Type type) { this.type = type; } public Type getType() { return this.type; } public void setCustomValidation(String grabBag) { validateCustom = grabBag; } public int parseInt() throws NumberFormatException { return Integer.parseInt(getText()); } public float parseFloat() throws NumberFormatException { return Float.parseFloat(getText()); } public short parseShort() throws NumberFormatException { return Short.parseShort(getText()); } public double parseDouble() throws NumberFormatException { return Double.parseDouble(getText()); } public long parseLong() throws NumberFormatException { return Long.parseLong(getText()); } // Interaction @Override public void onKeyPress(KeyInputEvent evt) { if (evt.getKeyCode() == KeyInput.KEY_LMETA || evt.getKeyCode() == KeyInput.KEY_RMETA || evt.getKeyCode() == KeyInput.KEY_F1 || evt.getKeyCode() == KeyInput.KEY_F2 || evt.getKeyCode() == KeyInput.KEY_F3 || evt.getKeyCode() == KeyInput.KEY_F4 || evt.getKeyCode() == KeyInput.KEY_F5 || evt.getKeyCode() == KeyInput.KEY_F6 || evt.getKeyCode() == KeyInput.KEY_F7 || evt.getKeyCode() == KeyInput.KEY_F8 || evt.getKeyCode() == KeyInput.KEY_F9 || evt.getKeyCode() == KeyInput.KEY_CAPITAL || evt.getKeyCode() == KeyInput.KEY_ESCAPE || evt.getKeyCode() == KeyInput.KEY_TAB) { } else if (evt.getKeyCode() == KeyInput.KEY_LCONTROL || evt.getKeyCode() == KeyInput.KEY_RCONTROL) { ctrl = true; } else if (evt.getKeyCode() == KeyInput.KEY_LSHIFT || evt.getKeyCode() == KeyInput.KEY_RSHIFT) { shift = true; } else if (evt.getKeyCode() == KeyInput.KEY_LMENU || evt.getKeyCode() == KeyInput.KEY_RMENU) { alt = true; } else if (evt.getKeyCode() == KeyInput.KEY_BACK) { if (caretIndex > 0) { textFieldText.remove(caretIndex-1); caretIndex } // updateTextElement(); } else if (evt.getKeyCode() == KeyInput.KEY_LEFT) { if (caretIndex > 0) { if (!ctrl) caretIndex else caretIndex = finalText.substring(0,caretIndex-1).lastIndexOf(" ")+1; if (caretIndex < 0) caretIndex = 0; if (!shift) { resetTextRange(); setTextRangeStart(caretIndex); } else { setTextRangeEnd(caretIndex); } } } else if (evt.getKeyCode() == KeyInput.KEY_RIGHT) { if (caretIndex < textFieldText.size()) { if (!ctrl) caretIndex++; else { if (finalText.substring(caretIndex+1, finalText.length()).indexOf(" ") != -1) caretIndex += finalText.substring(caretIndex+1, finalText.length()).indexOf(" ")+2; else caretIndex = finalText.length(); } if (caretIndex > finalText.length()) caretIndex = finalText.length(); if (!shift) { resetTextRange(); setTextRangeStart(caretIndex); } else { setTextRangeEnd(caretIndex); } } } else if (evt.getKeyCode() == KeyInput.KEY_END || evt.getKeyCode() == KeyInput.KEY_NEXT || evt.getKeyCode() == KeyInput.KEY_DOWN) { caretIndex = textFieldText.size(); } else if (evt.getKeyCode() == KeyInput.KEY_HOME || evt.getKeyCode() == KeyInput.KEY_PRIOR || evt.getKeyCode() == KeyInput.KEY_UP) { caretIndex = 0; } else { if (ctrl) { if (evt.getKeyCode() == KeyInput.KEY_C) { screen.setClipboardText(textRangeText); } else if (evt.getKeyCode() == KeyInput.KEY_V) { this.pasteTextInto(); } } else { if (isEnabled) { if (type == Type.DEFAULT) { textFieldText.add(caretIndex, String.valueOf(evt.getKeyChar())); caretIndex++; } else if (type == Type.ALPHA) { if (validateAlpha.indexOf(String.valueOf(evt.getKeyChar())) != -1) { textFieldText.add(caretIndex, String.valueOf(evt.getKeyChar())); caretIndex++; } } else if (type == Type.ALPHA_NOSPACE) { if (validateAlpha.indexOf(String.valueOf(evt.getKeyChar())) != -1) { textFieldText.add(caretIndex, String.valueOf(evt.getKeyChar())); caretIndex++; } } else if (type == Type.NUMERIC) { if (validateNumeric.indexOf(String.valueOf(evt.getKeyChar())) != -1) { textFieldText.add(caretIndex, String.valueOf(evt.getKeyChar())); caretIndex++; } } else if (type == Type.ALPHANUMERIC) { if (validateAlpha.indexOf(String.valueOf(evt.getKeyChar())) != -1 || validateNumeric.indexOf(String.valueOf(evt.getKeyChar())) != -1) { textFieldText.add(caretIndex, String.valueOf(evt.getKeyChar())); caretIndex++; } } else if (type == Type.ALPHANUMERIC_NOSPACE) { if (validateAlphaNoSpace.indexOf(String.valueOf(evt.getKeyChar())) != -1 || validateNumeric.indexOf(String.valueOf(evt.getKeyChar())) != -1) { textFieldText.add(caretIndex, String.valueOf(evt.getKeyChar())); caretIndex++; } } else if (type == Type.EXCLUDE_SPECIAL) { if (validateSpecChar.indexOf(String.valueOf(evt.getKeyChar())) == -1) { textFieldText.add(caretIndex, String.valueOf(evt.getKeyChar())); caretIndex++; } } else if (type == Type.EXCLUDE_CUSTOM) { if (validateCustom.indexOf(String.valueOf(evt.getKeyChar())) == -1) { textFieldText.add(caretIndex, String.valueOf(evt.getKeyChar())); caretIndex++; } } else if (type == Type.INCLUDE_CUSTOM) { if (validateCustom.indexOf(String.valueOf(evt.getKeyChar())) != -1) { textFieldText.add(caretIndex, String.valueOf(evt.getKeyChar())); caretIndex++; } } } } } this.setText(getVisibleText()); centerTextVertically(); controlKeyPressHook(evt, getText()); evt.setConsumed(); } public void controlKeyPressHook(KeyInputEvent evt, String text) { } @Override public void onKeyRelease(KeyInputEvent evt) { if (evt.getKeyCode() == KeyInput.KEY_LCONTROL || evt.getKeyCode() == KeyInput.KEY_RCONTROL) { ctrl = false; } else if (evt.getKeyCode() == KeyInput.KEY_LSHIFT || evt.getKeyCode() == KeyInput.KEY_RSHIFT) { shift = false; } else if (evt.getKeyCode() == KeyInput.KEY_LMENU || evt.getKeyCode() == KeyInput.KEY_RMENU) { alt = false; } evt.setConsumed(); } protected void getTextFieldText() { String ret = ""; int index = 0; for (String s : textFieldText) { ret += s; index++; } finalText = ret; } public void setTextFieldText(String s) { caretIndex = 0; textFieldText.clear(); for (int i = 0; i < s.length(); i++) { textFieldText.add(caretIndex, String.valueOf(s.charAt(i))); caretIndex++; } this.setText(getVisibleText()); setCaretPositionToEnd(); centerTextVertically(); } @Override public final void setFontSize(float fontSize) { this.fontSize = fontSize; // widthTest = new BitmapText(font, false); // widthTest.setBox(null); // widthTest.setSize(getFontSize()); // widthTest.setText(testString); if (textElement != null) { textElement.setSize(fontSize); } } @Override public String getText() { String ret = ""; int index = 0; for (String s : textFieldText) { ret += s; index++; } return ret; } protected String getVisibleText() { getTextFieldText(); widthTest = new BitmapText(font, false); widthTest.setBox(null); widthTest.setSize(getFontSize()); int index1 = 0, index2; widthTest.setText(finalText.substring(index1)); while(widthTest.getLineWidth() > getWidth()) { if (index1 == caretIndex) break; index1++; widthTest.setText(finalText.substring(index1)); } index2 = finalText.length()-1; if (index2 == caretIndex && caretIndex != textFieldText.size()) { index2 = caretIndex+1; widthTest.setText(finalText.substring(index1, index2)); while(widthTest.getLineWidth() < getWidth()) { if (index2 == textFieldText.size()) break; index2++; widthTest.setText(finalText.substring(index1, index2)); } } if (index2 != textFieldText.size()) index2++; if (head != index1 || tail != index2) { head = index1; tail = index2; } if (head != tail && head != -1 && tail != -1) { visibleText = finalText.substring(head, tail); } else { visibleText = ""; } widthTest.setText(finalText.substring(head, caretIndex)); caretX = widthTest.getLineWidth(); setCaretPosition(getAbsoluteX()+caretX); //caret.setLocalTranslation(caret.getLocalTranslation().setX(caretX)); /* if (rangeHead != -1 && rangeTail != -1) { float rangeX = getFont().getLineWidth(finalText.substring(head, rangeHead)); float rangeW = getFont().getLineWidth(finalText.substring(rangeHead, rangeTail)); System.out.println(rangeX + " : " + rangeW); textRange.setX(rangeX); textRange.setWidth(rangeW); } */ return visibleText; } protected void setCaretPosition(float caretX) { if (textElement != null) { if (hasTabFocus) { caret.getMaterial().setFloat("CaretX", caretX+getTextPadding()); caret.getMaterial().setFloat("LastUpdate", app.getTimer().getTimeInSeconds()); } } } public void setCaretPositionByX(float x) { int index1 = visibleText.length(); if (visibleText.length() > 0) { widthTest.setText(visibleText.substring(0, index1)); while(caret.getAbsoluteX()+widthTest.getLineWidth() > x) { index1 widthTest.setText(visibleText.substring(0, index1)); } caretX = widthTest.getLineWidth(); } caretIndex = head+index1; setCaretPosition(getAbsoluteX()+caretX); if (!shift) { resetTextRange(); setTextRangeStart(caretIndex); } else { setTextRangeEnd(caretIndex); } } public void setCaretPositionToEnd() { int index1 = visibleText.length(); if (visibleText.length() > 0) { widthTest.setText(visibleText.substring(0, index1)); caretX = widthTest.getLineWidth(); } caretIndex = head+index1; setCaretPosition(getAbsoluteX()+caretX); resetTextRange(); } private void setTextRangeStart(int head) { if (!visibleText.equals("")) { // System.out.println("Setting text range start to: " + head); rangeHead = head; if (head-this.head <= 0) widthTest.setText(""); else if(head-this.head < visibleText.length()) widthTest.setText(visibleText.substring(0, head-this.head)); else widthTest.setText(visibleText); caret.getMaterial().setFloat("TextRangeStart", getAbsoluteX()+widthTest.getLineWidth()+getTextPadding()); } } private void setTextRangeEnd(int tail) { if (!visibleText.equals("") && rangeHead != -1) { // System.out.println("Setting text range end to: " + tail); rangeTail = tail; if (tail-this.head <= 0) widthTest.setText(""); else if (tail-this.head < visibleText.length()) widthTest.setText(visibleText.substring(0, tail-this.head)); else widthTest.setText(visibleText); textRangeText = (rangeHead < rangeTail) ? finalText.substring(rangeHead, rangeTail) : finalText.substring(rangeTail, rangeHead); caret.getMaterial().setFloat("TextRangeEnd", getAbsoluteX()+widthTest.getLineWidth()+getTextPadding()); caret.getMaterial().setBoolean("ShowTextRange", true); } } private void resetTextRange() { textRangeText = ""; rangeHead = -1; rangeTail = -1; caret.getMaterial().setFloat("TextRangeStart", 0); caret.getMaterial().setFloat("TextRangeEnd", 0); caret.getMaterial().setBoolean("ShowTextRange", false); } private void pasteTextInto() { // TODO: Disabled this feature for the time being. Will re-enable at a later date. /* String text = screen.getClipboardText(); int index = caretIndex; if (text.length() > 0) { for (int i = 0; i < text.length(); i++) { textFieldText.add(index, String.valueOf(text.charAt(i))); index++; } caretIndex += index; getVisibleText(); } */ } public final void setTextFieldFontColor(ColorRGBA fontColor) { setFontColor(fontColor); caretMat.setColor("Color", fontColor); } public void setIsEnabled(boolean isEnabled) { this.isEnabled = isEnabled; } public boolean getIsEnabled() { return this.isEnabled; } @Override public void setTabFocus() { hasTabFocus = true; setTextRangeStart(caretIndex); if (isEnabled) caret.getMaterial().setBoolean("HasTabFocus", true); screen.setKeyboardElemeent(this); controlTextFieldSetTabFocusHook(); Effect effect = getEffect(Effect.EffectEvent.TabFocus); if (effect != null) { effect.setColor(ColorRGBA.DarkGray); screen.getEffectManager().applyEffect(effect); } } @Override public void resetTabFocus() { hasTabFocus = false; shift = false; ctrl = false; alt = false; caret.getMaterial().setBoolean("HasTabFocus", false); screen.setKeyboardElemeent(null); controlTextFieldResetTabFocusHook(); Effect effect = getEffect(Effect.EffectEvent.LoseTabFocus); if (effect != null) { effect.setColor(ColorRGBA.White); screen.getEffectManager().applyEffect(effect); } } public void controlTextFieldSetTabFocusHook() { } public void controlTextFieldResetTabFocusHook() { } @Override public void onGetFocus(MouseMotionEvent evt) { if (getIsEnabled()) screen.setCursor(Screen.CursorType.TEXT); setHasFocus(true); } @Override public void onLoseFocus(MouseMotionEvent evt) { if (getIsEnabled()) screen.setCursor(Screen.CursorType.POINTER); setHasFocus(false); } private void centerTextVertically() { float height = BitmapTextUtil.getTextLineHeight(this, testString);//widthTest.getHeight()+this.borders.x; float nextY = height-FastMath.floor(getHeight()); nextY /= 2; nextY = (float)FastMath.ceil(nextY)+1; // if (height > getHeight()) setTextPosition(getTextPosition().x, -nextY); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tonegod.gui.controls.windows; import com.jme3.font.BitmapFont; import com.jme3.font.LineWrapMode; import com.jme3.input.event.MouseButtonEvent; import com.jme3.math.Vector2f; import com.jme3.math.Vector4f; import tonegod.gui.controls.buttons.ButtonAdapter; import tonegod.gui.core.Element; import tonegod.gui.core.ElementManager; import tonegod.gui.core.layouts.Layout; import tonegod.gui.core.utils.ControlUtil; import tonegod.gui.core.utils.UIDUtil; import tonegod.gui.effects.Effect; /** * * @author t0neg0d */ public class Window extends Element { protected Element dragBar; protected Element contentArea; protected ButtonAdapter close, collapse; private boolean useShowSound, useHideSound; private String showSound, hideSound; private float showSoundVolume, hideSoundVolume; protected Vector4f dbIndents = new Vector4f(); private Window self; private boolean useClose = false, useCollapse = false, isCollapsed = false; private float winDif = 0; /** * Creates a new instance of the Window control * * @param screen The screen control the Element is to be added to */ public Window(ElementManager screen) { this(screen, UIDUtil.getUID(), Vector2f.ZERO, screen.getStyle("Window").getVector2f("defaultSize"), screen.getStyle("Window").getVector4f("resizeBorders"), screen.getStyle("Window").getString("defaultImg") ); } /** * Creates a new instance of the Window control * * @param screen The screen control the Element is to be added to * @param position A Vector2f containing the x/y position of the Element */ public Window(ElementManager screen, Vector2f position) { this(screen, UIDUtil.getUID(), position, screen.getStyle("Window").getVector2f("defaultSize"), screen.getStyle("Window").getVector4f("resizeBorders"), screen.getStyle("Window").getString("defaultImg") ); } /** * Creates a new instance of the Window control * * @param screen The screen control the Element is to be added to * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element */ public Window(ElementManager screen, Vector2f position, Vector2f dimensions) { this(screen, UIDUtil.getUID(), position, dimensions, screen.getStyle("Window").getVector4f("resizeBorders"), screen.getStyle("Window").getString("defaultImg") ); } /** * Creates a new instance of the Window control * * @param screen The screen control the Element is to be added to * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element * @param resizeBorders A Vector4f containg the border information used when resizing the default image (x = N, y = W, z = E, w = S) * @param defaultImg The default image to use for the Window */ public Window(ElementManager screen, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String defaultImg) { this(screen, UIDUtil.getUID(), position, dimensions, resizeBorders, defaultImg); } /** * Creates a new instance of the Window control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element */ public Window(ElementManager screen, String UID, Vector2f position) { this(screen, UID, position, screen.getStyle("Window").getVector2f("defaultSize"), screen.getStyle("Window").getVector4f("resizeBorders"), screen.getStyle("Window").getString("defaultImg") ); } /** * Creates a new instance of the Window control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element */ public Window(ElementManager screen, String UID, Vector2f position, Vector2f dimensions) { this(screen, UID, position, dimensions, screen.getStyle("Window").getVector4f("resizeBorders"), screen.getStyle("Window").getString("defaultImg") ); } /** * Creates a new instance of the Window control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element * @param resizeBorders A Vector4f containg the border information used when resizing the default image (x = N, y = W, z = E, w = S) * @param defaultImg The default image to use for the Slider's track */ public Window(ElementManager screen, String UID, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String defaultImg) { super(screen, UID, position, dimensions, resizeBorders, defaultImg); self = this; this.setIsResizable(true); this.setScaleNS(false); this.setScaleEW(false); this.setClipPadding(screen.getStyle("Window").getFloat("clipPadding")); this.setMinDimensions(screen.getStyle("Window").getVector2f("minSize")); // this.setClippingLayer(this); dbIndents.set(screen.getStyle("Window#Dragbar").getVector4f("indents")); dragBar = new Element(screen, UID + ":DragBar", new Vector2f(dbIndents.y, dbIndents.x), new Vector2f(getWidth()-dbIndents.y-dbIndents.z, screen.getStyle("Window#Dragbar").getFloat("defaultControlSize")), screen.getStyle("Window#Dragbar").getVector4f("resizeBorders"), screen.getStyle("Window#Dragbar").getString("defaultImg") ); dragBar.setFontSize(screen.getStyle("Window#Dragbar").getFloat("fontSize")); dragBar.setFontColor(screen.getStyle("Window#Dragbar").getColorRGBA("fontColor")); dragBar.setTextAlign(BitmapFont.Align.valueOf(screen.getStyle("Window#Dragbar").getString("textAlign"))); dragBar.setTextVAlign(BitmapFont.VAlign.valueOf(screen.getStyle("Window#Dragbar").getString("textVAlign"))); dragBar.setTextPosition(0,0); dragBar.setTextPaddingByKey("Window#Dragbar","textPadding"); dragBar.setTextWrap(LineWrapMode.valueOf(screen.getStyle("Window#Dragbar").getString("textWrap"))); dragBar.setIsResizable(false); dragBar.setScaleEW(true); dragBar.setScaleNS(false); dragBar.setIsMovable(true); dragBar.setEffectParent(true); dragBar.addClippingLayer(this); addChild(dragBar); float buttonHeight = (dragBar.getHeight() <= 25) ? 18 : dragBar.getHeight()-6; // buttonHeight -= 2; close = new ButtonAdapter(screen, Vector2f.ZERO, new Vector2f(buttonHeight,buttonHeight)) { @Override public void onButtonMouseLeftUp(MouseButtonEvent evt, boolean toggled) { self.hideWindow(); } }; close.setText("X"); close.setDocking(Docking.SE); collapse = new ButtonAdapter(screen, Vector2f.ZERO, new Vector2f(buttonHeight,buttonHeight)) { @Override public void onButtonMouseLeftUp(MouseButtonEvent evt, boolean toggled) { if (!isCollapsed) { isCollapsed = true; contentArea.hide(); winDif = self.getHeight(); self.setHeight(getDragBarHeight()+(dbIndents.y*2)); winDif -= self.getHeight(); dragBar.setY(self.getHeight()-dragBar.getHeight()-dbIndents.y); self.setY(self.getY()+winDif); setButtonIcon(getWidth(), getHeight(), screen.getStyle("Common").getString("arrowDown")); self.setResizeN(false); self.setResizeS(false); } else { isCollapsed = false; contentArea.show(); self.setHeight(getDragBarHeight()+contentArea.getHeight()+dbIndents.y+2); dragBar.setY(self.getHeight()-dragBar.getHeight()-dbIndents.y); self.setY(self.getY()-winDif);setButtonIcon(getWidth(), getHeight(), screen.getStyle("Common").getString("arrowUp")); self.setResizeN(self.getIsResizable()); self.setResizeS(self.getIsResizable()); } } }; collapse.setButtonIcon(collapse.getWidth(), collapse.getHeight(), screen.getStyle("Common").getString("arrowUp")); collapse.setDocking(Docking.SE); contentArea = ControlUtil.getContainer(screen); contentArea.setDimensions(dimensions.subtract(0, dragBar.getHeight()+dbIndents.y+2)); contentArea.setPosition(0,dragBar.getHeight()+dbIndents.y); contentArea.setScaleEW(true); contentArea.setScaleNS(true); addChild(contentArea); showSound = screen.getStyle("Window").getString("showSound"); useShowSound = screen.getStyle("Window").getBoolean("useShowSound"); showSoundVolume = screen.getStyle("Window").getFloat("showSoundVolume"); hideSound = screen.getStyle("Window").getString("hideSound"); useHideSound = screen.getStyle("Window").getBoolean("useHideSound"); hideSoundVolume = screen.getStyle("Window").getFloat("hideSoundVolume"); populateEffects("Window"); } /** * Returns a pointer to the Element used as a window dragbar * @return Element */ public Element getDragBar() { return this.dragBar; } /** * Returns the drag bar height * @return float */ public float getDragBarHeight() { return dragBar.getHeight(); } /** * Sets the Window title text * @param title String */ public void setWindowTitle(String title) { dragBar.setText(title); } /** * Shows the window using the default Show Effect */ public void showWindow() { Effect effect = getEffect(Effect.EffectEvent.Show); if (effect != null) { if (useShowSound && screen.getUseUIAudio()) { effect.setAudioFile(showSound); effect.setAudioVolume(showSoundVolume); } if (effect.getEffectType() == Effect.EffectType.FadeIn) { Effect clone = effect.clone(); clone.setAudioFile(null); this.propagateEffect(clone, false); } else screen.getEffectManager().applyEffect(effect); } else this.show(); } /** * Hides the Window using the default Hide Effect */ public void hideWindow() { Effect effect = getEffect(Effect.EffectEvent.Hide); if (effect != null) { if (useHideSound && screen.getUseUIAudio()) { effect.setAudioFile(hideSound); effect.setAudioVolume(hideSoundVolume); } if (effect.getEffectType() == Effect.EffectType.FadeOut) { Effect clone = effect.clone(); clone.setAudioFile(null); this.propagateEffect(clone, true); } else screen.getEffectManager().applyEffect(effect); } else this.hide(); } /** * Enables/disables the Window dragbar * @param isMovable boolean */ public void setWindowIsMovable(boolean isMovable) { this.dragBar.setIsMovable(isMovable); } /** * Returns if the Window dragbar is currently enabled/disabled * @return boolean */ public boolean getWindowIsMovable() { return this.dragBar.getIsMovable(); } public void addWindowContent(Element el) { contentArea.addChild(el); contentArea.addClippingLayer(contentArea); } public void removeWindowContent(Element el) { contentArea.removeChild(el); } public void setContentLayout(Layout layout) { contentArea.setLayout(layout);; } public Element getContentArea() { return contentArea; } public void setUseCloseButton(boolean use) { if (use) { this.useClose = true; dragBar.addChild(close); close.centerToParentV(); close.setX(dragBar.getWidth()-close.getWidth()-close.getY()); if (useCollapse) { close.centerToParentV(); close.setX(dragBar.getWidth()-close.getWidth()-collapse.getWidth()-collapse.getY()-5); } } else { this.useClose = false; dragBar.removeChild(close); if (useCollapse) { close.centerToParentV(); close.setX(dragBar.getWidth()-collapse.getWidth()-collapse.getY()); } } } public void setUseCollapseButton(boolean use) { if (use) { this.useCollapse = true; dragBar.addChild(collapse); collapse.centerToParentV(); if (useClose) collapse.setX(dragBar.getWidth()-collapse.getWidth()-close.getWidth()-collapse.getY()-5); else collapse.setX(dragBar.getWidth()-collapse.getWidth()-collapse.getY()); } else { this.useCollapse = false; dragBar.removeChild(collapse); } } public void sizeWindowToContent() { contentArea.sizeToContent(); setDimensions( contentArea.getWidth()+(dbIndents.z), contentArea.getHeight()+getDragBarHeight()+(dbIndents.y+dbIndents.w) ); dragBar.setY(dbIndents.y+contentArea.getHeight()); dragBar.setWidth(getWidth()-(dbIndents.x+dbIndents.z)); } }
package uk.co.sftrabbit.stacksync; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v13.app.FragmentPagerAdapter; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.widget.PopupMenu; import java.util.List; import java.util.Collections; import java.util.Arrays; public class StackSync extends Activity { private ActionBar actionBar; private ViewPager tabPager; //TODO - give content descriptions for accessibility private static final List<TabSpec> TAB_SPECS = Collections.unmodifiableList(Arrays.asList( new TabSpec(R.string.tab_dashboard, 0, null), new TabSpec(R.string.tab_sites, 0, SitesFragment.class), new TabSpec(R.string.tab_accounts, 0, null) )); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stacksync); actionBar = getActionBar(); assert actionBar != null : "No action bar available"; tabPager = (ViewPager) findViewById(R.id.tab_pager); assert tabPager != null : "No tab pager in layout"; initTabPager(); initTabs(); } @Override public boolean onCreateOptionsMenu(Menu menu) { final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.actions_stacksync, menu); return super.onCreateOptionsMenu(menu); } private void initTabPager() { tabPager.setAdapter(new TabPagerAdapter(getFragmentManager())); tabPager.setOnPageChangeListener(new TabPagerListener(actionBar)); } private void initTabs() { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); for (TabSpec tabSpec : TAB_SPECS) { addTab(tabSpec); } } private void addTab(TabSpec tabSpec) { final ActionBar.Tab tab = actionBar.newTab(); tab.setTabListener(new TabListener(tabPager)); actionBar.addTab(tabSpec.applyTo(tab)); } public void onDropdownClick(View v) { //TODO - Inflate this menu instead of hardcoding it final PopupMenu popupMenu = new PopupMenu(this, v); final Menu menu = popupMenu.getMenu(); menu.add("Meta Site"); menu.add("Your Account"); menu.add("Open in Browser"); popupMenu.show(); } private static class TabSpec { private int tabTextResourceId; private int contentDescriptionResourceId; private Class fragmentClass; public TabSpec(int tabTextResourceId, int contentDescriptionResourceId, Class fragmentClass) { this.tabTextResourceId = tabTextResourceId; this.contentDescriptionResourceId = contentDescriptionResourceId; this.fragmentClass = fragmentClass; } public ActionBar.Tab applyTo(ActionBar.Tab tab) { if (tabTextResourceId != 0) { tab.setText(tabTextResourceId); } if (contentDescriptionResourceId != 0) { tab.setContentDescription(contentDescriptionResourceId); } return tab; } public Fragment createFragment() { try { if (fragmentClass != null) { return (Fragment) fragmentClass.getConstructor().newInstance(); } else { return new Fragment(); } } catch (Exception exception) { return null; } } } private static class TabPagerAdapter extends FragmentPagerAdapter { public TabPagerAdapter(FragmentManager fragmentManager) { super(fragmentManager); } @Override public int getCount() { return TAB_SPECS.size(); } @Override public Fragment getItem(int position) { return TAB_SPECS.get(position).createFragment(); } } private static class TabPagerListener extends ViewPager.SimpleOnPageChangeListener { private final ActionBar actionBar; public TabPagerListener(ActionBar actionBar) { this.actionBar = actionBar; } @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } } private static class TabListener implements ActionBar.TabListener { private final ViewPager tabPager; public TabListener(ViewPager tabPager) { this.tabPager = tabPager; } public void onTabReselected(ActionBar.Tab tab, FragmentTransaction transaction) { } public void onTabSelected(ActionBar.Tab tab, FragmentTransaction transaction) { tabPager.setCurrentItem(tab.getPosition()); } public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction transaction) { } } }
package org.perl6.rakudo; import org.perl6.nqp.runtime.*; import org.perl6.nqp.sixmodel.*; /** * Contains implementation of nqp:: ops specific to Rakudo Perl 6. */ public final class Ops { private static SixModelObject Parcel; private static SixModelObject Code; private static SixModelObject Signature; public static SixModelObject Parameter; private static SixModelObject False; private static SixModelObject True; private static boolean initialized = false; /* Parameter hints for fast lookups. */ private static final int HINT_PARCEL_STORAGE = 0; private static final int HINT_CODE_DO = 0; private static final int HINT_CODE_SIG = 1; private static final int HINT_SIG_PARAMS = 0; public static SixModelObject p6init(ThreadContext tc) { if (!initialized) { tc.gc.contConfigs.put("rakudo_scalar", new RakudoContainerConfigurer()); initialized = true; } return null; } public static SixModelObject p6settypes(SixModelObject conf, ThreadContext tc) { Parcel = conf.at_key_boxed(tc, "Parcel"); Code = conf.at_key_boxed(tc, "Code"); Signature = conf.at_key_boxed(tc, "Signature"); Parameter = conf.at_key_boxed(tc, "Parameter"); False = conf.at_key_boxed(tc, "False"); True = conf.at_key_boxed(tc, "True"); return conf; } public static SixModelObject booleanize(int x) { return x == 0 ? False : True; } public static CallSiteDescriptor p6bindsig(ThreadContext tc, CallSiteDescriptor csd, Object[] args) { /* Do any flattening before processing begins. */ CallFrame cf = tc.curFrame; if (csd.hasFlattening) { csd = csd.explodeFlattening(cf, args); args = tc.flatArgs; } else { tc.flatArgs = args; } /* Look up parameters to bind. */ SixModelObject sig = cf.codeRef.codeObject .get_attribute_boxed(tc, Code, "$!signature", HINT_CODE_SIG); SixModelObject params = sig .get_attribute_boxed(tc, Signature, "$!params", HINT_SIG_PARAMS); /* Run binder, and handle any errors. */ switch (Binder.bind(tc, cf, params, csd, args, false, true)) { case Binder.BIND_RESULT_FAIL: throw ExceptionHandling.dieInternal(tc, Binder.lastError(tc)); case Binder.BIND_RESULT_JUNCTION: throw ExceptionHandling.dieInternal(tc, "Junction re-dispatch NYI"); } return csd; } public static SixModelObject p6parcel(SixModelObject array, SixModelObject fill, ThreadContext tc) { SixModelObject parcel = Parcel.st.REPR.allocate(tc, Parcel.st); parcel.initialize(tc); parcel.bind_attribute_boxed(tc, Parcel, "$!storage", HINT_PARCEL_STORAGE, array); if (fill != null) { long elems = array.elems(tc); for (long i = 0; i < elems; i++) { if (array.at_pos_boxed(tc, i) == null) array.bind_pos_boxed(tc, i, fill); } } return parcel; } }
package org.perl6.rakudo; import java.util.Arrays; import java.util.Calendar; import java.util.Comparator; import org.perl6.nqp.runtime.*; import org.perl6.nqp.sixmodel.*; import org.perl6.nqp.sixmodel.reprs.CallCaptureInstance; import org.perl6.nqp.sixmodel.reprs.ContextRefInstance; import org.perl6.nqp.sixmodel.reprs.LexoticInstance; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance; /** * Contains implementation of nqp:: ops specific to Rakudo Perl 6. */ public final class Ops { public static final boolean DEBUG_MODE = false; public static class ThreadExt { public SixModelObject firstPhaserCodeBlock; public ThreadExt(ThreadContext tc) { } } public static class GlobalExt { public SixModelObject Mu; public SixModelObject Parcel; public SixModelObject Code; public SixModelObject Routine; public SixModelObject Signature; public SixModelObject Parameter; public SixModelObject Int; public SixModelObject Num; public SixModelObject Str; public SixModelObject List; public SixModelObject ListIter; public SixModelObject Array; public SixModelObject LoL; public SixModelObject Nil; public SixModelObject EnumMap; public SixModelObject Hash; public SixModelObject Junction; public SixModelObject Scalar; public SixModelObject Capture; public SixModelObject ContainerDescriptor; public SixModelObject False; public SixModelObject True; public SixModelObject AutoThreader; public SixModelObject EMPTYARR; public SixModelObject EMPTYHASH; boolean initialized; public GlobalExt(ThreadContext tc) { } } public static ContextKey<ThreadExt, GlobalExt> key = new ContextKey< >(ThreadExt.class, GlobalExt.class); /* Parameter hints for fast lookups. */ private static final int HINT_PARCEL_STORAGE = 0; private static final int HINT_CODE_DO = 0; private static final int HINT_CODE_SIG = 1; private static final int HINT_ROUTINE_RW = 7; private static final int HINT_SIG_PARAMS = 0; private static final int HINT_SIG_CODE = 4; public static final int HINT_CD_OF = 0; public static final int HINT_CD_RW = 1; public static final int HINT_CD_NAME = 2; public static final int HINT_CD_DEFAULT = 3; private static final int HINT_LIST_items = 0; private static final int HINT_LIST_flattens = 1; private static final int HINT_LIST_nextiter = 2; private static final int HINT_LISTITER_reified = 0; private static final int HINT_LISTITER_nextiter = 1; private static final int HINT_LISTITER_rest = 2; private static final int HINT_LISTITER_list = 3; public static SixModelObject p6init(ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (!gcx.initialized) { tc.gc.contConfigs.put("rakudo_scalar", new RakudoContainerConfigurer()); SixModelObject BOOTArray = tc.gc.BOOTArray; gcx.EMPTYARR = BOOTArray.st.REPR.allocate(tc, BOOTArray.st); SixModelObject BOOTHash = tc.gc.BOOTHash; gcx.EMPTYHASH = BOOTHash.st.REPR.allocate(tc, BOOTHash.st); gcx.initialized = true; } return null; } public static SixModelObject p6settypes(SixModelObject conf, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); gcx.Mu = conf.at_key_boxed(tc, "Mu"); gcx.Parcel = conf.at_key_boxed(tc, "Parcel"); gcx.Code = conf.at_key_boxed(tc, "Code"); gcx.Routine = conf.at_key_boxed(tc, "Routine"); gcx.Signature = conf.at_key_boxed(tc, "Signature"); gcx.Parameter = conf.at_key_boxed(tc, "Parameter"); gcx.Int = conf.at_key_boxed(tc, "Int"); gcx.Num = conf.at_key_boxed(tc, "Num"); gcx.Str = conf.at_key_boxed(tc, "Str"); gcx.List = conf.at_key_boxed(tc, "List"); gcx.ListIter = conf.at_key_boxed(tc, "ListIter"); gcx.Array = conf.at_key_boxed(tc, "Array"); gcx.LoL = conf.at_key_boxed(tc, "LoL"); gcx.EnumMap = conf.at_key_boxed(tc, "EnumMap"); gcx.Hash = conf.at_key_boxed(tc, "Hash"); gcx.Junction = conf.at_key_boxed(tc, "Junction"); gcx.Scalar = conf.at_key_boxed(tc, "Scalar"); gcx.Capture = conf.at_key_boxed(tc, "Capture"); gcx.ContainerDescriptor = conf.at_key_boxed(tc, "ContainerDescriptor"); gcx.False = conf.at_key_boxed(tc, "False"); gcx.True = conf.at_key_boxed(tc, "True"); return conf; } public static SixModelObject p6setautothreader(SixModelObject autoThreader, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); gcx.AutoThreader = autoThreader; return autoThreader; } public static SixModelObject booleanize(int x, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); return x == 0 ? gcx.False : gcx.True; } public static SixModelObject p6definite(SixModelObject obj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); obj = org.perl6.nqp.runtime.Ops.decont(obj, tc); return obj instanceof TypeObject ? gcx.False : gcx.True; } public static SixModelObject p6box_i(long value, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject res = gcx.Int.st.REPR.allocate(tc, gcx.Int.st); res.set_int(tc, value); return res; } public static SixModelObject p6box_n(double value, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject res = gcx.Num.st.REPR.allocate(tc, gcx.Num.st); res.set_num(tc, value); return res; } public static SixModelObject p6box_s(String value, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject res = gcx.Str.st.REPR.allocate(tc, gcx.Str.st); res.set_str(tc, value); return res; } public static SixModelObject p6list(SixModelObject arr, SixModelObject type, SixModelObject flattens, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject list = type.st.REPR.allocate(tc, type.st); if (arr != null) list.bind_attribute_boxed(tc, gcx.List, "$!nextiter", HINT_LIST_nextiter, p6listiter(arr, list, tc)); list.bind_attribute_boxed(tc, gcx.List, "$!flattens", HINT_LIST_flattens, flattens); return list; } public static SixModelObject p6listitems(SixModelObject list, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject items = list.get_attribute_boxed(tc, gcx.List, "$!items", HINT_LIST_items); if (!(items instanceof VMArrayInstance)) { items = gcx.EMPTYARR.clone(tc); list.bind_attribute_boxed(tc, gcx.List, "$!items", HINT_LIST_items, items); } return items; } public static long p6arrfindtypes(SixModelObject arr, SixModelObject types, long start, long last, ThreadContext tc) { int ntypes = (int)types.elems(tc); SixModelObject[] typeArr = new SixModelObject[ntypes]; for (int i = 0; i < ntypes; i++) typeArr[i] = types.at_pos_boxed(tc, i); long elems = arr.elems(tc); if (elems < last) last = elems; long index; for (index = start; index < last; index++) { SixModelObject val = arr.at_pos_boxed(tc, index); if (val.st.ContainerSpec == null) { boolean found = false; for (int typeIndex = 0; typeIndex < ntypes; typeIndex++) { if (org.perl6.nqp.runtime.Ops.istype(val, typeArr[typeIndex], tc) != 0) { found = true; break; } } if (found) break; } } return index; } public static SixModelObject p6shiftpush(SixModelObject a, SixModelObject b, long total, ThreadContext tc) { long count = total; long elems = b.elems(tc); if (count > elems) count = elems; if (a != null && total > 0) { long getPos = 0; long setPos = a.elems(tc); a.set_elems(tc, setPos + count); while (count > 0) { a.bind_pos_boxed(tc, setPos, b.at_pos_boxed(tc, getPos)); count getPos++; setPos++; } } if (total > 0) { GlobalExt gcx = key.getGC(tc); b.splice(tc, gcx.EMPTYARR, 0, total); } return a; } public static SixModelObject p6listiter(SixModelObject arr, SixModelObject list, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject iter = gcx.ListIter.st.REPR.allocate(tc, gcx.ListIter.st); iter.bind_attribute_boxed(tc, gcx.ListIter, "$!rest", HINT_LISTITER_rest, arr); iter.bind_attribute_boxed(tc, gcx.ListIter, "$!list", HINT_LISTITER_list, list); return iter; } public static SixModelObject p6argvmarray(ThreadContext tc, CallSiteDescriptor csd, Object[] args) { SixModelObject BOOTArray = tc.gc.BOOTArray; SixModelObject res = BOOTArray.st.REPR.allocate(tc, BOOTArray.st); for (int i = 0; i < csd.numPositionals; i++) { SixModelObject toBind; switch (csd.argFlags[i]) { case CallSiteDescriptor.ARG_INT: toBind = p6box_i((long)args[i], tc); break; case CallSiteDescriptor.ARG_NUM: toBind = p6box_n((double)args[i], tc); break; case CallSiteDescriptor.ARG_STR: toBind = p6box_s((String)args[i], tc); break; default: toBind = org.perl6.nqp.runtime.Ops.hllize((SixModelObject)args[i], tc); break; } res.bind_pos_boxed(tc, i, toBind); } return res; } public static CallSiteDescriptor p6bindsig(ThreadContext tc, CallSiteDescriptor csd, Object[] args) { /* Do any flattening before processing begins. */ CallFrame cf = tc.curFrame; if (csd.hasFlattening) { csd = csd.explodeFlattening(cf, args); args = tc.flatArgs; } cf.csd = csd; cf.args = args; /* Look up parameters to bind. */ if (DEBUG_MODE) { if (cf.codeRef.name != null) System.err.println("Binding for " + cf.codeRef.name); } GlobalExt gcx = key.getGC(tc); SixModelObject sig = cf.codeRef.codeObject .get_attribute_boxed(tc, gcx.Code, "$!signature", HINT_CODE_SIG); SixModelObject params = sig .get_attribute_boxed(tc, gcx.Signature, "$!params", HINT_SIG_PARAMS); /* Run binder, and handle any errors. */ String[] error = new String[1]; switch (Binder.bind(tc, gcx, cf, params, csd, args, false, error)) { case Binder.BIND_RESULT_FAIL: throw ExceptionHandling.dieInternal(tc, error[0]); case Binder.BIND_RESULT_JUNCTION: /* Invoke the auto-threader. */ csd = csd.injectInvokee(tc, args, cf.codeRef.codeObject); args = tc.flatArgs; org.perl6.nqp.runtime.Ops.invokeDirect(tc, gcx.AutoThreader, csd, args); org.perl6.nqp.runtime.Ops.return_o( org.perl6.nqp.runtime.Ops.result_o(cf), cf); /* Return null to indicate immediate return to the routine. */ return null; } /* The binder may, for a variety of reasons, wind up calling Perl 6 code and overwriting flatArgs, so it needs to be set at the end to return reliably */ tc.flatArgs = args; return csd; } public static SixModelObject p6bindcaptosig(SixModelObject sig, SixModelObject cap, ThreadContext tc) { CallFrame cf = tc.curFrame; GlobalExt gcx = key.getGC(tc); CallSiteDescriptor csd = Binder.explodeCapture(tc, gcx, cap); SixModelObject params = sig.get_attribute_boxed(tc, gcx.Signature, "$!params", HINT_SIG_PARAMS); String[] error = new String[1]; switch (Binder.bind(tc, gcx, cf, params, csd, tc.flatArgs, false, error)) { case Binder.BIND_RESULT_FAIL: case Binder.BIND_RESULT_JUNCTION: throw ExceptionHandling.dieInternal(tc, error[0]); default: return sig; } } public static long p6isbindable(SixModelObject sig, SixModelObject cap, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); CallSiteDescriptor csd; Object[] args; if (cap instanceof CallCaptureInstance) { CallCaptureInstance cc = (CallCaptureInstance)cap; csd = cc.descriptor; args = cc.args; } else { csd = Binder.explodeCapture(tc, gcx, cap); args = tc.flatArgs; } SixModelObject params = sig.get_attribute_boxed(tc, gcx.Signature, "$!params", HINT_SIG_PARAMS); SixModelObject codeObj = sig.get_attribute_boxed(tc, gcx.Signature, "$!code", HINT_SIG_CODE); CodeRef cr = (CodeRef)codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); CallFrame cf = new CallFrame(tc, cr); try { switch (Binder.bind(tc, gcx, cf, params, csd, args, false, null)) { case Binder.BIND_RESULT_FAIL: return 0; default: return 1; } } finally { tc.curFrame = tc.curFrame.caller; } } public static long p6trialbind(SixModelObject routine, SixModelObject values, SixModelObject flags, ThreadContext tc) { /* TODO */ return Binder.TRIAL_BIND_NOT_SURE; } public static SixModelObject p6parcel(SixModelObject array, SixModelObject fill, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject parcel = gcx.Parcel.st.REPR.allocate(tc, gcx.Parcel.st); parcel.bind_attribute_boxed(tc, gcx.Parcel, "$!storage", HINT_PARCEL_STORAGE, array); if (fill != null) { long elems = array.elems(tc); for (long i = 0; i < elems; i++) { if (array.at_pos_boxed(tc, i) == null) array.bind_pos_boxed(tc, i, fill); } } return parcel; } private static final CallSiteDescriptor STORE = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); private static final CallSiteDescriptor storeThrower = new CallSiteDescriptor( new byte[] { }, null); public static SixModelObject p6store(SixModelObject cont, SixModelObject value, ThreadContext tc) { ContainerSpec spec = cont.st.ContainerSpec; if (spec != null) { spec.store(tc, cont, org.perl6.nqp.runtime.Ops.decont(value, tc)); } else { SixModelObject meth = org.perl6.nqp.runtime.Ops.findmethod(cont, "STORE", tc); if (meth != null) { org.perl6.nqp.runtime.Ops.invokeDirect(tc, meth, STORE, new Object[] { cont, value }); } else { SixModelObject thrower = getThrower(tc, "X::Assignment::RO"); if (thrower == null) ExceptionHandling.dieInternal(tc, "Cannot assign to a non-container"); else org.perl6.nqp.runtime.Ops.invokeDirect(tc, meth, storeThrower, new Object[] { }); } } return cont; } public static SixModelObject p6decontrv(SixModelObject cont, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (cont != null && isRWScalar(tc, gcx, cont)) { tc.curFrame.codeRef.codeObject.get_attribute_native(tc, gcx.Routine, "$!rw", HINT_ROUTINE_RW); if (tc.native_i == 0) { /* Recontainerize to RO. */ SixModelObject roCont = gcx.Scalar.st.REPR.allocate(tc, gcx.Scalar.st); roCont.bind_attribute_boxed(tc, gcx.Scalar, "$!value", RakudoContainerSpec.HINT_value, cont.st.ContainerSpec.fetch(tc, cont)); return roCont; } } return cont; } public static SixModelObject p6recont_ro(SixModelObject cont, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (isRWScalar(tc, gcx, cont)) { SixModelObject roCont = gcx.Scalar.st.REPR.allocate(tc, gcx.Scalar.st); roCont.bind_attribute_boxed(tc, gcx.Scalar, "$!value", RakudoContainerSpec.HINT_value, cont.st.ContainerSpec.fetch(tc, cont)); return roCont; } return cont; } private static boolean isRWScalar(ThreadContext tc, GlobalExt gcx, SixModelObject check) { if (!(check instanceof TypeObject) && check.st.WHAT == gcx.Scalar) { SixModelObject desc = check.get_attribute_boxed(tc, gcx.Scalar, "$!descriptor", RakudoContainerSpec.HINT_descriptor); if (desc == null) return false; desc.get_attribute_native(tc, gcx.ContainerDescriptor, "$!rw", HINT_CD_RW); return tc.native_i != 0; } return false; } public static SixModelObject p6var(SixModelObject cont, ThreadContext tc) { if (cont != null && cont.st.ContainerSpec != null) { GlobalExt gcx = key.getGC(tc); SixModelObject wrapper = gcx.Scalar.st.REPR.allocate(tc, gcx.Scalar.st); wrapper.bind_attribute_boxed(tc, gcx.Scalar, "$!value", RakudoContainerSpec.HINT_value, cont); return wrapper; } else { return cont; } } public static SixModelObject p6typecheckrv(SixModelObject rv, SixModelObject routine, ThreadContext tc) { if (DEBUG_MODE) System.err.println("p6typecheckrv NYI"); return rv; } private static final CallSiteDescriptor baThrower = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static SixModelObject p6bindassert(SixModelObject value, SixModelObject type, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (type != gcx.Mu) { SixModelObject decont = org.perl6.nqp.runtime.Ops.decont(value, tc); if (org.perl6.nqp.runtime.Ops.istype(decont, type, tc) == 0) { SixModelObject thrower = getThrower(tc, "X::TypeCheck::Binding"); if (thrower == null) ExceptionHandling.dieInternal(tc, "Type check failed in binding"); else org.perl6.nqp.runtime.Ops.invokeDirect(tc, thrower, baThrower, new Object[] { value, type }); } } return value; } public static SixModelObject p6capturelex(SixModelObject codeObj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); CodeRef closure = (CodeRef)codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); StaticCodeInfo wantedStaticInfo = closure.staticInfo.outerStaticInfo; if (tc.curFrame.codeRef.staticInfo == wantedStaticInfo) closure.outer = tc.curFrame; else if (tc.curFrame.outer.codeRef.staticInfo == wantedStaticInfo) closure.outer = tc.curFrame.outer; return codeObj; } public static SixModelObject p6getouterctx(SixModelObject codeObj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); codeObj = org.perl6.nqp.runtime.Ops.decont(codeObj, tc); CodeRef closure = (CodeRef)codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = closure.outer; return wrap; } public static SixModelObject p6captureouters(SixModelObject capList, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); CallFrame cf = tc.curFrame; long elems = capList.elems(tc); for (long i = 0; i < elems; i++) { SixModelObject codeObj = capList.at_pos_boxed(tc, i); CodeRef closure = (CodeRef)codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); CallFrame ctxToDiddle = closure.outer; ctxToDiddle.outer = tc.curFrame; } return capList; } public static SixModelObject p6bindattrinvres(SixModelObject obj, SixModelObject ch, String name, SixModelObject value, ThreadContext tc) { obj.bind_attribute_boxed(tc, org.perl6.nqp.runtime.Ops.decont(ch, tc), name, STable.NO_HINT, value); if (obj.sc != null) org.perl6.nqp.runtime.Ops.scwbObject(tc, obj); return obj; } public static SixModelObject getThrower(ThreadContext tc, String type) { /* XXX TODO: thrower lookup. */ return null; } private static CallFrame find_common_ctx(CallFrame ctx1, CallFrame ctx2) { int depth1 = 0; int depth2 = 0; CallFrame ctx; for (ctx = ctx1; ctx != null; ctx = ctx.caller, depth1++) if (ctx == ctx2) return ctx; for (ctx = ctx2; ctx != null; ctx = ctx.caller, depth2++) if (ctx == ctx1) return ctx; for (; depth1 > depth2; depth2++) ctx1 = ctx1.caller; for (; depth2 > depth1; depth1++) ctx2 = ctx2.caller; while (ctx1 != ctx2) { ctx1 = ctx1.caller; ctx2 = ctx2.caller; } return ctx1; } private static SixModelObject getremotelex(CallFrame pad, String name) { /* use for sub_find_pad */ CallFrame curFrame = pad; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found]; curFrame = curFrame.outer; } return null; } public static SixModelObject p6routinereturn(SixModelObject in, ThreadContext tc) { CallFrame ctx = tc.curFrame; SixModelObject cont = null; for (ctx = ctx.caller; ctx != null; ctx = ctx.caller) { cont = getremotelex(ctx, "RETURN"); if (cont != null) break; } if (!(cont instanceof LexoticInstance)) { SixModelObject thrower = getThrower(tc, "X::ControlFlow::Return"); if (thrower == null) ExceptionHandling.dieInternal(tc, "Attempt to return outside of any Routine"); else org.perl6.nqp.runtime.Ops.invokeArgless(tc, thrower); } // rewinding is handled by finally blocks in the generated subs LexoticException throwee = tc.theLexotic; throwee.target = ((LexoticInstance)cont).target; throwee.payload = in; throw throwee; } public static String tclc(String in, ThreadContext tc) { if (in.length() == 0) return in; int first = in.codePointAt(0); return new String(Character.toChars(Character.toTitleCase(first))) + in.substring(Character.charCount(first)).toLowerCase(); } private static final CallSiteDescriptor SortCSD = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static SixModelObject p6sort(SixModelObject indices, final SixModelObject comparator, final ThreadContext tc) { int elems = (int)indices.elems(tc); SixModelObject[] sortable = new SixModelObject[elems]; for (int i = 0; i < elems; i++) sortable[i] = indices.at_pos_boxed(tc, i); Arrays.sort(sortable, new Comparator<SixModelObject>() { public int compare(SixModelObject a, SixModelObject b) { org.perl6.nqp.runtime.Ops.invokeDirect(tc, comparator, SortCSD, new Object[] { a, b }); return (int)org.perl6.nqp.runtime.Ops.result_i(tc.curFrame); } }); for (int i = 0; i < elems; i++) indices.bind_pos_boxed(tc, i, sortable[i]); return indices; } public static long p6stateinit(ThreadContext tc) { return tc.curFrame.stateInit ? 1 : 0; } public static SixModelObject p6setfirstflag(SixModelObject codeObj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); ThreadExt tcx = key.getTC(tc); tcx.firstPhaserCodeBlock = codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); return codeObj; } public static long p6takefirstflag(ThreadContext tc) { ThreadExt tcx = key.getTC(tc); boolean matches = tcx.firstPhaserCodeBlock == tc.curFrame.codeRef; tcx.firstPhaserCodeBlock = null; return matches ? 1 : 0; } private static final CallSiteDescriptor dispVivifier = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); private static final CallSiteDescriptor dispThrower = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_STR }, null); public static SixModelObject p6finddispatcher(String usage, ThreadContext tc) { SixModelObject dispatcher = null; CallFrame ctx = tc.curFrame; while (ctx != null) { /* Do we have a dispatcher here? */ StaticCodeInfo sci = ctx.codeRef.staticInfo; Integer dispLexIdx = sci.oTryGetLexicalIdx("$*DISPATCHER"); if (dispLexIdx != null) { SixModelObject maybeDispatcher = ctx.oLex[dispLexIdx]; if (maybeDispatcher != null) { dispatcher = maybeDispatcher; if (dispatcher instanceof TypeObject) { /* Need to vivify it. */ SixModelObject meth = org.perl6.nqp.runtime.Ops.findmethod(dispatcher, "vivify_for", tc); SixModelObject p6sub = ctx.codeRef.codeObject; SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = ctx; SixModelObject CallCapture = tc.gc.CallCapture; CallCaptureInstance cc = (CallCaptureInstance)CallCapture.st.REPR.allocate(tc, CallCapture.st); cc.descriptor = ctx.csd; cc.args = ctx.args; org.perl6.nqp.runtime.Ops.invokeDirect(tc, meth, dispVivifier, new Object[] { dispatcher, p6sub, wrap, cc }); dispatcher = org.perl6.nqp.runtime.Ops.result_o(tc.curFrame); ctx.oLex[dispLexIdx] = dispatcher; } break; } } /* Follow dynamic chain. */ ctx = ctx.caller; } if (dispatcher == null) { SixModelObject thrower = getThrower(tc, "X::NoDispatcher"); if (thrower == null) { ExceptionHandling.dieInternal(tc, usage + " is not in the dynamic scope of a dispatcher"); } else { org.perl6.nqp.runtime.Ops.invokeDirect(tc, thrower, dispThrower, new Object[] { usage }); } } return dispatcher; } public static SixModelObject p6argsfordispatcher(SixModelObject disp, ThreadContext tc) { SixModelObject result = null; CallFrame ctx = tc.curFrame; while (ctx != null) { /* Do we have the dispatcher we're looking for? */ StaticCodeInfo sci = ctx.codeRef.staticInfo; Integer dispLexIdx = sci.oTryGetLexicalIdx("$*DISPATCHER"); if (dispLexIdx != null) { SixModelObject maybeDispatcher = ctx.oLex[dispLexIdx]; if (maybeDispatcher == disp) { /* Found; grab args. */ SixModelObject CallCapture = tc.gc.CallCapture; CallCaptureInstance cc = (CallCaptureInstance)CallCapture.st.REPR.allocate(tc, CallCapture.st); cc.descriptor = ctx.csd; cc.args = ctx.args; result = cc; break; } } /* Follow dynamic chain. */ ctx = ctx.caller; } if (result == null) throw ExceptionHandling.dieInternal(tc, "Could not find arguments for dispatcher"); return result; } public static SixModelObject p6decodelocaltime(long sinceEpoch, ThreadContext tc) { // Get calendar for current local host's timezone. Calendar c = Calendar.getInstance(); c.setTimeInMillis(sinceEpoch * 1000); // Populate result int array. SixModelObject BOOTIntArray = tc.gc.BOOTIntArray; SixModelObject result = BOOTIntArray.st.REPR.allocate(tc, BOOTIntArray.st); tc.native_i = c.get(Calendar.SECOND); result.bind_pos_native(tc, 0); tc.native_i = c.get(Calendar.MINUTE); result.bind_pos_native(tc, 1); tc.native_i = c.get(Calendar.HOUR_OF_DAY); result.bind_pos_native(tc, 2); tc.native_i = c.get(Calendar.DAY_OF_MONTH); result.bind_pos_native(tc, 3); tc.native_i = c.get(Calendar.MONTH) + 1; result.bind_pos_native(tc, 4); tc.native_i = c.get(Calendar.YEAR); result.bind_pos_native(tc, 5); return result; } }
package edu.umd.cs.findbugs; /** * A BugCode is an abbreviation that is shared among some number * of BugPatterns. For example, the code "HE" is shared by * all of the BugPatterns that represent hashcode/equals * violations. * * @author David Hovemeyer * @see BugPattern */ public class BugCode { private final String abbrev; private final String description; /** * Constructor. * * @param abbrev the abbreviation for the bug code * @param description a short textual description of the class of bug pattern * represented by this bug code */ public BugCode(String abbrev, String description) { this.abbrev = abbrev; this.description = description; } /** * Get the abbreviation for this bug code. */ public String getAbbrev() { return abbrev; } /** * Get the short textual description of the bug code. */ public String getDescription() { return description; } } // vim:ts=4
package edu.umd.cs.findbugs; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.dom4j.DocumentException; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.URLClassPath; import edu.umd.cs.findbugs.filter.Filter; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.xml.OutputStreamXMLOutput; import edu.umd.cs.findbugs.xml.XMLAttributeList; import edu.umd.cs.findbugs.xml.XMLOutput; import edu.umd.cs.findbugs.xml.XMLOutputUtil; import edu.umd.cs.findbugs.xml.XMLWriteable; /** * A project in the GUI. * This consists of some number of Jar files to analyze for bugs, and optionally * <p/> * <ul> * <li> some number of source directories, for locating the program's * source code * <li> some number of auxiliary classpath entries, for locating classes * referenced by the program which the user doesn't want to analyze * <li> some number of boolean options * </ul> * * @author David Hovemeyer */ public class Project implements XMLWriteable { private static final boolean DEBUG = SystemProperties.getBoolean("findbugs.project.debug"); private File currentWorkingDirectory; /** * Project filename. */ @Deprecated private String projectFileName; private String projectName; /** * Options. */ private Map<String, Boolean> optionsMap; /** * The list of project files. */ private List<String> fileList; /** * The list of source directories. */ private List<String> srcDirList; /** * The list of auxiliary classpath entries. */ private List<String> auxClasspathEntryList; /** * Flag to indicate that this Project has been modified. */ private boolean isModified; /** * Constant used to name anonymous projects. */ public static final String UNNAMED_PROJECT = "<<unnamed project>>"; private long timestamp = 0L; @NonNull private Filter suppressionFilter = new Filter(); /** * Create an anonymous project. */ public Project() { this.projectFileName = UNNAMED_PROJECT; optionsMap = new HashMap<String, Boolean>(); optionsMap.put(RELATIVE_PATHS, Boolean.FALSE); fileList = new LinkedList<String>(); srcDirList = new LinkedList<String>(); auxClasspathEntryList = new LinkedList<String>(); isModified = false; } /** * Return an exact copy of this Project. */ public Project duplicate() { Project dup = new Project(); dup.projectFileName = this.projectFileName; dup.currentWorkingDirectory = this.currentWorkingDirectory; dup.optionsMap.clear(); dup.optionsMap.putAll(this.optionsMap); dup.fileList.addAll(this.fileList); dup.srcDirList.addAll(this.srcDirList); dup.auxClasspathEntryList.addAll(this.auxClasspathEntryList); dup.timestamp = timestamp; return dup; } /** * add information from project2 to this project */ public void add(Project project2) { optionsMap.putAll(project2.optionsMap); fileList = appendWithoutDuplicates(fileList, project2.fileList); srcDirList = appendWithoutDuplicates(srcDirList, project2.srcDirList); auxClasspathEntryList = appendWithoutDuplicates(auxClasspathEntryList, project2.auxClasspathEntryList); } public static <T> List<T> appendWithoutDuplicates(List<T> lst1, List<T> lst2) { LinkedHashSet<T> joined = new LinkedHashSet<T>(lst1); joined.addAll(lst2); return new ArrayList<T>(joined); } public void setCurrentWorkingDirectory(File f) { this.currentWorkingDirectory = f; } /** * Return whether or not this Project has unsaved modifications. */ public boolean isModified() { return isModified; } /** * Set whether or not this Project has unsaved modifications. */ public void setModified(boolean isModified) { this.isModified = isModified; } /** * Get the project filename. */ @Deprecated public String getProjectFileName() { return projectFileName; } /** * Set the project filename. * * @param projectFileName the new filename */ @Deprecated public void setProjectFileName(String projectFileName) { this.projectFileName = projectFileName; } /** * Add a file to the project. * * @param fileName the file to add * @return true if the file was added, or false if the * file was already present */ public boolean addFile(String fileName) { return addToListInternal(fileList, makeAbsoluteCWD(fileName)); } /** * Add a source directory to the project. * @param dirName the directory to add * @return true if the source directory was added, or false if the * source directory was already present */ public boolean addSourceDir(String dirName) { return addToListInternal(srcDirList, makeAbsoluteCWD(dirName)); } /** * Retrieve the Options value. * * @param option the name of option to get * @return the value of the option */ public boolean getOption(String option) { Boolean value = optionsMap.get(option); return value != null && value.booleanValue(); } /** * Get the number of files in the project. * * @return the number of files in the project */ public int getFileCount() { return fileList.size(); } /** * Get the given file in the list of project files. * * @param num the number of the file in the list of project files * @return the name of the file */ public String getFile(int num) { return fileList.get(num); } /** * Remove file at the given index in the list of project files * * @param num index of the file to remove in the list of project files */ public void removeFile(int num) { fileList.remove(num); isModified = true; } /** * Get the list of files, directories, and zip files in the project. */ public List<String> getFileList() { return fileList; } /** * Get the number of source directories in the project. * * @return the number of source directories in the project */ public int getNumSourceDirs() { return srcDirList.size(); } /** * Get the given source directory. * * @param num the number of the source directory * @return the source directory */ public String getSourceDir(int num) { return srcDirList.get(num); } /** * Remove source directory at given index. * * @param num index of the source directory to remove */ public void removeSourceDir(int num) { srcDirList.remove(num); isModified = true; } /** * Get project files as an array of Strings. */ public String[] getFileArray() { return fileList.toArray(new String[fileList.size()]); } /** * Get source dirs as an array of Strings. */ public String[] getSourceDirArray() { return srcDirList.toArray(new String[srcDirList.size()]); } /** * Get the source dir list. */ public List<String> getSourceDirList() { return srcDirList; } /** * Add an auxiliary classpath entry * * @param auxClasspathEntry the entry * @return true if the entry was added successfully, or false * if the given entry is already in the list */ public boolean addAuxClasspathEntry(String auxClasspathEntry) { return addToListInternal(auxClasspathEntryList, makeAbsoluteCWD(auxClasspathEntry)); } /** * Get the number of auxiliary classpath entries. */ public int getNumAuxClasspathEntries() { return auxClasspathEntryList.size(); } /** * Get the n'th auxiliary classpath entry. */ public String getAuxClasspathEntry(int n) { return auxClasspathEntryList.get(n); } /** * Remove the n'th auxiliary classpath entry. */ public void removeAuxClasspathEntry(int n) { auxClasspathEntryList.remove(n); isModified = true; } /** * Return the list of aux classpath entries. */ public List<String> getAuxClasspathEntryList() { return auxClasspathEntryList; } /** * Worklist item for finding implicit classpath entries. */ private static class WorkListItem { private URL url; /** * Constructor. * * @param url the URL of the Jar or Zip file */ public WorkListItem(URL url) { this.url = url; } /** * Get URL of Jar/Zip file. */ public URL getURL() { return this.url; } } /** * Worklist for finding implicit classpath entries. */ private static class WorkList { private LinkedList<WorkListItem> itemList; private HashSet<String> addedSet; /** * Constructor. * Creates an empty worklist. */ public WorkList() { this.itemList = new LinkedList<WorkListItem>(); this.addedSet = new HashSet<String>(); } /** * Create a URL from a filename specified in the project file. */ public URL createURL(String fileName) throws MalformedURLException { String protocol = URLClassPath.getURLProtocol(fileName); if (protocol == null) { fileName = "file:" + fileName; } return new URL(fileName); } /** * Create a URL of a file relative to another URL. */ public URL createRelativeURL(URL base, String fileName) throws MalformedURLException { return new URL(base, fileName); } /** * Add a worklist item. * * @param item the WorkListItem representing a zip/jar file to be examined * @return true if the item was added, false if not (because it was * examined already) */ public boolean add(WorkListItem item) { if (DEBUG) { System.out.println("Adding " + item.getURL().toString()); } if (!addedSet.add(item.getURL().toString())) { if (DEBUG) { System.out.println("\t==> Already processed"); } return false; } itemList.add(item); return true; } /** * Return whether or not the worklist is empty. */ public boolean isEmpty() { return itemList.isEmpty(); } /** * Get the next item in the worklist. */ public WorkListItem getNextItem() { return itemList.removeFirst(); } } /** * Return the list of implicit classpath entries. The implicit * classpath is computed from the closure of the set of jar files * that are referenced by the <code>"Class-Path"</code> attribute * of the manifest of the any jar file that is part of this project * or by the <code>"Class-Path"</code> attribute of any directly or * indirectly referenced jar. The referenced jar files that exist * are the list of implicit classpath entries. * * @deprecated FindBugs2 and ClassPathBuilder take care of this automatically */ @Deprecated public List<String> getImplicitClasspathEntryList() { final LinkedList<String> implicitClasspath = new LinkedList<String>(); WorkList workList = new WorkList(); // Prime the worklist by adding the zip/jar files // in the project. for (String fileName : fileList) { try { URL url = workList.createURL(fileName); WorkListItem item = new WorkListItem(url); workList.add(item); } catch (MalformedURLException ignore) { // Ignore } } // Scan recursively. while (!workList.isEmpty()) { WorkListItem item = workList.getNextItem(); processComponentJar(item.getURL(), workList, implicitClasspath); } return implicitClasspath; } /** * Examine the manifest of a single zip/jar file for implicit * classapth entries. * * @param jarFileURL URL of the zip/jar file * @param workList worklist of zip/jar files to examine * @param implicitClasspath list of implicit classpath entries found */ private void processComponentJar(URL jarFileURL, WorkList workList, List<String> implicitClasspath) { if (DEBUG) { System.out.println("Processing " + jarFileURL.toString()); } if (!jarFileURL.toString().endsWith(".zip") && !jarFileURL.toString().endsWith(".jar")) { return; } try { URL manifestURL = new URL("jar:" + jarFileURL.toString() + "!/META-INF/MANIFEST.MF"); InputStream in = null; try { in = manifestURL.openStream(); Manifest manifest = new Manifest(in); Attributes mainAttrs = manifest.getMainAttributes(); String classPath = mainAttrs.getValue("Class-Path"); if (classPath != null) { String[] fileList = classPath.split("\\s+"); for (String jarFile : fileList) { URL referencedURL = workList.createRelativeURL(jarFileURL, jarFile); if (workList.add(new WorkListItem(referencedURL))) { implicitClasspath.add(referencedURL.toString()); if (DEBUG) { System.out.println("Implicit jar: " + referencedURL.toString()); } } } } } finally { if (in != null) { in.close(); } } } catch (IOException ignore) { // Ignore } } private static final String OPTIONS_KEY = "[Options]"; private static final String JAR_FILES_KEY = "[Jar files]"; private static final String SRC_DIRS_KEY = "[Source dirs]"; private static final String AUX_CLASSPATH_ENTRIES_KEY = "[Aux classpath entries]"; // Option keys public static final String RELATIVE_PATHS = "relative_paths"; /** * Save the project to an output file. * * @param outputFile name of output file * @param useRelativePaths true if the project should be written * using only relative paths * @param relativeBase if useRelativePaths is true, * this file is taken as the base directory in terms of which * all files should be made relative * @throws IOException if an error occurs while writing */ @Deprecated public void write(String outputFile, boolean useRelativePaths, String relativeBase) throws IOException { PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile))); try { writer.println(JAR_FILES_KEY); for (String jarFile : fileList) { if (useRelativePaths) { jarFile = convertToRelative(jarFile, relativeBase); } writer.println(jarFile); } writer.println(SRC_DIRS_KEY); for (String srcDir : srcDirList) { if (useRelativePaths) { srcDir = convertToRelative(srcDir, relativeBase); } writer.println(srcDir); } writer.println(AUX_CLASSPATH_ENTRIES_KEY); for (String auxClasspathEntry : auxClasspathEntryList) { if (useRelativePaths) { auxClasspathEntry = convertToRelative(auxClasspathEntry, relativeBase); } writer.println(auxClasspathEntry); } if (useRelativePaths) { writer.println(OPTIONS_KEY); writer.println(RELATIVE_PATHS + "=true"); } } finally { writer.close(); } // Project successfully saved isModified = false; } public static Project readXML(File f) throws IOException, DocumentException, SAXException { Project project = new Project(); InputStream in = new BufferedInputStream(new FileInputStream(f)); try { String tag = Util.getXMLType(in); SAXBugCollectionHandler handler; if (tag.equals("Project")) { handler = new SAXBugCollectionHandler(project, f); } else if (tag.equals("BugCollection")) { SortedBugCollection bugs = new SortedBugCollection(); handler = new SAXBugCollectionHandler(bugs, project, f); } else { throw new IOException("Can't load a project from a " + tag + " file"); } XMLReader xr = null; if (true) { try { xr = XMLReaderFactory.createXMLReader(); } catch (SAXException e) { AnalysisContext.logError("Couldn't create XMLReaderFactory", e); } } // if (xr == null) { // xr = new org.dom4j.io.aelfred.SAXDriver(); xr.setContentHandler(handler); xr.setErrorHandler(handler); Reader reader = Util.getReader(in); xr.parse(new InputSource(reader)); } finally { in.close(); } // Presumably, project is now up-to-date project.setModified(false); return project; } public void writeXML(File f) throws IOException { OutputStream out = new FileOutputStream(f); XMLOutput xmlOutput = new OutputStreamXMLOutput(out); try { writeXML(xmlOutput); } finally { xmlOutput.finish(); } } /** * Read the project from an input file. * This method should only be used on an empty Project * (created with the default constructor). * * @param inputFile name of the input file to read the project from * @throws IOException if an error occurs while reading */ public void read(String inputFile) throws IOException { if (isModified) { throw new IllegalStateException("Reading into a modified Project!"); } // Make the input file absolute, if necessary File file = new File(inputFile); if (!file.isAbsolute()) { inputFile = file.getAbsolutePath(); } // Store the project filename setProjectFileName(inputFile); BufferedReader reader = null; try { reader = new BufferedReader(Util.getFileReader(inputFile)); String line; line = getLine(reader); if (line == null || !line.equals(JAR_FILES_KEY)) { throw new IOException("Bad format: missing jar files key"); } while ((line = getLine(reader)) != null && !line.equals(SRC_DIRS_KEY)) { addToListInternal(fileList, line); } if (line == null) { throw new IOException("Bad format: missing source dirs key"); } while ((line = getLine(reader)) != null && !line.equals(AUX_CLASSPATH_ENTRIES_KEY)) { addToListInternal(srcDirList, line); } // The list of aux classpath entries is optional if (line != null) { while ((line = getLine(reader)) != null) { if (line.equals(OPTIONS_KEY)) { break; } addToListInternal(auxClasspathEntryList, line); } } // The Options section is also optional if (line != null && line.equals(OPTIONS_KEY)) { while ((line = getLine(reader)) != null && !line.equals(JAR_FILES_KEY)) { parseOption(line); } } // If this project has the relative paths option set, // resolve all internal relative paths into absolute // paths, using the absolute path of the project // file as a base directory. if (getOption(RELATIVE_PATHS)) { makeListAbsoluteProject(fileList); makeListAbsoluteProject(srcDirList); makeListAbsoluteProject(auxClasspathEntryList); } // Clear the modification flag set by the various "add" methods. isModified = false; } finally { if (reader != null) { reader.close(); } } } /** * Read Project from named file. * * @param argument command line argument containing project file name * @return the Project * @throws IOException */ public static Project readProject(String argument) throws IOException { String projectFileName = argument; File projectFile = new File(projectFileName); if (projectFile.isDirectory()) { // New-style (GUI2) project directory. // We read in the bug collection in order to read the project // information as a side effect. // Inefficient, but effective. String name = projectFile.getAbsolutePath() + File.separator + projectFile.getName() + ".xml"; File f = new File(name); SortedBugCollection bugCollection = new SortedBugCollection(); try { Project project = new Project(); bugCollection.readXML(f.getPath(), project); return project; } catch (DocumentException e) { IOException ioe = new IOException("Couldn't read saved XML in project directory"); ioe.initCause(e); throw ioe; } } else if (projectFileName.endsWith(".xml") || projectFileName.endsWith(".fbp")) { try { return Project.readXML(projectFile); } catch (DocumentException e) { IOException ioe = new IOException("Couldn't read saved FindBugs project"); ioe.initCause(e); throw ioe; } catch (SAXException e) { IOException ioe = new IOException("Couldn't read saved FindBugs project"); ioe.initCause(e); throw ioe; } } else { // Old-style (original GUI) project file // Convert project file to be an absolute path projectFileName = new File(projectFileName).getAbsolutePath(); try { Project project = new Project(); project.read(projectFileName); return project; } catch (IOException e) { System.err.println("Error opening " + projectFileName); e.printStackTrace(System.err); throw e; } } } /** * Read a line from a BufferedReader, ignoring blank lines * and comments. */ private static String getLine(BufferedReader reader) throws IOException { String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.equals("") && !line.startsWith(" break; } } return line; } public String projectNameFromProjectFileName() { String name = projectFileName; int lastSep = name.lastIndexOf(File.separatorChar); if (lastSep >= 0) { name = name.substring(lastSep + 1); } int dot = name.lastIndexOf('.'); if (dot >= 0) { name = name.substring(0, dot); } return name; } /** * Convert to a string in a nice (displayable) format. */ @Override public String toString() { if(projectName != null) { return projectName; } // TODO Andrei: if this old stuff is not more used, delete it String name = projectFileName; int lastSep = name.lastIndexOf(File.separatorChar); if (lastSep >= 0) { name = name.substring(lastSep + 1); } //int dot = name.lastIndexOf('.'); //Don't hide every suffix--some are informative and/or disambiguative. int dot = (name.endsWith(".fb") ? name.length()-3 : -1); if (dot >= 0) { name = name.substring(0, dot); } return name; } /** * Transform a user-entered filename into a proper filename, * by adding the ".fb" file extension if it isn't already present. */ public static String transformFilename(String fileName) { if (!fileName.endsWith(".fb")) { fileName = fileName + ".fb"; } return fileName; } static final String JAR_ELEMENT_NAME = "Jar"; static final String AUX_CLASSPATH_ENTRY_ELEMENT_NAME = "AuxClasspathEntry"; static final String SRC_DIR_ELEMENT_NAME = "SrcDir"; static final String FILENAME_ATTRIBUTE_NAME = "filename"; static final String PROJECTNAME_ATTRIBUTE_NAME = "projectName"; public void writeXML(XMLOutput xmlOutput) throws IOException { writeXML(xmlOutput, null); } public void writeXML(XMLOutput xmlOutput, @CheckForNull Object destination) throws IOException { XMLAttributeList attributeList = new XMLAttributeList().addAttribute(FILENAME_ATTRIBUTE_NAME, getProjectFileName()); if (getProjectName() != null) { attributeList = attributeList.addAttribute(PROJECTNAME_ATTRIBUTE_NAME, getProjectName()); } xmlOutput.openTag( BugCollection.PROJECT_ELEMENT_NAME, attributeList ); XMLOutputUtil.writeElementList(xmlOutput, JAR_ELEMENT_NAME, fileList); XMLOutputUtil.writeElementList(xmlOutput, AUX_CLASSPATH_ENTRY_ELEMENT_NAME, auxClasspathEntryList); XMLOutputUtil.writeElementList(xmlOutput, SRC_DIR_ELEMENT_NAME, srcDirList); if (suppressionFilter != null && !suppressionFilter.isEmpty()) { xmlOutput.openTag("SuppressionFilter"); suppressionFilter.writeBodyAsXML(xmlOutput); xmlOutput.closeTag("SuppressionFilter"); } xmlOutput.closeTag(BugCollection.PROJECT_ELEMENT_NAME); } List<String> makeRelative(List<String> files, @CheckForNull Object destination) { if (destination == null) { return files; } if (currentWorkingDirectory == null) { return files; } if (destination instanceof File) { File where = (File)destination; if (where.getParentFile().equals(currentWorkingDirectory)) { List<String> result = new ArrayList<String>(files.size()); String root = where.getParent(); for(String s : files) { if (s.startsWith(root)) { result.add(s.substring(root.length())); } else { result.add(s); } } return result; } } return files; } /** * Parse one line in the [Options] section. * * @param option one line in the [Options] section */ private void parseOption(String option) throws IOException { int equalPos = option.indexOf("="); if (equalPos < 0) { throw new IOException("Bad format: invalid option format"); } String name = option.substring(0, equalPos); String value = option.substring(equalPos + 1); optionsMap.put(name, Boolean.valueOf(value)); } /** * Hack for whether files are case insensitive. * For now, we'll assume that Windows is the only * case insensitive OS. (OpenVMS users, * feel free to submit a patch :-) */ private static final boolean FILE_IGNORE_CASE = SystemProperties.getProperty("os.name", "unknown").startsWith("Windows"); /** * Converts a full path to a relative path if possible * * @param srcFile path to convert * @return the converted filename */ private String convertToRelative(String srcFile, String base) { String slash = SystemProperties.getProperty("file.separator"); if (FILE_IGNORE_CASE) { srcFile = srcFile.toLowerCase(); base = base.toLowerCase(); } if (base.equals(srcFile)) { return "."; } if (!base.endsWith(slash)) { base = base + slash; } if (base.length() <= srcFile.length()) { String root = srcFile.substring(0, base.length()); if (root.equals(base)) { // Strip off the base directory, make relative return "." + SystemProperties.getProperty("file.separator") + srcFile.substring(base.length()); } } //See if we can build a relative path above the base using .. notation int slashPos = srcFile.indexOf(slash); int branchPoint; if (slashPos >= 0) { String subPath = srcFile.substring(0, slashPos); if ((subPath.length() == 0) || base.startsWith(subPath)) { branchPoint = slashPos + 1; slashPos = srcFile.indexOf(slash, branchPoint); while (slashPos >= 0) { subPath = srcFile.substring(0, slashPos); if (base.startsWith(subPath)) { branchPoint = slashPos + 1; } else { break; } slashPos = srcFile.indexOf(slash, branchPoint); } int slashCount = 0; slashPos = base.indexOf(slash, branchPoint); while (slashPos >= 0) { slashCount++; slashPos = base.indexOf(slash, slashPos + 1); } StringBuilder path = new StringBuilder(); String upDir = ".." + slash; for (int i = 0; i < slashCount; i++) { path.append(upDir); } path.append(srcFile.substring(branchPoint)); return path.toString(); } } return srcFile; } /** * Converts a relative path to an absolute path if possible. * * @param fileName path to convert * @return the converted filename */ private String convertToAbsolute(String fileName) throws IOException { // At present relative paths are only calculated if the fileName is // below the project file. This need not be the case, and we could use .. // syntax to move up the tree. (To Be Added) File file = new File(fileName); if (!file.isAbsolute()) { // Only try to make the relative path absolute // if the project file is absolute. File projectFile = new File(projectFileName); if (projectFile.isAbsolute()) { // Get base directory (parent of the project file) String base = new File(projectFileName).getParent(); // Make the file absolute in terms of the parent directory fileName = new File(base, fileName).getCanonicalPath(); } } return fileName; } /** * Make the given filename absolute relative to the * current working directory. */ private String makeAbsoluteCWD(String fileName) { boolean hasProtocol = (URLClassPath.getURLProtocol(fileName) != null); if (hasProtocol) { return fileName; } if (new File(fileName).isAbsolute()) { return fileName; } File relativeToCurrent = new File(currentWorkingDirectory, fileName); if (relativeToCurrent.exists()) { return relativeToCurrent.toString(); } return fileName; } /** * Add a value to given list, making the Project modified * if the value is not already present in the list. * * @param list the list * @param value the value to be added * @return true if the value was not already present in the list, * false otherwise */ private boolean addToListInternal(Collection<String> list, String value) { if (!list.contains(value)) { list.add(value); isModified = true; return true; } else { return false; } } /** * Make the given list of pathnames absolute relative * to the absolute path of the project file. */ private void makeListAbsoluteProject(List<String> list) throws IOException { List<String> replace = new LinkedList<String>(); for (String fileName : list) { fileName = convertToAbsolute(fileName); replace.add(fileName); } list.clear(); list.addAll(replace); } /** * @param timestamp The timestamp to set. */ public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public void addTimestamp(long timestamp) { if (this.timestamp < timestamp) { this.timestamp = timestamp; } } /** * @return Returns the timestamp. */ public long getTimestamp() { return timestamp; } /** * @param projectName The projectName to set. */ public void setProjectName(String projectName) { this.projectName = projectName; } /** * @return Returns the projectName. */ public String getProjectName() { return projectName; } /** * @param suppressionFilter The suppressionFilter to set. */ public void setSuppressionFilter(Filter suppressionFilter) { this.suppressionFilter = suppressionFilter; } /** * @return Returns the suppressionFilter. */ public Filter getSuppressionFilter() { if (suppressionFilter == null) { suppressionFilter = new Filter(); } return suppressionFilter; } } // vim:ts=4
package edu.umd.cs.findbugs; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; /** * Version number and release date information. */ public class Version { /** * Major version number. */ public static final int MAJOR = 1; /** * Minor version number. */ public static final int MINOR = 3; /** * Patch level. */ public static final int PATCHLEVEL = 9; /** * Development version or release candidate? */ public static final boolean IS_DEVELOPMENT = true; /** * Release candidate number. * "0" indicates that the version is not a release candidate. */ public static final int RELEASE_CANDIDATE = 0; /** * Release date. */ public static final String COMPUTED_DATE; public static final String DATE; private static final String COMPUTED_ECLIPSE_DATE; static { SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss z, dd MMMM, yyyy"); SimpleDateFormat eclipseDateFormat = new SimpleDateFormat("yyyyMMdd"); COMPUTED_DATE = dateFormat.format(new Date()); COMPUTED_ECLIPSE_DATE = eclipseDateFormat.format(new Date()) ; } /** * Preview release number. * "0" indicates that the version is not a preview release. */ public static final int PREVIEW = 0; private static final String RELEASE_SUFFIX_WORD = (RELEASE_CANDIDATE > 0 ? "rc" + RELEASE_CANDIDATE : (PREVIEW > 0 ? "preview" + PREVIEW : "dev-" + COMPUTED_ECLIPSE_DATE)); public static final String RELEASE_BASE = MAJOR + "." + MINOR + "." + PATCHLEVEL ; /** * Release version string. */ public static final String COMPUTED_RELEASE = RELEASE_BASE + (IS_DEVELOPMENT ? "-" + RELEASE_SUFFIX_WORD : ""); /** * Release version string. */ public static final String RELEASE; /** * Version of Eclipse plugin. */ public static final String COMPUTED_ECLIPSE_UI_VERSION = RELEASE_BASE + "." + COMPUTED_ECLIPSE_DATE; static { InputStream in = null; String release, date; try { Properties versionProperties = new Properties(); in = Version.class.getResourceAsStream("version.properties"); versionProperties.load(in); release = (String) versionProperties.get("release.number"); date = (String) versionProperties.get("release.date"); if (release == null) release = COMPUTED_RELEASE; if (date == null) date = COMPUTED_DATE; } catch (RuntimeException e) { release = COMPUTED_RELEASE; date = COMPUTED_DATE; } catch (IOException e) { release = COMPUTED_RELEASE; date = COMPUTED_DATE; } finally { try { if (in != null) in.close(); } catch (IOException e) { assert true; // nothing to do here } } RELEASE = release; DATE = date; } /** * FindBugs website. */ public static final String WEBSITE = "http://findbugs.sourceforge.net"; /** * Downloads website. */ public static final String DOWNLOADS_WEBSITE = "http://prdownloads.sourceforge.net/findbugs"; /** * Support email. */ public static final String SUPPORT_EMAIL = "http://findbugs.sourceforge.net/reportingBugs.html"; public static void main(String[] argv) { if (argv.length != 1) usage(); String arg = argv[0]; if (!IS_DEVELOPMENT && RELEASE_CANDIDATE != 0) { throw new IllegalStateException("Non developmental version, but is release candidate " + RELEASE_CANDIDATE); } if (arg.equals("-release")) System.out.println(RELEASE); else if (arg.equals("-date")) System.out.println(DATE); else if (arg.equals("-props")) { System.out.println("release.base=" + RELEASE_BASE); System.out.println("release.number=" + COMPUTED_RELEASE); System.out.println("release.date=" + COMPUTED_DATE); System.out.println("eclipse.ui.version=" + COMPUTED_ECLIPSE_UI_VERSION); System.out.println("findbugs.website=" + WEBSITE); System.out.println("findbugs.downloads.website=" + DOWNLOADS_WEBSITE); } else { usage(); System.exit(1); } } private static void usage() { System.err.println("Usage: " + Version.class.getName() + " (-release|-date|-props)"); } } // vim:ts=4
package com.gallatinsystems.survey.domain; import java.util.HashMap; import java.util.TreeMap; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import com.gallatinsystems.framework.domain.BaseDomain; import com.google.appengine.api.datastore.Key; @PersistenceCapable public class Question extends BaseDomain { private static final long serialVersionUID = -9123426646238761996L; public enum Type { FREE_TEXT, OPTION, NUMBER, GEO, PHOTO, VIDEO, SCAN, TRACK }; private Type type = null; private String tip = null; private String text = null; @NotPersistent private HashMap<String, Translation> translationMap; private Boolean dependentFlag = null; private Boolean allowMultipleFlag = null; private Boolean allowOtherFlag = null; private Key dependentQuestionKey = null; @NotPersistent private TreeMap<Integer, QuestionOption> questionOptionMap = null; private String validationRule = null; @NotPersistent private HashMap<Integer, QuestionHelpMedia> questionHelpMediaMap = null; private Long questionGroupId; private Integer order = null; private Boolean mandatoryFlag = null; private String path = null; public Long getQuestionGroupId() { return questionGroupId; } public void setQuestionGroupId(Long questionGroupId) { this.questionGroupId = questionGroupId; } public HashMap<String, Translation> getTranslationMap() { return translationMap; } public void setTranslationMap(HashMap<String, Translation> translationMap) { this.translationMap = translationMap; } public void addQuestionOption(QuestionOption questionOption) { if (getQuestionOptionMap() == null) setQuestionOptionMap(new TreeMap<Integer, QuestionOption>()); getQuestionOptionMap().put( questionOption.getOrder() != null ? questionOption.getOrder() : getQuestionOptionMap().size() + 1, questionOption); } public void addHelpMedia(Integer order, QuestionHelpMedia questionHelpMedia) { if (getQuestionHelpMediaMap() == null) setQuestionHelpMediaMap(new HashMap<Integer, QuestionHelpMedia>()); getQuestionHelpMediaMap().put(order, questionHelpMedia); } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public Boolean getDependentFlag() { return dependentFlag; } public void setDependentFlag(Boolean dependentFlag) { this.dependentFlag = dependentFlag; } public Boolean getAllowMultipleFlag() { return allowMultipleFlag; } public void setAllowMultipleFlag(Boolean allowMultipleFlag) { this.allowMultipleFlag = allowMultipleFlag; } public Boolean getAllowOtherFlag() { return allowOtherFlag; } public void setAllowOtherFlag(Boolean allowOtherFlag) { this.allowOtherFlag = allowOtherFlag; } public Key getDependentQuestionKey() { return dependentQuestionKey; } public void setDependentQuestionKey(Key dependentQuestionKey) { this.dependentQuestionKey = dependentQuestionKey; } public String getValidationRule() { return validationRule; } public void setValidationRule(String validationRule) { this.validationRule = validationRule; } public void setQuestionOptionMap( TreeMap<Integer, QuestionOption> questionOptionMap) { this.questionOptionMap = questionOptionMap; } public TreeMap<Integer, QuestionOption> getQuestionOptionMap() { return questionOptionMap; } public void setQuestionHelpMediaMap( HashMap<Integer, QuestionHelpMedia> questionHelpMediaMap) { this.questionHelpMediaMap = questionHelpMediaMap; } public HashMap<Integer, QuestionHelpMedia> getQuestionHelpMediaMap() { return questionHelpMediaMap; } public void setOrder(Integer order) { this.order = order; } public Integer getOrder() { return order; } public void setMandatoryFlag(Boolean mandatoryFlag) { this.mandatoryFlag = mandatoryFlag; } public Boolean getMandatoryFlag() { return mandatoryFlag; } public void setPath(String path) { this.path = path; } public String getPath() { return path; } public void setTip(String tip) { this.tip = tip; } public String getTip() { return tip; } public void setText(String text) { this.text = text; } public String getText() { return text; } public void addTranslation(Translation t) { if (translationMap == null) { translationMap = new HashMap<String, Translation>(); } translationMap.put(t.getLanguageCode(), t); } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wyil.transforms; import static wyil.util.SyntaxError.syntaxError; import java.math.BigInteger; import java.util.*; import wyil.ModuleLoader; import wyil.lang.*; import wyil.lang.Block.Entry; import wyil.lang.Code.*; import wyil.transforms.TypePropagation.Env; import wyil.util.*; import wyil.util.dfa.ForwardFlowAnalysis; import wyjc.runtime.BigRational; public class ConstantPropagation extends ForwardFlowAnalysis<ConstantPropagation.Env> { private static final HashMap<Integer,Block.Entry> rewrites = new HashMap<Integer,Block.Entry>(); public ConstantPropagation(ModuleLoader loader) { super(loader); } public Module.TypeDef transform(Module.TypeDef type) { return type; } public Env initialStore() { Env environment = new Env(); int nvars = methodCase.locals().size(); for (int i=0; i != nvars; ++i) { environment.add(null); } return environment; } public Module.Case propagate(Module.Case mcase) { methodCase = mcase; stores = new HashMap<String,Env>(); rewrites.clear(); Env environment = initialStore(); propagate(0,mcase.body().size(), environment); // At this point, we apply the inserts Block body = mcase.body(); Block nbody = new Block(); for(int i=0;i!=body.size();++i) { Block.Entry rewrite = rewrites.get(i); if(rewrite != null) { nbody.add(rewrite); } else { nbody.add(body.get(i)); } } return new Module.Case(nbody,mcase.locals(),mcase.attributes()); } /* protected Block unrollFor(Code.ForAll fall, Block body) { Block blk = new Block(); Collection<Value> values; if(fall.source instanceof Value.List) { Value.List l = (Value.List) fall.source; values = l.values; } else { Value.Set s = (Value.Set) fall.source; values = s.values; } HashMap<String,CExpr> binding = new HashMap<String,CExpr>(); String var = fall.variable.name(); for(Value v : values) { // first, relabel to avoid conflicts Block tmp = Block.relabel(body); // second, substitute value binding.put(var, v); tmp = Block.substitute(binding,tmp); // finally,add to the target blk blk.addAll(tmp); } return blk; } */ public Env propagate(int index, Entry entry, Env environment) { Code code = entry.code; environment = (Env) environment.clone(); if(code instanceof Assert) { infer((Assert)code,entry,environment); } else if(code instanceof BinOp) { infer((BinOp)code,entry,environment); } else if(code instanceof Convert) { infer((Convert)code,entry,environment); } else if(code instanceof Const) { infer((Const)code,entry,environment); } else if(code instanceof Debug) { infer((Debug)code,entry,environment); } else if(code instanceof ExternJvm) { // skip } else if(code instanceof Fail) { // skip } else if(code instanceof FieldLoad) { infer((FieldLoad)code,entry,environment); } else if(code instanceof IndirectInvoke) { infer((IndirectInvoke)code,entry,environment); } else if(code instanceof IndirectSend) { infer((IndirectSend)code,entry,environment); } else if(code instanceof Invoke) { infer((Invoke)code,entry,environment); } else if(code instanceof Label) { // skip } else if(code instanceof ListOp) { infer((ListOp)code,entry,environment); } else if(code instanceof ListLoad) { infer((ListLoad)code,entry,environment); } else if(code instanceof Load) { infer(index,(Load)code,entry,environment); } else if(code instanceof MultiStore) { infer((MultiStore)code,entry,environment); } else if(code instanceof NewDict) { infer((NewDict)code,entry,environment); } else if(code instanceof NewList) { infer((NewList)code,entry,environment); } else if(code instanceof NewRecord) { infer((NewRecord)code,entry,environment); } else if(code instanceof NewSet) { infer((NewSet)code,entry,environment); } else if(code instanceof Return) { infer((Return)code,entry,environment); } else if(code instanceof Send) { infer((Send)code,entry,environment); } else if(code instanceof Store) { infer((Store)code,entry,environment); } else if(code instanceof SetOp) { infer((SetOp)code,entry,environment); } else if(code instanceof UnOp) { infer((UnOp)code,entry,environment); } else { syntaxError("Need to finish type inference " + code,filename,entry); return null; } return environment; } public void infer(Code.Assert code, Block.Entry entry, Env environment) { } public void infer(Code.BinOp code, Block.Entry entry, Env environment) { Value rhs = environment.pop(); Value lhs = environment.pop(); // should evaluate here Value result = null; environment.push(result); } public void infer(Code.Convert code, Block.Entry entry, Env environment) { Value val = environment.pop(); // need to apply conversion here environment.push(null); } public void infer(Code.Const code, Block.Entry entry, Env environment) { environment.push(code.constant); } public void infer(Code.Debug code, Block.Entry entry, Env environment) { environment.pop(); } public void infer(Code.FieldLoad code, Block.Entry entry, Env environment) { Value src = environment.pop(); if(src instanceof Value.Record) { Value.Record rec = (Value.Record) src; environment.push(rec.values.get(code.field)); } else { environment.push(null); } } public void infer(Code.IndirectInvoke code, Block.Entry entry, Env environment) { // TODO: in principle we can do better here in the case that the target // is a constant. This seems pretty unlikely though ... for(int i=0;i!=code.type.params().size();++i) { environment.pop(); } environment.pop(); // target if(code.type.ret() != Type.T_VOID && code.retval) { environment.push(null); } } public void infer(Code.IndirectSend code, Block.Entry entry, Env environment) { // FIXME: need to do something here } public void infer(Code.Invoke code, Block.Entry entry, Env environment) { // TODO: in the case of a function call (rather than an internal message // send), we could potentially evaluate the function in question to give // a constant value. for(int i=0;i!=code.type.params().size();++i) { environment.pop(); } if(code.type.ret() != Type.T_VOID && code.retval) { environment.push(null); } } public void infer(Code.ListOp code, Block.Entry entry, Env environment) { switch(code.lop) { case SUBLIST: { Value end = environment.pop(); Value start = environment.pop(); Value list = environment.pop(); if (list instanceof Value.List && start instanceof Value.Number && end instanceof Value.Number) { Value.Number en = (Value.Number) end; Value.Number st = (Value.Number) start; if (en.value.isInteger() && st.value.isInteger()) { Value.List li = (Value.List) list; int eni = en.value.intValue(); int sti = st.value.intValue(); if (BigRational.valueOf(eni).equals(en.value) && eni >= 0 && eni <= li.values.size() && BigRational.valueOf(sti).equals(st.value) && sti >= 0 && sti <= li.values.size()) { ArrayList<Value> nvals = new ArrayList<Value>(); for (int i = sti; i < eni; ++i) { nvals.add(li.values.get(i)); } environment.push(Value.V_LIST(nvals)); } } } environment.push(null); break; } case APPEND: { Value lhs = environment.pop(); Value rhs = environment.pop(); if(code.dir == OpDir.UNIFORM && lhs instanceof Value.List && rhs instanceof Value.List) { Value.List left = (Value.List) lhs; Value.List right = (Value.List) rhs; ArrayList<Value> values = new ArrayList<Value>(left.values); values.addAll(right.values); environment.push(Value.V_LIST(values)); } else if(code.dir == OpDir.LEFT && lhs instanceof Value.List && rhs instanceof Value) { Value.List left = (Value.List) lhs; Value right = (Value) rhs; ArrayList<Value> values = new ArrayList<Value>(left.values); values.add(right); environment.push(Value.V_LIST(values)); } else if(code.dir == OpDir.RIGHT && lhs instanceof Value && rhs instanceof Value.List) { Value left = (Value) lhs; Value.List right = (Value.List) rhs; ArrayList<Value> values = new ArrayList<Value>(); values.add(left); values.addAll(right.values); environment.push(Value.V_LIST(values)); } else { environment.push(null); } break; } case LENGTHOF: { Value val = environment.pop(); if(val instanceof Value.List) { Value.List list = (Value.List) val; environment.push(Value.V_NUMBER(BigRational .valueOf(list.values.size()))); } else { environment.push(null); } break; } } } public void infer(Code.ListLoad code, Block.Entry entry, Env environment) { Value idx = environment.pop(); Value src = environment.pop(); if (idx instanceof Value.Number && src instanceof Value.List) { Value.Number num = (Value.Number) idx; Value.List list = (Value.List) src; if(num.value.isInteger()) { int i = num.value.intValue(); if (BigRational.valueOf(i).equals(num.value) && i >= 0 && i < list.values.size()) { environment.push(list.values.get(i)); return; } } } environment.push(null); } public void infer(int index, Code.Load code, Block.Entry entry, Env environment) { Value val = environment.get(code.slot); if(val instanceof Value) { // register rewrite entry = new Block.Entry(Code.Const(val), entry.attributes()); rewrites.put(index, entry); } else { rewrites.remove(index); } environment.push(val); } public void infer(Code.MultiStore code, Block.Entry entry, Env environment) { // TO DO: I could definite do more here int npop = code.level - code.fields.size(); for(int i=0;i!=npop;++i) { environment.pop(); } environment.set(code.slot,null); } public void infer(Code.NewDict code, Block.Entry entry, Env environment) { HashMap<Value,Value> values = new HashMap<Value,Value>(); boolean isValue = true; for(int i=0;i!=code.nargs;++i) { Value val = environment.pop(); Value key = environment.pop(); if(key instanceof Value && val instanceof Value) { values.put(key, val); } else { isValue=false; } } if(isValue) { environment.push(Value.V_DICTIONARY(values)); } else { environment.push(null); } } public void infer(Code.NewRecord code, Block.Entry entry, Env environment) { HashMap<String, Value> values = new HashMap<String, Value>(); ArrayList<String> keys = new ArrayList<String>(code.type.keys()); Collections.sort(keys); Collections.reverse(keys); boolean isValue = true; for (String key : keys) { Value val = environment.pop(); if (val instanceof Value) { values.put(key, val); } else { isValue = false; } } if (isValue) { environment.push(Value.V_RECORD(values)); } else { environment.push(null); } } public void infer(Code.NewList code, Block.Entry entry, Env environment) { ArrayList<Value> values = new ArrayList<Value>(); boolean isValue = true; for (int i=0;i!=code.nargs;++i) { Value val = environment.pop(); if (val instanceof Value) { values.add(val); } else { isValue = false; } } if (isValue) { Collections.reverse(values); environment.push(Value.V_LIST(values)); } else { environment.push(null); } } public void infer(Code.NewSet code, Block.Entry entry, Env environment) { HashSet<Value> values = new HashSet<Value>(); boolean isValue = true; for (int i=0;i!=code.nargs;++i) { Value val = environment.pop(); if (val instanceof Value) { values.add(val); } else { isValue = false; } } if (isValue) { environment.push(Value.V_SET(values)); } else { environment.push(null); } } public void infer(Code.Return code, Block.Entry entry, Env environment) { if(code.type != Type.T_VOID) { environment.pop(); } } public void infer(Code.Send code, Block.Entry entry, Env environment) { for(int i=0;i!=code.type.params().size();++i) { environment.pop(); } environment.pop(); // receiver if (code.type.ret() != Type.T_VOID && code.synchronous && code.retval) { environment.push(null); } } public void infer(Code.Store code, Block.Entry entry, Env environment) { environment.set(code.slot, environment.pop()); } public void infer(Code.SetOp code, Block.Entry entry, Env environment) { Value rhs = environment.pop(); Value lhs = environment.pop(); switch (code.sop) { case UNION: { if (code.dir == OpDir.UNIFORM && lhs instanceof Value.Set && rhs instanceof Value.Set) { Value.Set lv = (Value.Set) lhs; Value.Set rv = (Value.Set) rhs; environment.push(lv.union(rv)); } else if(code.dir == OpDir.LEFT && lhs instanceof Value.Set && rhs instanceof Value) { Value.Set lv = (Value.Set) lhs; Value rv = (Value) rhs; environment.push(lv.add(rv)); } else if(code.dir == OpDir.RIGHT && lhs instanceof Value && rhs instanceof Value.Set) { Value lv = (Value) lhs; Value.Set rv = (Value.Set) rhs; environment.push(rv.add(lv)); } else { environment.push(null); } } case DIFFERENCE: { if (code.dir == OpDir.UNIFORM && lhs instanceof Value.Set && rhs instanceof Value.Set) { Value.Set lv = (Value.Set) lhs; Value.Set rv = (Value.Set) rhs; environment.push(lv.difference(rv)); } else if(code.dir == OpDir.LEFT && lhs instanceof Value.Set && rhs instanceof Value) { Value.Set lv = (Value.Set) lhs; Value rv = (Value) rhs; environment.push(lv.remove(rv)); } else if(code.dir == OpDir.RIGHT && lhs instanceof Value && rhs instanceof Value.Set) { Value lv = (Value) lhs; Value.Set rv = (Value.Set) rhs; environment.push(rv.remove(lv)); } else { environment.push(null); } } case INTERSECT: { if (code.dir == OpDir.UNIFORM && lhs instanceof Value.Set && rhs instanceof Value.Set) { Value.Set lv = (Value.Set) lhs; Value.Set rv = (Value.Set) rhs; environment.push(lv.intersect(rv)); } else if(code.dir == OpDir.LEFT && lhs instanceof Value.Set && rhs instanceof Value) { Value.Set lv = (Value.Set) lhs; Value rv = (Value) rhs; if(lv.values.contains(rv)) { HashSet<Value> nset = new HashSet<Value>(); nset.add(rv); environment.push(Value.V_SET(nset)); } else { environment.push(Value.V_SET(Collections.EMPTY_SET)); } } else if(code.dir == OpDir.RIGHT && lhs instanceof Value && rhs instanceof Value.Set) { Value lv = (Value) lhs; Value.Set rv = (Value.Set) rhs; if(rv.values.contains(lv)) { HashSet<Value> nset = new HashSet<Value>(); nset.add(lv); environment.push(Value.V_SET(nset)); } else { environment.push(Value.V_SET(Collections.EMPTY_SET)); } } else { environment.push(null); } } } } public void infer(Code.UnOp code, Block.Entry entry, Env environment) { Value val = environment.pop(); switch(code.uop) { case NEG: { if(val instanceof Value.Number) { Value.Number num = (Value.Number) val; environment.push(Value.V_NUMBER(num.value.negate())); } else { environment.push(null); } } case PROCESSACCESS: case PROCESSSPAWN: environment.push(null); } } public Pair<Env, Env> propagate(int index, Code.IfGoto igoto, Entry stmt, Env environment) { Value rhs = environment.pop(); Value lhs = environment.pop(); return new Pair(environment, environment); } public Pair<Env, Env> propagate(int index, Code.IfType code, Entry stmt, Env environment) { if(code.slot < 0) { Value lhs = environment.pop(); } return new Pair(environment, environment); } public List<Env> propagate(int index, Code.Switch sw, Entry stmt, Env environment) { Value val = environment.pop(); ArrayList<Env> stores = new ArrayList(); for (int i = 0; i != sw.branches.size(); ++i) { stores.add(environment); } return stores; } public Env propagate(int start, int end, Code.Loop loop, Entry stmt, Env environment) { if(loop instanceof Code.ForAll) { Code.ForAll fall = (Code.ForAll) loop; environment.pop(); environment.set(fall.slot,null); } Env oldEnv = null; Env newEnv = null; do { // iterate until a fixed point reached oldEnv = newEnv != null ? newEnv : environment; newEnv = propagate(start+1,end, oldEnv); } while (!newEnv.equals(oldEnv)); return join(environment,newEnv); } public Env join(Env env1, Env env2) { if (env2 == null) { return env1; } else if (env1 == null) { return env2; } Env env = new Env(); for (int i = 0; i != Math.min(env1.size(), env2.size()); ++i) { Value mt = env1.get(i); Value ot = env2.get(i); if (ot instanceof Value && mt instanceof Value && ot.equals(mt)) { env.add(mt); } else { env.add(null); } } return env; } public static class Env extends ArrayList<Value> { public Env() { } public Env(Collection<Value> v) { super(v); } public void push(Value t) { add(t); } public Value top() { return get(size()-1); } public Value pop() { return remove(size()-1); } public Env clone() { return new Env(this); } } }
package sk.henrichg.phoneprofiles; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.os.Parcel; import android.os.Parcelable; import android.preference.Preference; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; public class ImageViewPreference extends Preference { private String imageIdentifier; private boolean isImageResourceID; private String imageSource; private ImageView imageView; private Context prefContext; CharSequence preferenceTitle; public static int RESULT_LOAD_IMAGE = 1970; public ImageViewPreference(Context context, AttributeSet attrs) { super(context, attrs); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageViewPreference); // resource, resource_file, file imageSource = typedArray.getString( R.styleable.ImageViewPreference_imageSource); if (imageSource.equals("file")) { imageIdentifier = "-"; isImageResourceID = false; } else { imageIdentifier = GlobalData.PROFILE_ICON_DEFAULT; isImageResourceID = true; } prefContext = context; preferenceTitle = getTitle(); setWidgetLayoutResource(R.layout.imageview_preference); // resource na layout custom preference - TextView-ImageView typedArray.recycle(); } //@Override protected void onBindView(View view) { super.onBindView(view); //imageTitle = (TextView)view.findViewById(R.id.imageview_pref_label); // resource na image title //imageTitle.setText(preferenceTitle); imageView = (ImageView)view.findViewById(R.id.imageview_pref_imageview); // resource na Textview v custom preference layoute if (imageView != null) { if (isImageResourceID) { // je to resource id int res = prefContext.getResources().getIdentifier(imageIdentifier, "drawable", prefContext.getPackageName()); imageView.setImageResource(res); // resource na ikonu } else { // je to file Resources resources = prefContext.getResources(); int height = (int) resources.getDimension(android.R.dimen.app_icon_size); int width = (int) resources.getDimension(android.R.dimen.app_icon_size); Bitmap bitmap = BitmapManipulator.resampleBitmap(imageIdentifier, width, height); //if (bitmap != null) imageView.setImageBitmap(bitmap); } } } @Override protected void onClick() { // klik na preference if (imageSource.equals("resource_file") || imageSource.equals("resource")) { final ImageViewPreferenceDialog dialog = new ImageViewPreferenceDialog(prefContext, this, imageSource, imageIdentifier, isImageResourceID); dialog.show(); } else { // zavolat galeriu na vyzdvihnutie image startGallery(); } } @Override protected Object onGetDefaultValue(TypedArray a, int index) { super.onGetDefaultValue(a, index); return a.getString(index); // ikona bude vratena ako retazec } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { if (restoreValue) { // restore state String value = getPersistedString(imageIdentifier+"|"+((isImageResourceID) ? "1" : "0")); String[] splits = value.split("\\|"); try { imageIdentifier = splits[0]; } catch (Exception e) { imageIdentifier = GlobalData.PROFILE_ICON_DEFAULT; } try { isImageResourceID = (splits[1].equals("1")) ? true : false; } catch (Exception e) { isImageResourceID = true; } } else { // set state String value = (String) defaultValue; String[] splits = value.split("\\|"); try { imageIdentifier = splits[0]; } catch (Exception e) { imageIdentifier = GlobalData.PROFILE_ICON_DEFAULT; } try { isImageResourceID = (splits[1].equals("1")) ? true : false; } catch (Exception e) { isImageResourceID = true; } persistString(value); } } @Override protected Parcelable onSaveInstanceState() { // ulozime instance state - napriklad kvoli zmene orientacie final Parcelable superState = super.onSaveInstanceState(); if (isPersistent()) { // netreba ukladat, je ulozene persistentne return superState; } // ulozenie istance state final SavedState myState = new SavedState(superState); myState.imageIdentifierAndType = imageIdentifier+"|"+((isImageResourceID) ? "1" : "0"); return myState; } @Override protected void onRestoreInstanceState(Parcelable state) { if (!state.getClass().equals(SavedState.class)) { // Didn't save state for us in onSaveInstanceState super.onRestoreInstanceState(state); return; } // restore instance state SavedState myState = (SavedState)state; super.onRestoreInstanceState(myState.getSuperState()); String value = (String) myState.imageIdentifierAndType; String[] splits = value.split("\\|"); try { imageIdentifier = splits[0]; } catch (Exception e) { imageIdentifier = GlobalData.PROFILE_ICON_DEFAULT; } try { isImageResourceID = (splits[1].equals("1")) ? true : false; } catch (Exception e) { isImageResourceID = true; } notifyChanged(); } public String getImageIdentifier() { return imageIdentifier; } public boolean getIsImageResourceID() { return isImageResourceID; } public void setImageIdentifierAndType(String newImageIdentifier, boolean newIsImageResourceID) { String newValue = newImageIdentifier+"|"+((newIsImageResourceID) ? "1" : "0"); if (!callChangeListener(newValue)) { // nema sa nova hodnota zapisat return; } String[] splits = newValue.split("\\|"); try { imageIdentifier = splits[0]; } catch (Exception e) { imageIdentifier = GlobalData.PROFILE_ICON_DEFAULT; } try { isImageResourceID = (splits[1].equals("1")) ? true : false; } catch (Exception e) { isImageResourceID = true; } // zapis do preferences persistString(newValue); // Data sa zmenili,notifikujeme notifyChanged(); } public void startGallery() { Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // hm, neda sa ziskat aktivita z preference, tak vyuzivam static metodu ProfilePreferencesFragment.setChangedImageViewPreference(this); ProfilePreferencesFragment.getPreferencesActivity().startActivityForResult(intent, RESULT_LOAD_IMAGE); } // SavedState class private static class SavedState extends BaseSavedState { String imageIdentifierAndType; public SavedState(Parcel source) { super(source); // restore image identifier and type imageIdentifierAndType = source.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); // save image identifier and type dest.writeString(imageIdentifierAndType); } public SavedState(Parcelable superState) { super(superState); } @SuppressWarnings("unused") public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
package com.intellij.openapi.vcs.changes; import com.intellij.icons.AllIcons; import com.intellij.ide.CommonActionsManager; import com.intellij.ide.TreeExpander; import com.intellij.ide.dnd.DnDEvent; import com.intellij.ide.ui.customization.CustomActionsSchema; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.progress.EmptyProgressIndicator; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.SimpleToolWindowPanel; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Factory; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.registry.RegistryValue; import com.intellij.openapi.util.registry.RegistryValueListener; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.actions.ShowDiffPreviewAction; import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager; import com.intellij.openapi.vcs.changes.ui.*; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.problems.ProblemListener; import com.intellij.ui.GuiUtils; import com.intellij.ui.JBColor; import com.intellij.ui.components.panels.Wrapper; import com.intellij.ui.content.Content; import com.intellij.util.Alarm; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.components.BorderLayoutPanel; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.util.xmlb.annotations.Attribute; import com.intellij.util.xmlb.annotations.XCollection; import com.intellij.vcs.commit.*; import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Function; import static com.intellij.openapi.actionSystem.EmptyAction.registerWithShortcutSet; import static com.intellij.openapi.vcs.changes.ui.ChangesTree.DEFAULT_GROUPING_KEYS; import static com.intellij.openapi.vcs.changes.ui.ChangesTree.GROUP_BY_ACTION_GROUP; import static com.intellij.util.containers.ContainerUtil.set; import static com.intellij.util.ui.JBUI.Panels.simplePanel; import static com.intellij.vcs.commit.ToggleChangesViewCommitUiActionKt.isToggleCommitUi; import static java.util.Arrays.asList; @State( name = "ChangesViewManager", storages = @Storage(StoragePathMacros.WORKSPACE_FILE) ) public class ChangesViewManager implements ChangesViewEx, PersistentStateComponent<ChangesViewManager.State>, Disposable { private static final Logger LOG = Logger.getInstance(ChangesViewManager.class); private static final String CHANGES_VIEW_PREVIEW_SPLITTER_PROPORTION = "ChangesViewManager.DETAILS_SPLITTER_PROPORTION"; @NotNull private final Project myProject; @NotNull private ChangesViewManager.State myState = new ChangesViewManager.State(); @Nullable private ChangesViewToolWindowPanel myToolWindowPanel; @NotNull public static ChangesViewI getInstance(@NotNull Project project) { return project.getService(ChangesViewI.class); } @NotNull public static ChangesViewEx getInstanceEx(@NotNull Project project) { return (ChangesViewEx)getInstance(project); } public ChangesViewManager(@NotNull Project project) { myProject = project; } public static class ContentPreloader implements ChangesViewContentProvider.Preloader { @NotNull private final Project myProject; public ContentPreloader(@NotNull Project project) { myProject = project; } @Override public void preloadTabContent(@NotNull Content content) { content.putUserData(Content.TAB_DND_TARGET_KEY, new MyContentDnDTarget(myProject, content)); } } public static class ContentProvider implements ChangesViewContentProvider { @NotNull private final Project myProject; public ContentProvider(@NotNull Project project) { myProject = project; } @Override public void initTabContent(@NotNull Content content) { ChangesViewManager viewManager = (ChangesViewManager)getInstance(myProject); ChangesViewToolWindowPanel panel = viewManager.initToolWindowPanel(); content.setHelpId(ChangesListView.HELP_ID); content.setComponent(panel); content.setPreferredFocusableComponent(panel.myView); } } @NotNull @CalledInAwt private ChangesViewToolWindowPanel initToolWindowPanel() { if (myToolWindowPanel == null) { ChangesViewToolWindowPanel panel = new ChangesViewToolWindowPanel(myProject, this); Disposer.register(myProject, panel); myToolWindowPanel = panel; } return myToolWindowPanel; } @Override public void dispose() { myToolWindowPanel = null; } @NotNull @Override public ChangesViewManager.State getState() { return myState; } @Override public void loadState(@NotNull ChangesViewManager.State state) { myState = state; migrateShowFlattenSetting(); } private void migrateShowFlattenSetting() { if (!myState.myShowFlatten) { myState.groupingKeys = set(DEFAULT_GROUPING_KEYS); myState.myShowFlatten = true; } } public static class State { /** * @deprecated Use {@link #groupingKeys} instead. */ @Deprecated @SuppressWarnings("DeprecatedIsStillUsed") @Attribute("flattened_view") public boolean myShowFlatten = true; @XCollection public Set<String> groupingKeys = new HashSet<>(); @Attribute("show_ignored") public boolean myShowIgnored; } @Override public void scheduleRefresh() { if (myToolWindowPanel == null) return; myToolWindowPanel.scheduleRefresh(); } @Override public void selectFile(VirtualFile vFile) { if (myToolWindowPanel == null) return; myToolWindowPanel.selectFile(vFile); } @Override public void selectChanges(@NotNull List<? extends Change> changes) { if (myToolWindowPanel == null) return; myToolWindowPanel.selectChanges(changes); } @Override public void updateProgressText(String text, boolean isError) { if (myToolWindowPanel == null) return; myToolWindowPanel.updateProgressText(text, isError); } @Override public void setBusy(boolean b) { if (myToolWindowPanel == null) return; myToolWindowPanel.setBusy(b); } @Override public void setGrouping(@NotNull String groupingKey) { if (myToolWindowPanel == null) return; myToolWindowPanel.setGrouping(groupingKey); } @Override public void updateCommitWorkflow() { boolean isNonModal = CommitWorkflowManager.getInstance(myProject).isNonModal(); if (myToolWindowPanel != null) { myToolWindowPanel.updateCommitWorkflow(isNonModal); } else if (isNonModal) { // CommitWorkflowManager needs our ChangesViewCommitWorkflowHandler to work initToolWindowPanel().updateCommitWorkflow(isNonModal); } } @Override @Nullable public ChangesViewCommitWorkflowHandler getCommitWorkflowHandler() { if (myToolWindowPanel == null) return null; return myToolWindowPanel.getCommitWorkflowHandler(); } @Override public void refreshImmediately() { if (myToolWindowPanel == null) return; myToolWindowPanel.refreshImmediately(); } @Override public boolean isAllowExcludeFromCommit() { if (myToolWindowPanel == null) return false; return myToolWindowPanel.isAllowExcludeFromCommit(); } public void closeEditorPreview() { ChangesViewPreview diffPreview = myToolWindowPanel.myDiffPreview; if (diffPreview instanceof EditorTabPreview) { PreviewDiffVirtualFile vcsContentFile = ((EditorTabPreview) diffPreview).getVcsContentFile(); FileEditorManager.getInstance(myProject).closeFile(vcsContentFile); } } public void openEditorPreview() { ChangesViewPreview diffPreview = myToolWindowPanel.myDiffPreview; if (diffPreview instanceof EditorTabPreview) { EditorTabPreview editorTabPreview = (EditorTabPreview) diffPreview; PreviewDiffVirtualFile vcsContentFile = editorTabPreview.getVcsContentFile(); if (editorTabPreview.getCurrentName() != null) { FileEditorManager.getInstance(myProject).openFile(vcsContentFile, true, true); } } } public static class ChangesViewToolWindowPanel extends SimpleToolWindowPanel implements Disposable { @NotNull private static final RegistryValue isToolbarHorizontalSetting = Registry.get("vcs.local.changes.toolbar.horizontal"); @NotNull private static final RegistryValue isCommitSplitHorizontal = Registry.get("vcs.non.modal.commit.split.horizontal.if.no.diff.preview"); @NotNull private final Project myProject; @NotNull private final ChangesViewManager myChangesViewManager; @NotNull private final VcsConfiguration myVcsConfiguration; @NotNull private final ChangesViewPanel myChangesPanel; @NotNull private final ChangesListView myView; @NotNull private final ChangesViewCommitPanelSplitter myCommitPanelSplitter; @NotNull private final ChangesViewPreview myDiffPreview; @NotNull private final Wrapper myProgressLabel = new Wrapper(); @Nullable private ChangesViewCommitPanel myCommitPanel; @Nullable private ChangesViewCommitWorkflowHandler myCommitWorkflowHandler; @NotNull private final Alarm myTreeUpdateAlarm; @NotNull private final Object myTreeUpdateIndicatorLock = new Object(); @NotNull private ProgressIndicator myTreeUpdateIndicator = new EmptyProgressIndicator(); private boolean myModelUpdateInProgress; private boolean myDisposed = false; private ChangesViewToolWindowPanel(@NotNull Project project, @NotNull ChangesViewManager changesViewManager) { super(false, true); myProject = project; myChangesViewManager = changesViewManager; CommitWorkflowManager commitWorkflowManager = CommitWorkflowManager.getInstance(myProject); myVcsConfiguration = VcsConfiguration.getInstance(myProject); myTreeUpdateAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, this); myChangesPanel = new ChangesViewPanel(project); myView = myChangesPanel.getChangesView(); myView.installPopupHandler((DefaultActionGroup)ActionManager.getInstance().getAction("ChangesViewPopupMenu")); myView.getGroupingSupport().setGroupingKeysOrSkip(myChangesViewManager.myState.groupingKeys); myView.addGroupingChangeListener(e -> { myChangesViewManager.myState.groupingKeys = myView.getGroupingSupport().getGroupingKeys(); scheduleRefresh(); }); ChangesDnDSupport.install(myProject, myView); myChangesPanel.getToolbarActionGroup().addAll(createChangesToolbarActions(myView.getTreeExpander())); myChangesPanel.setToolbarHorizontal(commitWorkflowManager.isNonModal() && isToolbarHorizontalSetting.asBoolean()); registerShortcuts(this); isToolbarHorizontalSetting.addListener(new RegistryValueListener.Adapter() { @Override public void afterValueChanged(@NotNull RegistryValue value) { boolean isToolbarHorizontal = value.asBoolean() && commitWorkflowManager.isNonModal(); myChangesPanel.setToolbarHorizontal(isToolbarHorizontal); if (myCommitPanel != null) myCommitPanel.setToolbarHorizontal(isToolbarHorizontal); } }, this); myCommitPanelSplitter = new ChangesViewCommitPanelSplitter(); myCommitPanelSplitter.setFirstComponent(myChangesPanel); BorderLayoutPanel contentPanel = new BorderLayoutPanel() { @Override public Dimension getMinimumSize() { return isMinimumSizeSet() || myChangesPanel.isToolbarHorizontal() ? super.getMinimumSize() : myChangesPanel.getToolbar().getComponent().getPreferredSize(); } }; contentPanel.addToCenter(myCommitPanelSplitter); ChangesViewDiffPreviewProcessor changeProcessor = new ChangesViewDiffPreviewProcessor(myView); Disposer.register(this, changeProcessor); JComponent mainPanel; if (Registry.is("show.diff.preview.as.editor.tab")) { myDiffPreview = new EditorTabPreview(changeProcessor, myProject, contentPanel, myView){ @Override protected String getCurrentName() { return changeProcessor.getCurrentChangeName(); } @Override protected boolean shouldSkip() { return myModelUpdateInProgress; } @Override protected void doRefresh() { changeProcessor.refresh(false); PreviewDiffVirtualFile vcsContentFile = getVcsContentFile(); if (changeProcessor.getCurrentChangeName() == null) { FileEditorManager.getInstance(project).closeFile(vcsContentFile); } } }; mainPanel = contentPanel; myView.setExpandableItemsEnabled(false); } else { PreviewDiffSplitterComponent splitter = new PreviewDiffSplitterComponent(contentPanel, changeProcessor, CHANGES_VIEW_PREVIEW_SPLITTER_PROPORTION, myVcsConfiguration.LOCAL_CHANGES_DETAILS_PREVIEW_SHOWN); myDiffPreview = new PanelPreview(splitter); mainPanel = splitter; myView.addTreeSelectionListener(e -> { boolean fromModelRefresh = myModelUpdateInProgress; invokeLater(() -> myDiffPreview.updatePreview(fromModelRefresh)); }); } setContent(simplePanel(mainPanel).addToBottom(myProgressLabel)); setCommitSplitOrientation(); isCommitSplitHorizontal.addListener(new RegistryValueListener.Adapter() { @Override public void afterValueChanged(@NotNull RegistryValue value) { setCommitSplitOrientation(); } }, this); isToggleCommitUi().addListener(new RegistryValueListener.Adapter() { @Override public void afterValueChanged(@NotNull RegistryValue value) { if (myCommitWorkflowHandler == null) return; if (value.asBoolean()) { myCommitWorkflowHandler.deactivate(false); } else { myCommitWorkflowHandler.activate(); } } }, this); MessageBusConnection busConnection = myProject.getMessageBus().connect(this); busConnection.subscribe(RemoteRevisionsCache.REMOTE_VERSION_CHANGED, () -> scheduleRefresh()); busConnection.subscribe(ProblemListener.TOPIC, new ProblemListener() { @Override public void problemsAppeared(@NotNull VirtualFile file) { refreshChangesViewNodeAsync(file); } @Override public void problemsDisappeared(@NotNull VirtualFile file) { refreshChangesViewNodeAsync(file); } }); ChangeListManager.getInstance(myProject).addChangeListListener(new MyChangeListListener(), this); scheduleRefresh(); myDiffPreview.updatePreview(false); } @Override public void dispose() { myDisposed = true; myTreeUpdateAlarm.cancelAllRequests(); synchronized (myTreeUpdateIndicatorLock) { myTreeUpdateIndicator.cancel(); } } @Nullable public ChangesViewCommitWorkflowHandler getCommitWorkflowHandler() { return myCommitWorkflowHandler; } public void updateCommitWorkflow(boolean isNonModal) { if (isNonModal) { if (myCommitPanel == null) { myChangesPanel.setToolbarHorizontal(isToolbarHorizontalSetting.asBoolean()); myCommitPanel = myChangesViewManager.createCommitPanel(myView, this); myCommitPanel.setToolbarHorizontal(isToolbarHorizontalSetting.asBoolean()); myCommitWorkflowHandler = new ChangesViewCommitWorkflowHandler(new ChangesViewCommitWorkflow(myProject), myCommitPanel); if (isToggleCommitUi().asBoolean()) myCommitWorkflowHandler.deactivate(false); Disposer.register(this, myCommitPanel); myCommitPanelSplitter.setSecondComponent(myCommitPanel); myDiffPreview.setAllowExcludeFromCommit(isAllowExcludeFromCommit()); myCommitWorkflowHandler.addActivityListener( () -> myDiffPreview.setAllowExcludeFromCommit(isAllowExcludeFromCommit()), myCommitWorkflowHandler ); } } else { myChangesPanel.setToolbarHorizontal(false); if (myCommitPanel != null) { myDiffPreview.setAllowExcludeFromCommit(false); myCommitPanelSplitter.setSecondComponent(null); Disposer.dispose(myCommitPanel); myCommitPanel = null; myCommitWorkflowHandler = null; } } } public boolean isAllowExcludeFromCommit() { return myCommitWorkflowHandler != null && myCommitWorkflowHandler.isActive(); } private void setCommitSplitOrientation() { boolean hasPreviewPanel = myVcsConfiguration.LOCAL_CHANGES_DETAILS_PREVIEW_SHOWN && myDiffPreview instanceof PanelPreview; myCommitPanelSplitter.setOrientation(hasPreviewPanel || !isCommitSplitHorizontal.asBoolean()); } @NotNull private Function<ChangeNodeDecorator, ChangeNodeDecorator> getChangeDecoratorProvider() { return baseDecorator -> new PartialCommitChangeNodeDecorator(myProject, baseDecorator, () -> isAllowExcludeFromCommit()); } @NotNull @Override public List<AnAction> getActions(boolean originalProvider) { return asList(myChangesPanel.getToolbarActionGroup().getChildren(null)); } @Nullable @Override public Object getData(@NotNull String dataId) { Object data = super.getData(dataId); if (data != null) return data; // This makes COMMIT_WORKFLOW_HANDLER available anywhere in "Local Changes" - so commit executor actions are enabled. return myCommitPanel != null ? myCommitPanel.getDataFromProviders(dataId) : null; } private static void registerShortcuts(@NotNull JComponent component) { registerWithShortcutSet("ChangesView.Refresh", CommonShortcuts.getRerun(), component); registerWithShortcutSet("ChangesView.NewChangeList", CommonShortcuts.getNew(), component); registerWithShortcutSet("ChangesView.RemoveChangeList", CommonShortcuts.getDelete(), component); registerWithShortcutSet(IdeActions.MOVE_TO_ANOTHER_CHANGE_LIST, CommonShortcuts.getMove(), component); } @NotNull private List<AnAction> createChangesToolbarActions(@NotNull TreeExpander treeExpander) { List<AnAction> actions = new ArrayList<>(); actions.add(CustomActionsSchema.getInstance().getCorrectedAction(ActionPlaces.CHANGES_VIEW_TOOLBAR)); actions.add(Separator.getInstance()); actions.add(ActionManager.getInstance().getAction(GROUP_BY_ACTION_GROUP)); DefaultActionGroup viewOptionsGroup = new DefaultActionGroup("View Options", true); viewOptionsGroup.getTemplatePresentation().setIcon(AllIcons.Actions.Show); viewOptionsGroup.add(new ToggleShowIgnoredAction()); viewOptionsGroup.add(ActionManager.getInstance().getAction("ChangesView.ViewOptions")); actions.add(viewOptionsGroup); actions.add(CommonActionsManager.getInstance().createExpandAllHeaderAction(treeExpander, myView)); actions.add(CommonActionsManager.getInstance().createCollapseAllAction(treeExpander, myView)); actions.add(Separator.getInstance()); actions.add(new ToggleDetailsAction()); return actions; } private void updateProgressComponent(@Nullable Factory<? extends JComponent> progress) { invokeLaterIfNeeded(() -> { if (myDisposed) return; JComponent component = progress != null ? progress.create() : null; myProgressLabel.setContent(component); myProgressLabel.setMinimumSize(JBUI.emptySize()); }); } public void updateProgressText(String text, boolean isError) { updateProgressComponent(createTextStatusFactory(text, isError)); } public void setBusy(final boolean b) { invokeLaterIfNeeded(() -> myView.setPaintBusy(b)); } public void scheduleRefresh() { if (myDisposed) return; myTreeUpdateAlarm.cancelAllRequests(); myTreeUpdateAlarm.addRequest(() -> refreshView(), 100); } public void refreshImmediately() { ApplicationManager.getApplication().assertIsDispatchThread(); myTreeUpdateAlarm.cancelAllRequests(); ProgressManager.getInstance().executeNonCancelableSection(() -> refreshView()); } private void refreshView() { ProgressIndicator indicator = new EmptyProgressIndicator(); synchronized (myTreeUpdateIndicatorLock) { myTreeUpdateIndicator.cancel(); myTreeUpdateIndicator = indicator; } ProgressManager.getInstance().executeProcessUnderProgress(() -> { if (myDisposed || !myProject.isInitialized() || ApplicationManager.getApplication().isUnitTestMode()) return; if (!ProjectLevelVcsManager.getInstance(myProject).hasActiveVcss()) return; ChangeListManagerImpl changeListManager = ChangeListManagerImpl.getInstanceImpl(myProject); List<LocalChangeList> changeLists = changeListManager.getChangeListsCopy(); List<FilePath> unversionedFiles = changeListManager.getUnversionedFilesPaths(); TreeModelBuilder treeModelBuilder = new TreeModelBuilder(myProject, myView.getGrouping()) .setChangeLists(changeLists, Registry.is("vcs.skip.single.default.changelist"), getChangeDecoratorProvider()) .setLocallyDeletedPaths(changeListManager.getDeletedFiles()) .setModifiedWithoutEditing(changeListManager.getModifiedWithoutEditing()) .setSwitchedFiles(changeListManager.getSwitchedFilesMap()) .setSwitchedRoots(changeListManager.getSwitchedRoots()) .setLockedFolders(changeListManager.getLockedFolders()) .setLogicallyLockedFiles(changeListManager.getLogicallyLockedFolders()) .setUnversioned(unversionedFiles); if (myChangesViewManager.myState.myShowIgnored) { treeModelBuilder.setIgnored(changeListManager.getIgnoredFilePaths(), changeListManager.isIgnoredInUpdateMode()); } for (ChangesViewModifier extension : ChangesViewModifier.KEY.getExtensions(myProject)) { extension.modifyTreeModelBuilder(treeModelBuilder); } DefaultTreeModel newModel = treeModelBuilder.build(); invokeLaterIfNeeded(() -> { if (myDisposed) return; indicator.checkCanceled(); myModelUpdateInProgress = true; try { myView.updateModel(newModel); if (myCommitWorkflowHandler != null) myCommitWorkflowHandler.synchronizeInclusion(changeLists, unversionedFiles); } finally { myModelUpdateInProgress = false; } myDiffPreview.updatePreview(true); }); }, indicator); } public void setGrouping(@NotNull String groupingKey) { myView.getGroupingSupport().setGroupingKeysOrSkip(set(groupingKey)); } public void selectFile(@Nullable VirtualFile vFile) { if (vFile == null) return; Change change = ChangeListManager.getInstance(myProject).getChange(vFile); Object objectToFind = change != null ? change : vFile; DefaultMutableTreeNode root = (DefaultMutableTreeNode)myView.getModel().getRoot(); DefaultMutableTreeNode node = TreeUtil.findNodeWithObject(root, objectToFind); if (node != null) { TreeUtil.selectNode(myView, node); } } public void selectChanges(@NotNull List<? extends Change> changes) { List<TreePath> paths = new ArrayList<>(); for (Change change : changes) { ContainerUtil.addIfNotNull(paths, myView.findNodePathInTree(change)); } TreeUtil.selectPaths(myView, paths); } public void refreshChangesViewNodeAsync(@NotNull VirtualFile file) { invokeLater(() -> refreshChangesViewNode(file)); } private void refreshChangesViewNode(@NotNull VirtualFile file) { ChangeListManager changeListManager = ChangeListManager.getInstance(myProject); Object userObject = changeListManager.isUnversioned(file) ? file : changeListManager.getChange(file); if (userObject != null) { DefaultMutableTreeNode root = (DefaultMutableTreeNode)myView.getModel().getRoot(); DefaultMutableTreeNode node = TreeUtil.findNodeWithObject(root, userObject); if (node != null) { myView.getModel().nodeChanged(node); } } } private void invokeLater(Runnable runnable) { ApplicationManager.getApplication().invokeLater(runnable, ModalityState.NON_MODAL, myProject.getDisposed()); } private void invokeLaterIfNeeded(Runnable runnable) { GuiUtils.invokeLaterIfNeeded(runnable, ModalityState.NON_MODAL, myProject.getDisposed()); } private class MyChangeListListener extends ChangeListAdapter { @Override public void changeListsChanged() { scheduleRefresh(); } @Override public void changeListUpdateDone() { setBusy(false); scheduleRefresh(); ChangeListManagerImpl changeListManager = ChangeListManagerImpl.getInstanceImpl(myProject); VcsException updateException = changeListManager.getUpdateException(); if (updateException == null) { updateProgressComponent(changeListManager.getAdditionalUpdateInfo()); } else { updateProgressText(VcsBundle.message("error.updating.changes", updateException.getMessage()), true); } } } private class ToggleShowIgnoredAction extends ToggleAction implements DumbAware { ToggleShowIgnoredAction() { super(VcsBundle.message("changes.action.show.ignored.text"), VcsBundle.message("changes.action.show.ignored.description"), AllIcons.Actions.ShowHiddens); } @Override public boolean isSelected(@NotNull AnActionEvent e) { return myChangesViewManager.myState.myShowIgnored; } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myChangesViewManager.myState.myShowIgnored = state; refreshView(); } } private class ToggleDetailsAction extends ShowDiffPreviewAction { @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myVcsConfiguration.LOCAL_CHANGES_DETAILS_PREVIEW_SHOWN = state; myDiffPreview.setDiffPreviewVisible(state); setCommitSplitOrientation(); } @Override public boolean isSelected(@NotNull AnActionEvent e) { return myVcsConfiguration.LOCAL_CHANGES_DETAILS_PREVIEW_SHOWN; } } private class PanelPreview implements ChangesViewPreview { @NotNull private final PreviewDiffSplitterComponent myPreviewSplitter; private PanelPreview(@NotNull PreviewDiffSplitterComponent previewSplitter) { myPreviewSplitter = previewSplitter; } @Override public void updatePreview(boolean fromModelRefresh) { myPreviewSplitter.updatePreview(fromModelRefresh); } @Override public void setDiffPreviewVisible(boolean isVisible) { myPreviewSplitter.setDetailsOn(isVisible); } @Override public void setAllowExcludeFromCommit(boolean value) { myPreviewSplitter.setAllowExcludeFromCommit(value); } } } protected ChangesViewCommitPanel createCommitPanel(@NotNull ChangesListView myView, @NotNull ChangesViewToolWindowPanel changesViewToolWindowPanel) { return new ChangesViewCommitPanel(myView, changesViewToolWindowPanel); } private static class MyContentDnDTarget extends VcsToolwindowDnDTarget { private MyContentDnDTarget(@NotNull Project project, @NotNull Content content) { super(project, content); } @Override public void drop(DnDEvent event) { super.drop(event); Object attachedObject = event.getAttachedObject(); if (attachedObject instanceof ShelvedChangeListDragBean) { ChangesViewToolWindowPanel panel = ((ChangesViewManager)getInstance(myProject)).initToolWindowPanel(); ShelveChangesManager.unshelveSilentlyWithDnd(myProject, (ShelvedChangeListDragBean)attachedObject, ChangesDnDSupport.getDropRootNode(panel.myView, event), !ChangesDnDSupport.isCopyAction(event)); } } @Override public boolean isDropPossible(@NotNull DnDEvent event) { Object attachedObject = event.getAttachedObject(); if (attachedObject instanceof ShelvedChangeListDragBean) { return !((ShelvedChangeListDragBean)attachedObject).getShelvedChangelists().isEmpty(); } return attachedObject instanceof ChangeListDragBean; } } @NotNull public static Factory<JComponent> createTextStatusFactory(final String text, final boolean isError) { return () -> { JLabel label = new JLabel(text); label.setForeground(isError ? JBColor.RED : UIUtil.getLabelForeground()); return label; }; } }
package com.intellij.coverage.view; import com.intellij.coverage.*; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.GlobalSearchScopes; import com.intellij.util.ui.ColumnInfo; import org.jetbrains.annotations.Nullable; import java.util.*; public class JavaCoverageViewExtension extends CoverageViewExtension { private JavaCoverageAnnotator myAnnotator; public JavaCoverageViewExtension(JavaCoverageAnnotator annotator, Project project, CoverageSuitesBundle suitesBundle, CoverageViewManager.StateBean stateBean) { super(project, suitesBundle, stateBean); myAnnotator = annotator; } @Override public String getSummaryForNode(AbstractTreeNode node) { final String coverageInformationString = myAnnotator .getPackageCoverageInformationString((PsiPackage)node.getValue(), null, myCoverageDataManager, myStateBean.myFlattenPackages); return "Coverage Summary for Package \'" + node.toString() + "\': " + getNotCoveredMessage(coverageInformationString); } @Override public String getSummaryForRootNode(AbstractTreeNode childNode) { final Object value = childNode.getValue(); String coverageInformationString = myAnnotator.getPackageCoverageInformationString((PsiPackage)value, null, myCoverageDataManager); if (coverageInformationString == null) { PackageAnnotator.PackageCoverageInfo info = new PackageAnnotator.PackageCoverageInfo(); final Collection children = childNode.getChildren(); for (Object child : children) { final Object childValue = ((CoverageListNode)child).getValue(); if (childValue instanceof PsiPackage) { final PackageAnnotator.PackageCoverageInfo coverageInfo = myAnnotator.getPackageCoverageInfo((PsiPackage)childValue, myStateBean.myFlattenPackages); if (coverageInfo != null) { info = JavaCoverageAnnotator.merge(info, coverageInfo); } else { return "Loading..."; } } } coverageInformationString = JavaCoverageAnnotator.getCoverageInformationString(info, false); } return "Coverage Summary for \'all classes in scope\': " + getNotCoveredMessage(coverageInformationString); } private static String getNotCoveredMessage(String coverageInformationString) { if (coverageInformationString == null) { coverageInformationString = "not covered"; } return coverageInformationString; } @Override public String getPercentage(int columnIndex, AbstractTreeNode node) { final Object value = node.getValue(); if (value instanceof PsiClass) { //no coverage gathered if (((PsiClass)value).isInterface()) return null; final String qualifiedName = ((PsiClass)value).getQualifiedName(); if (columnIndex == 1) { return myAnnotator.isClassCovered(qualifiedName) ? "100% (1/1)" : "0% (0/1)"; } else if (columnIndex == 2){ return myAnnotator.getClassMethodPercentage(qualifiedName); } return myAnnotator.getClassLinePercentage(qualifiedName); } final boolean flatten = myStateBean.myFlattenPackages; if (columnIndex == 1) { return myAnnotator.getPackageClassPercentage((PsiPackage)value, flatten); } else if (columnIndex == 2) { return myAnnotator.getPackageMethodPercentage((PsiPackage)value, flatten); } return myAnnotator.getPackageLinePercentage((PsiPackage)value, flatten); } @Override public PsiElement getElementToSelect(VirtualFile virtualFile) { final PsiElement psiElement = super.getElementToSelect(virtualFile); if (psiElement instanceof PsiClassOwner) { final PsiClass[] classes = ((PsiClassOwner)psiElement).getClasses(); if (classes.length > 0) return classes[0]; } return psiElement; } @Nullable @Override public PsiElement getParentElement(PsiElement element) { if (element instanceof PsiClass) { final PsiDirectory containingDirectory = element.getContainingFile().getContainingDirectory(); return containingDirectory != null ? JavaDirectoryService.getInstance().getPackage(containingDirectory) : null; } return ((PsiPackage)element).getParentPackage(); } @Override public AbstractTreeNode createRootNode() { return new CoverageListRootNode(JavaPsiFacade.getInstance(myProject).findPackage(""), mySuitesBundle, myStateBean); } @Override public List<AbstractTreeNode> createTopLevelNodes() { final List<AbstractTreeNode> topLevelNodes = new ArrayList<AbstractTreeNode>(); for (CoverageSuite suite : mySuitesBundle.getSuites()) { final List<PsiPackage> packages = ((JavaCoverageSuite)suite).getCurrentSuitePackages(myProject); for (PsiPackage aPackage : packages) { final GlobalSearchScope searchScope = getSearchScope(mySuitesBundle, myProject); if (aPackage.getDirectories(searchScope).length == 0) continue; if (aPackage.getClasses(searchScope).length == 0) continue; final CoverageListNode node = new CoverageListNode(aPackage, mySuitesBundle, myStateBean); topLevelNodes.add(node); collectSubPackages(topLevelNodes, aPackage, mySuitesBundle, myStateBean); } final List<PsiClass> classes = ((JavaCoverageSuite)suite).getCurrentSuiteClasses(myProject); for (PsiClass aClass : classes) { topLevelNodes.add(new CoverageListNode(aClass, mySuitesBundle, myStateBean)); } } return topLevelNodes; } private static GlobalSearchScope getSearchScope(CoverageSuitesBundle bundle, Project project) { return bundle.isTrackTestFolders() ? GlobalSearchScope.projectScope(project) : GlobalSearchScopes.projectProductionScope(project); } private static void collectSubPackages(List<AbstractTreeNode> children, final PsiPackage rootPackage, final CoverageSuitesBundle data, final CoverageViewManager.StateBean stateBean) { final GlobalSearchScope searchScope = getSearchScope(data, rootPackage.getProject()); final PsiPackage[] subPackages = ApplicationManager.getApplication().runReadAction(new Computable<PsiPackage[]>() { public PsiPackage[] compute() { return rootPackage.getSubPackages(searchScope); } }); for (final PsiPackage aPackage : subPackages) { final PsiDirectory[] directories = ApplicationManager.getApplication().runReadAction(new Computable<PsiDirectory[]>() { public PsiDirectory[] compute() { return aPackage.getDirectories(searchScope); } }); if (directories.length == 0) continue; if (ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() { public Boolean compute() { return isInCoverageScope(aPackage, data); } })) { final CoverageListNode node = new CoverageListNode(aPackage, data, stateBean); children.add(node); } else if (!stateBean.myFlattenPackages) { collectSubPackages(children, aPackage, data, stateBean); } if (stateBean.myFlattenPackages) { collectSubPackages(children, aPackage, data, stateBean); } } } @Override public List<AbstractTreeNode> getChildrenNodes(final AbstractTreeNode node) { List<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>(); if (node instanceof CoverageListNode) { final Object val = node.getValue(); if (val instanceof PsiClass) return Collections.emptyList(); //append package classes if (val instanceof PsiPackage) { boolean found = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() { public Boolean compute() { return isInCoverageScope((PsiPackage)val, mySuitesBundle); } }); if (!myStateBean.myFlattenPackages) { collectSubPackages(children, (PsiPackage)val, mySuitesBundle, myStateBean); } final PsiClass[] classes = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass[]>() { public PsiClass[] compute() { return ((PsiPackage)val).getClasses(getSearchScope(mySuitesBundle, node.getProject())); } }); if (found) { for (PsiClass aClass : classes) { children.add(new CoverageListNode(aClass, mySuitesBundle, myStateBean)); } } else { for (final PsiClass aClass : classes) { final String classFQName = ApplicationManager.getApplication().runReadAction(new Computable<String>() { public String compute() { return aClass.getQualifiedName(); } }); for (CoverageSuite suite : mySuitesBundle.getSuites()) { if (((JavaCoverageSuite)suite).isClassFiltered(classFQName)) { children.add(new CoverageListNode(aClass, mySuitesBundle, myStateBean)); } } } } } for (AbstractTreeNode childNode : children) { childNode.setParent(node); } } return children; } @Override public ColumnInfo[] createColumnInfos() { return new ColumnInfo[]{ new ElementColumnInfo(), new PercentageCoverageColumnInfo(1, "Class, %", mySuitesBundle, myStateBean), new PercentageCoverageColumnInfo(2, "Method, %", mySuitesBundle, myStateBean), new PercentageCoverageColumnInfo(3, "Line, %", mySuitesBundle, myStateBean) }; } public static boolean isInCoverageScope(PsiElement element, CoverageSuitesBundle suitesBundle) { final PsiPackage psiPackage = (PsiPackage)element; final String qualifiedName = psiPackage.getQualifiedName(); Set<String> filteredClasses = new HashSet<String>(); for (CoverageSuite suite : suitesBundle.getSuites()) { if (((JavaCoverageSuite)suite).isPackageFiltered(qualifiedName)) return true; Collections.addAll(filteredClasses, ((JavaCoverageSuite)suite).getFilteredClassNames()); } if (!filteredClasses.isEmpty()) { final PsiClass[] classes = psiPackage.getClasses(getSearchScope(suitesBundle, psiPackage.getProject())); for (PsiClass psiClass : classes) { final String classFQName = psiClass.getQualifiedName(); for (CoverageSuite suite : suitesBundle.getSuites()) { if (((JavaCoverageSuite)suite).isClassFiltered(classFQName)) return true; } } } return false; } @Override public boolean canSelectInCoverageView(VirtualFile file) { final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file); if (psiFile instanceof PsiClassOwner) { final String packageName = ((PsiClassOwner)psiFile).getPackageName(); return isInCoverageScope(JavaPsiFacade.getInstance(myProject).findPackage(packageName), mySuitesBundle); } return false; } @Override public boolean supportFlattenPackages() { return true; } }
package net.tomp2p.dht; import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.SignatureException; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import javax.crypto.Cipher; import net.tomp2p.connection.ChannelClientConfiguration; import net.tomp2p.connection.ChannelServerConfiguration; import net.tomp2p.connection.DSASignatureFactory; import net.tomp2p.connection.RSASignatureFactory; import net.tomp2p.connection.SignatureFactory; import net.tomp2p.dht.StorageLayer.ProtectionEnable; import net.tomp2p.dht.StorageLayer.ProtectionMode; import net.tomp2p.message.RSASignatureCodec; import net.tomp2p.message.SignatureCodec; import net.tomp2p.p2p.PeerBuilder; import net.tomp2p.p2p.RequestP2PConfiguration; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number640; import net.tomp2p.storage.Data; import net.tomp2p.utils.Utils; import org.junit.Assert; import org.junit.Test; public class TestSecurity { final private static Random rnd = new Random(42L); private static final DSASignatureFactory factory = new DSASignatureFactory(); private static KeyPairGenerator keyGen; static { try { keyGen = KeyPairGenerator.getInstance("DSA"); } catch (NoSuchAlgorithmException e) { Assert.fail("Cannot initialize DSA key pair generator"); } } @Test public void testPublicKeyReceived() throws Exception { final Random rnd = new Random(43L); PeerDHT master = null; PeerDHT slave1 = null; KeyPair pair1 = keyGen.generateKeyPair(); KeyPair pair2 = keyGen.generateKeyPair(); // make master try { final AtomicBoolean gotPK = new AtomicBoolean(false); // set storage to test PK StorageLayer sl = new StorageLayer(new StorageMemory()) { @Override public Enum<?> put(Number640 key, Data newData, PublicKey publicKey, boolean putIfAbsent, boolean domainProtection, boolean selfSend) { System.err.println("P is " + publicKey); gotPK.set(publicKey != null); System.err.println("PK is " + gotPK); return super.put(key, newData, publicKey, putIfAbsent, domainProtection, selfSend); } }; master = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair1).ports(4001).start()).start(); // make slave slave1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair2).masterPeer(master.peer()).start()) .storageLayer(sl).start(); // perfect routing boolean peerInMap1 = master.peerBean().peerMap().peerFound(slave1.peerAddress(), null, null, null); boolean peerInMap2 = slave1.peerBean().peerMap().peerFound(master.peerAddress(), null, null, null); Assert.assertEquals(true, peerInMap1); Assert.assertEquals(true, peerInMap2); Number160 locationKey = new Number160(50); RequestP2PConfiguration rc = new RequestP2PConfiguration(1, 1, 0); master.put(locationKey).data(new Data(new byte[100000])).requestP2PConfiguration(rc).sign().start() .awaitUninterruptibly(); // master.put(locationKey, new Data("test"), // cs1).awaitUninterruptibly(); Assert.assertEquals(true, gotPK.get()); // without PK, this test should fail. master.put(locationKey).data(new Data("test1")).requestP2PConfiguration(rc).start().awaitUninterruptibly(); Assert.assertEquals(false, gotPK.get()); } finally { master.shutdown(); slave1.shutdown(); } } @Test public void testPublicKeyReceivedDomain() throws Exception { final Random rnd = new Random(43L); PeerDHT master = null; try { KeyPair pair1 = keyGen.generateKeyPair(); final AtomicBoolean gotPK = new AtomicBoolean(false); // set storage to test PK StorageLayer sl = new StorageLayer(new StorageMemory()) { @Override public Enum<?> put(Number640 key, Data newData, PublicKey publicKey, boolean putIfAbsent, boolean domainProtection, boolean selfSend) { gotPK.set(publicKey != null); System.err.println("PK is " + gotPK); return super.put(key, newData, publicKey, putIfAbsent, domainProtection, selfSend); } }; // make master master = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair1).ports(4001).start()) .storageLayer(sl).start(); Number160 locationKey = new Number160(50); RequestP2PConfiguration rc = new RequestP2PConfiguration(1, 1, 0); master.put(locationKey).data(Number160.ONE, new Data(new byte[2000])).requestP2PConfiguration(rc) .domainKey(Number160.ONE).sign().start().awaitUninterruptibly(); Assert.assertEquals(true, gotPK.get()); // without PK master.put(locationKey).data(Number160.ONE, new Data("test1")).requestP2PConfiguration(rc) .domainKey(Number160.ONE).start().awaitUninterruptibly(); Assert.assertEquals(false, gotPK.get()); } catch (Throwable t) { Assert.fail(t.getMessage()); t.printStackTrace(); } finally { master.shutdown().awaitUninterruptibly(); } } @Test public void testProtection() throws Exception { final Random rnd = new Random(43L); PeerDHT master = null; PeerDHT slave1 = null; PeerDHT slave2 = null; KeyPair pair1 = keyGen.generateKeyPair(); KeyPair pair2 = keyGen.generateKeyPair(); KeyPair pair3 = keyGen.generateKeyPair(); System.err.println("PPK1 " + pair1.getPublic()); System.err.println("PPK2 " + pair2.getPublic()); System.err.println("PPK3 " + pair3.getPublic()); try { master = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair1).ports(4001).start()).start(); master.storageLayer().protection(ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY, ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY); slave1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair2).masterPeer(master.peer()).start()) .start(); slave1.storageLayer().protection(ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY, ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY); slave2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair3).masterPeer(master.peer()).start()) .start(); slave2.storageLayer().protection(ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY, ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY); // perfect routing master.peerBean().peerMap().peerFound(slave1.peerAddress(), null, null, null); master.peerBean().peerMap().peerFound(slave2.peerAddress(), null, null, null); slave1.peerBean().peerMap().peerFound(master.peerAddress(), null, null, null); slave1.peerBean().peerMap().peerFound(slave2.peerAddress(), null, null, null); slave2.peerBean().peerMap().peerFound(master.peerAddress(), null, null, null); slave2.peerBean().peerMap().peerFound(slave1.peerAddress(), null, null, null); Number160 locationKey = new Number160(50); FuturePut fdht1 = master.put(locationKey).data(new Number160(10), new Data("test1")) .domainKey(Utils.makeSHAHash(pair3.getPublic().getEncoded())).protectDomain().start(); fdht1.awaitUninterruptibly(); Assert.assertEquals(true, fdht1.isSuccess()); // try to insert in same domain from different peer FuturePut fdht2 = slave1.put(locationKey).data(new Number160(11), new Data("tes2")) .domainKey(Utils.makeSHAHash(pair3.getPublic().getEncoded())).protectDomain().start(); fdht2.awaitUninterruptibly(); Assert.assertEquals(false, fdht2.isSuccess()); // insert from same peer but with public key protection FuturePut fdht3 = slave2.put(locationKey).data(new Number160(12), new Data("tes2")) .domainKey(Utils.makeSHAHash(pair3.getPublic().getEncoded())).protectDomain().start(); fdht3.awaitUninterruptibly(); Assert.assertEquals(true, fdht3.isSuccess()); // get at least 3 results, because we want to test the domain // removel feature RequestP2PConfiguration rc = new RequestP2PConfiguration(3, 3, 3); FutureGet fdht4 = slave1.get(locationKey).all().requestP2PConfiguration(rc) .domainKey(Utils.makeSHAHash(pair3.getPublic().getEncoded())).start(); fdht4.awaitUninterruptibly(); Assert.assertEquals(true, fdht4.isSuccess()); Assert.assertEquals(2, fdht4.dataMap().size()); } finally { master.shutdown().awaitUninterruptibly(); slave1.shutdown().awaitUninterruptibly(); slave2.shutdown().awaitUninterruptibly(); } } @Test public void testProtectionWithRemove() throws Exception { final Random rnd = new Random(42L); PeerDHT master = null; PeerDHT slave1 = null; PeerDHT slave2 = null; KeyPair pair1 = keyGen.generateKeyPair(); KeyPair pair2 = keyGen.generateKeyPair(); KeyPair pair3 = keyGen.generateKeyPair(); System.err.println("PPK1 " + pair1.getPublic()); System.err.println("PPK2 " + pair2.getPublic()); System.err.println("PPK3 " + pair3.getPublic()); try { master = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair1).ports(4001).start()).start(); master.storageLayer().protection(ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY, ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY); slave1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair2).masterPeer(master.peer()).start()) .start(); slave1.storageLayer().protection(ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY, ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY); slave2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair3).masterPeer(master.peer()).start()) .start(); slave2.storageLayer().protection(ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY, ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY); // perfect routing master.peerBean().peerMap().peerFound(slave1.peerAddress(), null, null, null); master.peerBean().peerMap().peerFound(slave2.peerAddress(), null, null, null); slave1.peerBean().peerMap().peerFound(master.peerAddress(), null, null, null); slave1.peerBean().peerMap().peerFound(slave2.peerAddress(), null, null, null); slave2.peerBean().peerMap().peerFound(master.peerAddress(), null, null, null); slave2.peerBean().peerMap().peerFound(slave1.peerAddress(), null, null, null); Number160 locationKey = new Number160(50); FuturePut fdht1 = master.put(locationKey).data(new Data("test1")) .domainKey(Utils.makeSHAHash(pair1.getPublic().getEncoded())).protectDomain().start(); fdht1.awaitUninterruptibly(); // remove from different peer, should fail FutureRemove futureRemove = slave1.remove(locationKey) .domainKey(Utils.makeSHAHash(pair1.getPublic().getEncoded())).sign().start(); futureRemove.awaitUninterruptibly(); Assert.assertFalse(futureRemove.isRemoved()); // this should work FutureRemove fdht3 = master.remove(locationKey).domainKey(Utils.makeSHAHash(pair1.getPublic().getEncoded())) .sign().start(); fdht3.awaitUninterruptibly(); Assert.assertTrue(fdht3.isSuccess()); } finally { master.shutdown().awaitUninterruptibly(); slave1.shutdown().awaitUninterruptibly(); slave2.shutdown().awaitUninterruptibly(); } } @Test public void testProtectionDomain() throws Exception { final Random rnd = new Random(43L); PeerDHT master = null; PeerDHT slave1 = null; KeyPair pair1 = keyGen.generateKeyPair(); KeyPair pair2 = keyGen.generateKeyPair(); // make master try { StorageLayer slm = new StorageLayer(new StorageMemory()) { @Override public Enum<?> put(Number640 key, Data newData, PublicKey publicKey, boolean putIfAbsent, boolean domainProtection, boolean selfSend) { // System.out.println("store1"); return super.put(key, newData, publicKey, putIfAbsent, domainProtection, selfSend); } }; StorageLayer sls = new StorageLayer(new StorageMemory()) { @Override public Enum<?> put(Number640 key, Data newData, PublicKey publicKey, boolean putIfAbsent, boolean domainProtection, boolean selfSend) { // System.out.println("store2"); return super.put(key, newData, publicKey, putIfAbsent, domainProtection, selfSend); } }; master = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair1).ports(4001).start()) .storageLayer(slm).start(); // make slave slave1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair2).masterPeer(master.peer()).start()) .storageLayer(sls).start(); // perfect routing boolean peerInMap1 = master.peerBean().peerMap().peerFound(slave1.peerAddress(), null, null, null); boolean peerInMap2 = slave1.peerBean().peerMap().peerFound(master.peerAddress(), null, null, null); Assert.assertEquals(true, peerInMap1); Assert.assertEquals(true, peerInMap2); // since we have to peers, we store on both, otherwise this test may // sometimes work, sometimes not. RequestP2PConfiguration rc = new RequestP2PConfiguration(1, 1, 0); Number160 locationKey = Number160.createHash("loctaion"); FuturePut futureDHT = master.put(locationKey).data(Number160.createHash("content1"), new Data("test1")) .domainKey(Number160.createHash("domain1")).protectDomain().requestP2PConfiguration(rc).start(); futureDHT.awaitUninterruptibly(); Assert.assertEquals(true, futureDHT.isSuccess()); // now the slave stores with different in the same domain. This // should not work futureDHT = slave1.put(locationKey).data(Number160.createHash("content2"), new Data("test2")) .domainKey(Number160.createHash("domain1")).protectDomain().requestP2PConfiguration(rc).start(); futureDHT.awaitUninterruptibly(); System.err.println(futureDHT.failedReason()); Assert.assertEquals(false, futureDHT.isSuccess()); } finally { master.shutdown().awaitUninterruptibly(); slave1.shutdown().awaitUninterruptibly(); } } @Test public void testSecurePutGet1() throws Exception { PeerDHT master = null; PeerDHT slave1 = null; PeerDHT slave2 = null; KeyPair pair1 = keyGen.generateKeyPair(); KeyPair pair2 = keyGen.generateKeyPair(); KeyPair pair3 = keyGen.generateKeyPair(); System.err.println("PPK1 " + pair1.getPublic()); System.err.println("PPK2 " + pair2.getPublic()); System.err.println("PPK3 " + pair3.getPublic()); try { // make slave master = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair1).ports(4001).start()).start(); master.storageLayer().protection(ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY, ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY); slave1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair2).masterPeer(master.peer()).start()) .start(); slave1.storageLayer().protection(ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY, ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY); slave2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).keyPair(pair3).masterPeer(master.peer()).start()) .start(); slave2.storageLayer().protection(ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY, ProtectionEnable.ALL, ProtectionMode.MASTER_PUBLIC_KEY); // perfect routing master.peerBean().peerMap().peerFound(slave1.peerAddress(), null, null, null); master.peerBean().peerMap().peerFound(slave2.peerAddress(), null, null, null); slave1.peerBean().peerMap().peerFound(master.peerAddress(), null, null, null); slave1.peerBean().peerMap().peerFound(slave2.peerAddress(), null, null, null); slave2.peerBean().peerMap().peerFound(master.peerAddress(), null, null, null); slave2.peerBean().peerMap().peerFound(slave1.peerAddress(), null, null, null); Number160 locationKey = new Number160(50); Data data1 = new Data("test1"); data1.protectEntry(pair1); FuturePut fdht1 = master.put(locationKey).data(data1).sign().start(); fdht1.awaitUninterruptibly(); fdht1.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fdht1.isSuccess()); // store again Data data2 = new Data("test1"); data2.protectEntry(pair2); FuturePut fdht2 = slave1.put(locationKey).data(data2).sign().start(); fdht2.awaitUninterruptibly(); fdht2.futureRequests().awaitUninterruptibly(); Assert.assertEquals(0, fdht2.result().size()); Assert.assertEquals(false, fdht2.isSuccess()); // Utils.sleep(1000000); // try to remove it, will fail since we do not sign FutureRemove fdht3 = slave2.remove(locationKey).start(); fdht3.awaitUninterruptibly(); // false, since we have domain protection yet Assert.assertEquals(false, fdht3.isRemoved()); // try to put another thing Data data3 = new Data("test2"); data3.protectEntry(pair1); FuturePut fdht4 = master.put(locationKey).sign().data(new Number160(33), data3).start(); fdht4.awaitUninterruptibly(); fdht4.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fdht4.isSuccess()); // get it FutureGet fdht7 = slave2.get(locationKey).all().start(); fdht7.awaitUninterruptibly(); Assert.assertEquals(2, fdht7.dataMap().size()); Assert.assertEquals(true, fdht7.isSuccess()); // if(true) // System.exit(0); // try to remove for real, all FutureRemove fdht5 = master.remove(locationKey).sign().all().sign().start(); fdht5.awaitUninterruptibly(); System.err.println(fdht5.failedReason()); Assert.assertEquals(true, fdht5.isSuccess()); // get all, they should be removed now FutureGet fdht6 = slave2.get(locationKey).all().start(); fdht6.awaitUninterruptibly(); Assert.assertEquals(0, fdht6.dataMap().size()); Assert.assertEquals(true, fdht6.isEmpty()); // put there the data again... FuturePut fdht8 = slave1.put(locationKey) .data(Utils.makeSHAHash(pair1.getPublic().getEncoded()), new Data("test1")).sign().start(); fdht8.awaitUninterruptibly(); fdht8.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fdht8.isSuccess()); // overwrite Data data4 = new Data("test1"); data4.protectEntry(pair1); FuturePut fdht9 = master.put(locationKey).data(Utils.makeSHAHash(pair1.getPublic().getEncoded()), data4).sign() .start(); fdht9.awaitUninterruptibly(); fdht9.futureRequests().awaitUninterruptibly(); System.err.println("reason " + fdht9.failedReason()); Assert.assertEquals(true, fdht9.isSuccess()); } finally { // Utils.sleep(1000000); master.shutdown().awaitUninterruptibly(); slave1.shutdown().awaitUninterruptibly(); slave2.shutdown().awaitUninterruptibly(); } } @Test public void testContentProtectoin() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InterruptedException, InvalidKeyException, SignatureException { KeyPair keyPairPeer1 = keyGen.generateKeyPair(); KeyPair keyPairPeer2 = keyGen.generateKeyPair(); KeyPair keyPairData = keyGen.generateKeyPair(); PeerDHT p1 = null, p2 = null; try { p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1).start()) .start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); String locationKey = "location"; Number160 lKey = Number160.createHash(locationKey); String contentKey = "content"; Number160 cKey = Number160.createHash(contentKey); String testData1 = "data1"; Data data = new Data(testData1).protectEntry(keyPairData); // put trough peer 1 with key pair FuturePut futurePut1 = p1.put(lKey).data(cKey, data).keyPair(keyPairData).start(); futurePut1.awaitUninterruptibly(); Assert.assertTrue(futurePut1.isSuccess()); FutureGet futureGet1a = p1.get(lKey).contentKey(cKey).start(); futureGet1a.awaitUninterruptibly(); Assert.assertTrue(futureGet1a.isSuccess()); Assert.assertEquals(testData1, (String) futureGet1a.data().object()); FutureGet futureGet1b = p2.get(lKey).contentKey(cKey).start(); futureGet1b.awaitUninterruptibly(); Assert.assertTrue(futureGet1b.isSuccess()); Assert.assertEquals(testData1, (String) futureGet1b.data().object()); // put trough peer 2 without key pair String testData2 = "data2"; Data data2 = new Data(testData2); FuturePut futurePut2 = p2.put(lKey).data(cKey, data2).start(); futurePut2.awaitUninterruptibly(); // PutStatus.FAILED_SECURITY Assert.assertFalse(futurePut2.isSuccess()); FutureGet futureGet2 = p2.get(lKey).contentKey(cKey).start(); futureGet2.awaitUninterruptibly(); Assert.assertTrue(futureGet2.isSuccess()); // should have been not modified Assert.assertEquals(testData1, (String) futureGet2.data().object()); // put trough peer 1 without key pair String testData3 = "data3"; Data data3 = new Data(testData3); FuturePut futurePut3 = p2.put(lKey).data(cKey, data3).start(); futurePut3.awaitUninterruptibly(); // FAILED_SECURITY? Assert.assertFalse(futurePut3.isSuccess()); FutureGet futureGet3 = p2.get(lKey).contentKey(cKey).start(); futureGet3.awaitUninterruptibly(); Assert.assertTrue(futureGet3.isSuccess()); // without giving a key pair? Assert.assertEquals(testData1, (String) futureGet3.data().object()); Assert.assertEquals(keyPairData.getPublic(), futureGet3.data().publicKey()); // now we store a signed data object and we will get back the public // key as well data = new Data("Juhuu").protectEntryNow(keyPairData, factory); FuturePut futurePut4 = p1.put(lKey).data(cKey, data).keyPair(keyPairData).start(); futurePut4.awaitUninterruptibly(); Assert.assertTrue(futurePut4.isSuccess()); FutureGet futureGet4 = p2.get(lKey).contentKey(cKey).start(); futureGet4.awaitUninterruptibly(); Assert.assertTrue(futureGet4.isSuccess()); // without giving a key pair? Assert.assertEquals("Juhuu", (String) futureGet4.data().object()); Assert.assertEquals(keyPairData.getPublic(), futureGet4.data().publicKey()); } finally { p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } } @Test public void testContentProtectoinGeneric() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InterruptedException, InvalidKeyException, SignatureException { KeyPair keyPair = keyGen.generateKeyPair(); PeerDHT p1 = null; try { p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4838).keyPair(keyPair).start()).start(); String locationKey = "location"; Number160 lKey = Number160.createHash(locationKey); String contentKey = "content"; Number160 cKey = Number160.createHash(contentKey); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { sb.append(i); } Data data = new Data(sb.toString()).protectEntryNow(keyPair, factory); FuturePut futurePut4 = p1.put(lKey).data(cKey, data).keyPair(keyPair).start(); futurePut4.awaitUninterruptibly(); System.err.println(futurePut4.failedReason()); Assert.assertTrue(futurePut4.isSuccess()); FutureGet futureGet4 = p1.get(lKey).contentKey(cKey).start(); futureGet4.awaitUninterruptibly(); Assert.assertTrue(futureGet4.isSuccess()); // without giving a key pair? Assert.assertEquals(sb.toString(), (String) futureGet4.data().object()); Assert.assertEquals(keyPair.getPublic(), futureGet4.data().publicKey()); } finally { p1.shutdown().awaitUninterruptibly(); } } @Test public void testVersionContentProtectoinGeneric() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InterruptedException, InvalidKeyException, SignatureException { KeyPair keyPair1 = keyGen.generateKeyPair(); KeyPair keyPair2 = keyGen.generateKeyPair(); PeerDHT p1 = null, p2 = null; try { p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4838).keyPair(keyPair1).start()).start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).ports(4839).keyPair(keyPair2).start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); String locationKey = "location"; Number160 lKey = Number160.createHash(locationKey); String contentKey = "content"; Number160 cKey = Number160.createHash(contentKey); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { sb.append(i); } Data data1 = new Data(sb.toString()).protectEntryNow(keyPair1, factory); FuturePut futurePut4 = p1.put(lKey).data(cKey, data1).keyPair(keyPair1).versionKey(Number160.ZERO).start(); futurePut4.awaitUninterruptibly(); Assert.assertTrue(futurePut4.isSuccess()); Data data2 = new Data(sb.toString()).protectEntryNow(keyPair2, factory); FuturePut futurePut5 = p2.put(lKey).data(cKey, data2).keyPair(keyPair2).versionKey(Number160.ONE).start(); futurePut5.awaitUninterruptibly(); Assert.assertTrue(!futurePut5.isSuccess()); Data data3 = new Data(sb.toString()).protectEntryNow(keyPair2, factory); FuturePut futurePut6 = p1.put(lKey).data(cKey, data3).keyPair(keyPair1).versionKey(Number160.MAX_VALUE).start(); futurePut6.awaitUninterruptibly(); Assert.assertTrue(futurePut6.isSuccess()); FuturePut futurePut7 = p2.put(lKey).data(cKey, data2).keyPair(keyPair2).versionKey(Number160.ONE).start(); futurePut7.awaitUninterruptibly(); Assert.assertTrue(futurePut7.isSuccess()); } finally { p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } } @Test public void testChangeDomainProtectionKey() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InterruptedException, InvalidKeyException, SignatureException { KeyPair keyPair1 = keyGen.generateKeyPair(); KeyPair keyPair2 = keyGen.generateKeyPair(); PeerDHT p1 = null, p2 = null; try { p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4838).keyPair(keyPair1).start()).start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).ports(4839).keyPair(keyPair2).start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); Data data = new Data("test"); FuturePut fp1 = p1.put(Number160.createHash("key1")).protectDomain().data(data).start().awaitUninterruptibly(); Assert.assertTrue(fp1.isSuccess()); FuturePut fp2 = p2.put(Number160.createHash("key1")).protectDomain().data(data).start().awaitUninterruptibly(); Assert.assertTrue(!fp2.isSuccess()); FuturePut fp3 = p1.put(Number160.createHash("key1")).changePublicKey(keyPair2.getPublic()).start() .awaitUninterruptibly(); Assert.assertTrue(fp3.isSuccess()); FuturePut fp4 = p2.put(Number160.createHash("key1")).protectDomain().data(data).start().awaitUninterruptibly(); Assert.assertTrue(fp4.isSuccess()); } finally { p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } } @Test public void testChangeEntryProtectionKey() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InterruptedException, InvalidKeyException, SignatureException { KeyPair keyPair1 = keyGen.generateKeyPair(); KeyPair keyPair2 = keyGen.generateKeyPair(); PeerDHT p1 = null, p2 = null; try { p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4838).keyPair(keyPair1).start()).start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).ports(4839).keyPair(keyPair2).start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); Data data = new Data("test").protectEntry(keyPair1); Data data2 = new Data().protectEntry(keyPair2); FuturePut fp1 = p1.put(Number160.createHash("key1")).sign().data(data).start().awaitUninterruptibly(); Assert.assertTrue(fp1.isSuccess()); FuturePut fp2 = p2.put(Number160.createHash("key1")).data(data2).start().awaitUninterruptibly(); Assert.assertTrue(!fp2.isSuccess()); data2.publicKey(keyPair2.getPublic()); FuturePut fp3 = p1.put(Number160.createHash("key1")).sign().putMeta().data(data2).start().awaitUninterruptibly(); Assert.assertTrue(fp3.isSuccess()); FuturePut fp4 = p2.put(Number160.createHash("key1")).sign().data(data).start().awaitUninterruptibly(); Assert.assertTrue(fp4.isSuccess()); } finally { p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } } @Test public void testChangeEntryProtectionKeySignature() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InterruptedException, InvalidKeyException, SignatureException { KeyPair keyPair1 = keyGen.generateKeyPair(); KeyPair keyPair2 = keyGen.generateKeyPair(); PeerDHT p1 = null, p2 = null; try { p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4838).keyPair(keyPair1).start()).start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).ports(4839).keyPair(keyPair2).start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); Data data = new Data("test1").protectEntryNow(keyPair1, factory); Data data2 = new Data("test1").protectEntryNow(keyPair2, factory); FuturePut fp1 = p1.put(Number160.createHash("key1")).sign().data(data).start().awaitUninterruptibly(); Assert.assertTrue(fp1.isSuccess()); FuturePut fp2 = p2.put(Number160.createHash("key1")).data(data2).start().awaitUninterruptibly(); Assert.assertTrue(!fp2.isSuccess()); data2 = data2.duplicateMeta(); FuturePut fp3 = p1.put(Number160.createHash("key1")).sign().putMeta().data(data2).start().awaitUninterruptibly(); Assert.assertTrue(fp3.isSuccess()); Data retData = p2.get(Number160.createHash("key1")).start().awaitUninterruptibly().data(); Assert.assertTrue(retData.verify(keyPair2.getPublic(), factory)); } finally { p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } } @Test public void testTTLUpdate() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InterruptedException, InvalidKeyException, SignatureException { PeerDHT p1 = null; PeerDHT p2 = null; try { StorageMemory sm1 = new StorageMemory(1); StorageMemory sm2 = new StorageMemory(1); p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4838).start()).storage(sm1).start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).ports(4839).start()).storage(sm2).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); Data data = new Data("test1"); data.ttlSeconds(1); FuturePut fp1 = p1.put(Number160.createHash("key1")).data(data).start().awaitUninterruptibly(); Assert.assertTrue(fp1.isSuccess()); Thread.sleep(2000); Data retData = p2.get(Number160.createHash("key1")).start().awaitUninterruptibly().data(); Assert.assertNull(retData); FuturePut fp2 = p1.put(Number160.createHash("key1")).data(data).start().awaitUninterruptibly(); Assert.assertTrue(fp2.isSuccess()); Data update = data.duplicateMeta(); update.ttlSeconds(100); FuturePut fp3 = p1.put(Number160.createHash("key1")).putMeta().data(update).start().awaitUninterruptibly(); System.err.println(fp3.failedReason()); Assert.assertTrue(fp3.isSuccess()); Thread.sleep(1000); retData = p2.get(Number160.createHash("key1")).start().awaitUninterruptibly().data(); Assert.assertEquals("test1", retData.object()); } finally { if (p1 != null) { p1.shutdown().awaitUninterruptibly(); } if (p2 != null) { p2.shutdown().awaitUninterruptibly(); } } } @Test public void testRemoveFromTo2() throws NoSuchAlgorithmException, IOException, InvalidKeyException, SignatureException, ClassNotFoundException { KeyPair keyPairPeer1 = keyGen.generateKeyPair(); KeyPair keyPairPeer2 = keyGen.generateKeyPair(); KeyPair keyPairData = keyGen.generateKeyPair(); PeerDHT p1 = null, p2 = null; try { p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1).start()) .start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); String locationKey = "location"; Number160 lKey = Number160.createHash(locationKey); String domainKey = "domain"; Number160 dKey = Number160.createHash(domainKey); String contentKey = "content"; Number160 cKey = Number160.createHash(contentKey); String testData1 = "data1"; Data data = new Data(testData1).protectEntryNow(keyPairData, factory); // put trough peer 1 with key pair FuturePut futurePut1 = p1.put(lKey).domainKey(dKey).data(cKey, data).keyPair(keyPairData).start(); futurePut1.awaitUninterruptibly(); Assert.assertTrue(futurePut1.isSuccess()); FutureGet futureGet1a = p1.get(lKey).domainKey(dKey).contentKey(cKey).start(); futureGet1a.awaitUninterruptibly(); Assert.assertTrue(futureGet1a.isSuccess()); Assert.assertEquals(testData1, (String) futureGet1a.data().object()); FutureGet futureGet1b = p2.get(lKey).domainKey(dKey).contentKey(cKey).start(); futureGet1b.awaitUninterruptibly(); Assert.assertTrue(futureGet1b.isSuccess()); Assert.assertEquals(testData1, (String) futureGet1b.data().object()); // remove with correct key pair FutureRemove futureRemove4 = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO)) .to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).keyPair(keyPairData).start(); futureRemove4.awaitUninterruptibly(); Assert.assertTrue(futureRemove4.isSuccess()); FutureGet futureGet4a = p2.get(lKey).domainKey(dKey).contentKey(cKey).start(); futureGet4a.awaitUninterruptibly(); // we did not find the data Assert.assertTrue(futureGet4a.isEmpty()); // should have been removed Assert.assertNull(futureGet4a.data()); FutureGet futureGet4b = p2.get(lKey).contentKey(cKey).start(); futureGet4b.awaitUninterruptibly(); // we did not find the data Assert.assertTrue(futureGet4b.isEmpty()); // should have been removed Assert.assertNull(futureGet4b.data()); } finally { p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } } @Test public void testRemoveFutureResponse() throws NoSuchAlgorithmException, IOException, InvalidKeyException, SignatureException, ClassNotFoundException { KeyPair keyPairPeer1 = keyGen.generateKeyPair(); KeyPair keyPairPeer2 = keyGen.generateKeyPair(); PeerDHT p1 = null, p2 = null; try { p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1).start()) .start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair key1 = keyGen.generateKeyPair(); String locationKey = "location"; Number160 lKey = Number160.createHash(locationKey); // String domainKey = "domain"; // Number160 dKey = Number160.createHash(domainKey); String contentKey = "content"; Number160 cKey = Number160.createHash(contentKey); String testData1 = "data1"; Data data = new Data(testData1).protectEntryNow(key1, factory); // put trough peer 1 with key pair FuturePut futurePut1 = p1.put(lKey).data(cKey, data).keyPair(key1).start(); futurePut1.awaitUninterruptibly(); Assert.assertTrue(futurePut1.isSuccess()); FutureGet futureGet1a = p1.get(lKey).contentKey(cKey).start(); futureGet1a.awaitUninterruptibly(); Assert.assertTrue(futureGet1a.isSuccess()); Assert.assertEquals(testData1, (String) futureGet1a.data().object()); FutureGet futureGet1b = p2.get(lKey).contentKey(cKey).start(); futureGet1b.awaitUninterruptibly(); Assert.assertTrue(futureGet1b.isSuccess()); Assert.assertEquals(testData1, (String) futureGet1b.data().object()); // try to remove without key pair using the direct remove // should fail FutureRemove futureRemoveDirect = p1.remove(lKey).contentKey(cKey).start(); futureRemoveDirect.awaitUninterruptibly(); // try to remove without key pair using the from/to // should fail FutureRemove futureRemoveFromTo = p1.remove(lKey) .from(new Number640(lKey, Number160.ZERO, cKey, Number160.ZERO)) .to(new Number640(lKey, Number160.ZERO, cKey, Number160.MAX_VALUE)).start(); futureRemoveFromTo.awaitUninterruptibly(); Assert.assertEquals(futureRemoveDirect.isRemoved(), futureRemoveFromTo.isRemoved()); Assert.assertFalse(futureRemoveDirect.isRemoved()); Assert.assertFalse(futureRemoveFromTo.isRemoved()); } finally { p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } } @Test public void testChangeProtectionKey() throws NoSuchAlgorithmException, IOException, InvalidKeyException, SignatureException, ClassNotFoundException { KeyPair keyPairPeer1 = keyGen.generateKeyPair(); KeyPair keyPairPeer2 = keyGen.generateKeyPair(); PeerDHT p1 = null, p2 = null; try { p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4834).keyPair(keyPairPeer1).start()) .start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = keyGen.generateKeyPair(); KeyPair keyPair2 = keyGen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); // initial put String testData = "data"; Data data = new Data(testData).protectEntryNow(keyPair1, factory); FuturePut futurePut1 = p1.put(lKey).domainKey(dKey).sign().data(cKey, data).keyPair(keyPair1).start(); futurePut1.awaitUninterruptibly(); Assert.assertTrue(futurePut1.isSuccess()); Data retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).start().awaitUninterruptibly().data(); Assert.assertEquals(testData, (String) retData.object()); Assert.assertTrue(retData.verify(keyPair1.getPublic(), factory)); retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).start().awaitUninterruptibly().data(); Assert.assertEquals(testData, (String) retData.object()); Assert.assertTrue(retData.verify(keyPair1.getPublic(), factory)); // change the key pair to the new one using an empty data object data = new Data(testData).protectEntryNow(keyPair2, factory).duplicateMeta(); // use the old protection key to sign the message FuturePut futurePut2 = p1.put(lKey).domainKey(dKey).sign().putMeta().data(cKey, data).keyPair(keyPair1).start(); futurePut2.awaitUninterruptibly(); Assert.assertTrue(futurePut2.isSuccess()); retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).start().awaitUninterruptibly().data(); Assert.assertEquals(testData, (String) retData.object()); Assert.assertTrue(retData.verify(keyPair2.getPublic(), factory)); retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).start().awaitUninterruptibly().data(); Assert.assertEquals(testData, (String) retData.object()); Assert.assertTrue(retData.verify(keyPair2.getPublic(), factory)); // should be not possible to modify data = new Data().protectEntryNow(keyPair1, factory); FuturePut futurePut3 = p1.put(lKey).domainKey(dKey).sign().data(cKey, data).keyPair(keyPair1).start(); futurePut3.awaitUninterruptibly(); Assert.assertFalse(futurePut3.isSuccess()); retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).start().awaitUninterruptibly().data(); Assert.assertEquals(testData, (String) retData.object()); Assert.assertTrue(retData.verify(keyPair2.getPublic(), factory)); retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).start().awaitUninterruptibly().data(); Assert.assertEquals(testData, (String) retData.object()); Assert.assertTrue(retData.verify(keyPair2.getPublic(), factory)); // modify with new protection key String newTestData = "new data"; data = new Data(newTestData).protectEntryNow(keyPair2, factory); FuturePut futurePut4 = p1.put(lKey).domainKey(dKey).sign().data(cKey, data).keyPair(keyPair2).start(); futurePut4.awaitUninterruptibly(); Assert.assertTrue(futurePut4.isSuccess()); retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).start().awaitUninterruptibly().data(); Assert.assertEquals(newTestData, (String) retData.object()); Assert.assertTrue(retData.verify(keyPair2.getPublic(), factory)); retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).start().awaitUninterruptibly().data(); Assert.assertEquals(newTestData, (String) retData.object()); Assert.assertTrue(retData.verify(keyPair2.getPublic(), factory)); } finally { p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } } @Test public void testChangeProtectionKeyWithVersions() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, InvalidKeyException, SignatureException { KeyPair keyPairPeer1 = keyGen.generateKeyPair(); KeyPair keyPairPeer2 = keyGen.generateKeyPair(); PeerDHT p1 = null; PeerDHT p2 = null; try { p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4834).keyPair(keyPairPeer1).start()) .start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = keyGen.generateKeyPair(); KeyPair keyPair2 = keyGen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); // put the first version of the content with key pair 1 Number160 vKey1 = Number160.createHash("version1"); Data data = new Data("data1v1").protectEntryNow(keyPair1, factory); data.addBasedOn(Number160.ZERO); FuturePut futurePut1 = p1.put(lKey).domainKey(dKey).sign().data(cKey, data).keyPair(keyPair1).versionKey(vKey1) .start(); futurePut1.awaitUninterruptibly(); Assert.assertTrue(futurePut1.isSuccess()); // add another version with the correct key pair 1 Number160 vKey2 = Number160.createHash("version2"); data = new Data("data1v2").protectEntryNow(keyPair1, factory); data.addBasedOn(vKey1); FuturePut futurePut2 = p1.put(lKey).domainKey(dKey).sign().data(cKey, data).keyPair(keyPair1).versionKey(vKey2) .start(); futurePut2.awaitUninterruptibly(); Assert.assertTrue(futurePut2.isSuccess()); // put new version with other key pair 2 (expected to fail) Number160 vKey3 = Number160.createHash("version3"); data = new Data("data1v3").protectEntryNow(keyPair2, factory); data.addBasedOn(vKey2); FuturePut futurePut3 = p1.put(lKey).domainKey(dKey).data(cKey, data).keyPair(keyPair2).versionKey(vKey3).start(); futurePut3.awaitUninterruptibly(); Assert.assertFalse(futurePut3.isSuccess()); // change the key pair to the new one using an empty data object data = new Data().protectEntryNow(keyPair2, factory).duplicateMeta(); // use the old protection key to sign the message FuturePut futurePut4 = p1.put(lKey).domainKey(dKey).sign().putMeta().data(cKey, data).keyPair(keyPair1).start(); futurePut4.awaitUninterruptibly(); Assert.assertFalse(futurePut4.isSuccess()); // verify if the two versions have the new protection key Data retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey1).start().awaitUninterruptibly() .data(); Assert.assertEquals("data1v1", (String) retData.object()); Assert.assertFalse(retData.verify(keyPair2.getPublic(), factory)); retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey2).start().awaitUninterruptibly().data(); // Assert.assertEquals("data1v2", (String) retData.object()); Assert.assertFalse(retData.verify(keyPair2.getPublic(), factory)); // add another version with the new protection key Number160 vKey4 = Number160.createHash("version4"); data = new Data("data1v4").protectEntryNow(keyPair2, factory); data.addBasedOn(vKey2); FuturePut futurePut5 = p1.put(lKey).domainKey(dKey).sign().data(cKey, data).keyPair(keyPair2).versionKey(vKey4) .start(); futurePut5.awaitUninterruptibly(); Assert.assertTrue(futurePut5.isSuccess()); } finally { p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } } @Test public void testGetMeta() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, InvalidKeyException, SignatureException { KeyPair keyPairPeer1 = keyGen.generateKeyPair(); KeyPair keyPairPeer2 = keyGen.generateKeyPair(); PeerDHT p1 = null; PeerDHT p2 = null; try { p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4834).keyPair(keyPairPeer1).start()) .start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = keyGen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Data data = new Data("data1v11").protectEntryNow(keyPair1, factory); FuturePut futurePut = p1.put(lKey).sign().data(data).keyPair(keyPair1).start(); futurePut.awaitUninterruptibly(); Assert.assertTrue(futurePut.isSuccess()); FutureDigest futureDigest = p1.digest(lKey).returnMetaValues().start(); futureDigest.awaitUninterruptibly(); Assert.assertTrue(futureDigest.isSuccess()); Data dataMeta = futureDigest.digest().dataMap().values().iterator().next(); Assert.assertEquals(keyPair1.getPublic(), dataMeta.publicKey()); Assert.assertEquals(data.signature(), dataMeta.signature()); Assert.assertEquals(0, dataMeta.length()); } finally { p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } } @Test public void testSignature() throws InvalidKeyException, SignatureException, IOException, NoSuchAlgorithmException { SignatureFactory signatureFactory = new RSASignatureFactory(); // generate some test data Data testData = new Data("test"); // create a content protection key KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); KeyPair protectionKey = gen.generateKeyPair(); SignatureCodec signature = signatureFactory.sign(protectionKey.getPrivate(), testData.buffer()); boolean isVerified = signatureFactory.verify(protectionKey.getPublic(), testData.buffer(), signature); Assert.assertTrue(isVerified); } @Test public void testTTLDecrement() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, InterruptedException { KeyPair keyPairPeer1 = keyGen.generateKeyPair(); KeyPair keyPairPeer2 = keyGen.generateKeyPair(); PeerDHT p1 = null; PeerDHT p2 = null; try { StorageMemory sm1 = new StorageMemory(1); StorageMemory sm2 = new StorageMemory(1); p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4834).keyPair(keyPairPeer1).start()) .storage(sm1).start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).storage(sm2).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = keyGen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); Number160 vKey = Number160.createHash("version"); Number160 bKey = Number160.ZERO; int ttl = 4; String testData = "data"; Data data = new Data(testData).protectEntry(keyPair1); data.ttlSeconds(ttl).addBasedOn(bKey); // initial put FuturePut futurePut = p1.put(lKey).domainKey(dKey).data(cKey, data).versionKey(vKey).keyPair(keyPair1).start(); futurePut.awaitUninterruptibly(); Assert.assertTrue(futurePut.isSuccess()); // wait a moment, so that the ttl decrements Thread.sleep(2000); // check decrement of ttl through a normal get FutureGet futureGet = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start(); futureGet.awaitUninterruptibly(); Assert.assertTrue(futureGet.isSuccess()); System.err.println(futureGet.data().ttlSeconds()); Assert.assertTrue(ttl > futureGet.data().ttlSeconds()); // check decrement of ttl through a get meta FutureDigest futureDigest = p1.digest(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).returnMetaValues() .start(); futureDigest.awaitUninterruptibly(); Assert.assertTrue(futureDigest.isSuccess()); Data dataMeta = futureDigest.digest().dataMap().values().iterator().next(); Assert.assertTrue(ttl > dataMeta.ttlSeconds()); // wait again a moment, till data gets expired Thread.sleep(2000); // check if data has been removed Data retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly() .data(); Assert.assertNull(retData); } finally { p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } } @Test public void testChangeProtectionKeyWithReusedSignature() throws Exception { PeerDHT p1 = null; PeerDHT p2 = null; try { KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); // create custom RSA factories SignatureFactory factory = new RSASignatureFactory(); // replace default signature factories ChannelClientConfiguration clientConfig = PeerBuilder.createDefaultChannelClientConfiguration(); clientConfig.signatureFactory(factory); ChannelServerConfiguration serverConfig = PeerBuilder.createDefaultChannelServerConfiguration(); serverConfig.signatureFactory(factory); KeyPair keyPairPeer1 = gen.generateKeyPair(); p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4834).keyPair(keyPairPeer1) .channelClientConfiguration(clientConfig).channelServerConfiguration(serverConfig).start()).start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .channelClientConfiguration(clientConfig).channelServerConfiguration(serverConfig).start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPairOld = gen.generateKeyPair(); KeyPair keyPairNew = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); Number160 vKey = Number160.createHash("version"); Number160 bKey = Number160.ZERO; int ttl = 10; String testData = "data"; Data data = new Data(testData).protectEntryNow(keyPairOld, factory); data.ttlSeconds(ttl).addBasedOn(bKey); // initial put of some test data FuturePut futurePut = p1.put(lKey).domainKey(dKey).data(cKey, data).versionKey(vKey).keyPair(keyPairOld).start(); futurePut.awaitUninterruptibly(); Assert.assertTrue(futurePut.isSuccess()); // create signature with old key pair having the data object byte[] signature1 = factory.sign(keyPairOld.getPrivate(), data.buffer()).encode(); // decrypt signature to get hash of the object Cipher rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.DECRYPT_MODE, keyPairOld.getPublic()); byte[] hash = rsa.doFinal(signature1); // encrypt hash with new key pair to get the new signature (without // having the data object) rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.ENCRYPT_MODE, keyPairNew.getPrivate()); byte[] signatureNew = rsa.doFinal(hash); // verify old content protection keys Data retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly() .data(); Assert.assertTrue(retData.verify(keyPairOld.getPublic(), factory)); // create a dummy data object for changing the content protection // key // through a put meta Data dummyData = new Data(); dummyData.addBasedOn(bKey).ttlSeconds(ttl); // assign the reused hash from signature (don't forget to set the // signedflag) dummyData.signature(new RSASignatureCodec(signatureNew)).signed(true).duplicateMeta(); // change content protection key through a put meta FuturePut futurePutMeta = p1.put(lKey).domainKey(dKey).putMeta().data(cKey, dummyData).versionKey(vKey) .keyPair(keyPairOld).start(); futurePutMeta.awaitUninterruptibly(); Assert.assertTrue(futurePutMeta.isSuccess()); // verify new content protection keys retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertTrue(retData.verify(keyPairNew.getPublic(), factory)); } finally { p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } } }
package cz.siret.prank.geom; import com.google.common.collect.Lists; import cz.siret.prank.features.api.AtomFeatureCalculator; import cz.siret.prank.geom.kdtree.AtomKdTree; import cz.siret.prank.program.params.Params; import cz.siret.prank.utils.ATimer; import cz.siret.prank.utils.CutoffAtomsCallLog; import cz.siret.prank.utils.PerfUtils; import org.biojava.nbio.structure.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.stream.Collectors; import static cz.siret.prank.utils.ATimer.startTimer; /** * list of atoms with additional properties */ public final class Atoms implements Iterable<Atom> { private static final Logger log = LoggerFactory.getLogger(Atoms.class); private static final int KD_TREE_THRESHOLD = 15; public final List<Atom> list; private Map<Integer, Atom> index; private AtomKdTree kdTree; private Atom centerOfMass; public Atoms() { list = new ArrayList<>(); } public Atoms(int initialCapacity) { list = new ArrayList<>(initialCapacity); } public Atoms(List<? extends Atom> list) { if (list == null) throw new AssertionError(); this.list = (List<Atom>) list; } public Atoms(Collection<? extends Atom> collection) { if (collection == null) throw new AssertionError(); this.list = new ArrayList<>(collection.size()); this.list.addAll(collection); } /** * copy atoms and fill with points */ public static Atoms copyPoints(Atom... atoms) { Atoms res = new Atoms(atoms.length); for (Atom a: atoms) { res.add(new Point(a.getCoords())); } return res; } /** * @return Atom objects with Points (all have unit C mass) */ public Atoms toPoints() { return copyPoints(this.list.toArray(new Atom[0])); } public List<Integer> getIndexes() { return list.stream().map(Atom::getPDBserial).collect(Collectors.toList()); } public Atoms(Atom atom) { this(Lists.newArrayList(atom)); } public Atoms(Atoms atoms) { this(atoms.list); } public Atoms withIndex() { index = new HashMap<>(list.size()); for (Atom a : list) { index.put(a.getPDBserial(), a); } return this; } /** * @return conditionally builds KDTree */ public Atoms withKdTreeConditional() { if (getCount() > KD_TREE_THRESHOLD) { if (kdTree==null || kdTree.size()!=getCount()) { buildKdTree(); } } return this; } public Atoms withKdTree() { if (kdTree==null) { buildKdTree(); } return this; } /** * @return builds KDTree */ public Atoms buildKdTree() { kdTree = AtomKdTree.build(this); return this; } public AtomKdTree getKdTree() { return kdTree; } @Override public Iterator<Atom> iterator() { return list.iterator(); } /** * based on index and PDBSerial */ public boolean contains(Atom a) { withIndex(); return index.containsKey(a.getPDBserial()); } /** * @param id pdb serial (PDBserial) of the atom */ public Atom getByID(int id) { return this.index.get(id); } public int getCount() { return list.size(); } public boolean isEmpty() { return getCount()==0; } public double dist(Atom a) { if (kdTree!=null && getCount() > KD_TREE_THRESHOLD) { return kdTree.nearestDist(a); } else { return Struct.dist(a, list); } } public double sqrDist(Atom a) { if (kdTree!=null && getCount() > KD_TREE_THRESHOLD) { return kdTree.nearestSqrDist(a); } else { return Struct.sqrDist(a, list); } } public double dist(Atoms toAtoms) { double sqrMin = Double.POSITIVE_INFINITY; for (Atom a : toAtoms) { double next = sqrDist(a); if (next < sqrMin) { sqrMin = next; } } return Math.sqrt(sqrMin); } public boolean areWithinDistance(Atom a, double dist) { if (kdTree!=null && getCount() > KD_TREE_THRESHOLD) { return kdTree.nearestDist(a) <= dist; } else { return Struct.areWithinDistance(a, this.list, dist); } } public boolean areWithinDistance(Atoms toAtoms, double dist) { return areWithinDistance(this, toAtoms, dist); } private static boolean areWithinDistance(Atoms aa, Atoms ab, double dist) { Atoms bigger; Atoms smaller; if (ab.getCount() > aa.getCount()) { bigger = ab; smaller = aa; } else { bigger = aa; smaller = ab; } bigger.withKdTreeConditional(); for (Atom a : smaller) { if (bigger.areWithinDistance(a, dist)) { // give a chance to kdtree return true; } } return false; } public boolean areDistantFromAtomAtLeast(Atom a, double dist) { return Struct.areDistantAtLeast(a, this.list, dist); } public Atom getCenterOfMass() { if (list.isEmpty()) { return null; } if (centerOfMass==null) { Atom[] aa = new Atom[list.size()]; aa = list.toArray(aa); centerOfMass = Calc.centerOfMass(aa); } return centerOfMass; } public List<Group> getDistinctGroupsSorted() { return Struct.sortedGroups(getDistinctGroups()); } public List<Group> getDistinctGroups() { Set<Group> res = new HashSet<>(); for (Atom a : list) { if (a.getGroup()!=null) { res.add(a.getGroup()); } } return new ArrayList<>(res); } public void add(Atom a) { list.add(a); if (kdTree!=null) { kdTree.add(a); } } public Atoms addAll(Atoms atoms) { list.addAll(atoms.list); if (kdTree!=null) { kdTree.addAll(atoms); } return this; } public Atoms addAll(Collection<Atoms> col) { for (Atoms a : col) { addAll(a); } return this; } public static Atoms join(Collection<Atoms> col) { return new Atoms().addAll(col); } /** * @return new instance */ public Atoms joinWith(Atoms atoms) { List<Atom> newlist = new ArrayList<>(list.size() + atoms.getCount()); newlist.addAll(list); newlist.addAll(atoms.list); return new Atoms(newlist); } /** * @return new instance */ public Atoms plus(Atoms atoms) { return joinWith(atoms); } public static Atoms union(Atoms... aa) { return union(Arrays.asList(aa)); } public static Atoms union(Collection<Atoms> aa) { Set<Atom> res = new HashSet<>(100); for (Atoms a : aa) { if (a != null) { res.addAll(a.list); } } return new Atoms(res); } public static Atoms intersection(Atoms aa, Atoms bb) { Set<Atom> bset = new HashSet<>(bb.list); List<Atom> res = new ArrayList<>(aa.getCount()); for (Atom a : aa) { if (bset.contains(a)) { res.add(a); } } return new Atoms(res); } public Atoms cutoutShell(Atoms aroundAtoms, double dist) { if (aroundAtoms==null || aroundAtoms.isEmpty()) { return new Atoms(0); } // Atom center; // double additionalDist; // if (aroundAtoms.getCount()==1) { // center = aroundAtoms.list.get(0); // return cutoutSphere(center, dist); // } else { // Box box = Box.aroundAtoms(aroundAtoms); // center = box.getCenter(); // additionalDist = Struct.dist(center, box.getMax()); // Atoms ofAtoms = this.cutoutSphere(center, dist + additionalDist); // return cutoutShell(ofAtoms, aroundAtoms, dist); return cutoutShell(this, aroundAtoms, dist); } public static Atoms cutoutShell(Atoms ofAtoms, Atoms aroundAtoms, double dist) { if (aroundAtoms==null || aroundAtoms.isEmpty()) { return new Atoms(0); } aroundAtoms.withKdTreeConditional(); Atoms res = new Atoms(128); double sqrDist = dist*dist; for (Atom a : ofAtoms) { if (aroundAtoms.sqrDist(a) <= sqrDist) { res.add(a); } } return res; } /** * intercepting calls for further alalysis */ public Atoms cutSphere_(Atom distanceTo, double dist) { ATimer timer = startTimer(); Atoms res = cutoutSphere(distanceTo, dist); CutoffAtomsCallLog.INST.addCall(getCount(), res.getCount(), timer.getTime()); return res; } public Atoms cutoutSphereSerial(Atom center, double radius) { List<Atom> res = new ArrayList<>(); double sqrDist = radius*radius; double[] toCoords = center.getCoords(); for (Atom a : list) { if (PerfUtils.sqrDist(a.getCoords(), toCoords) <= sqrDist) { res.add(a); } } return new Atoms(res); } public Atoms cutoutSphereKD(Atom center, double radius) { withKdTree(); return kdTree.findAtomsWithinRadius(center, radius, false); } public Atoms cutoutSphere(Atom center, double radius) { if (getCount() >= Params.INSTANCE.getUse_kdtree_cutout_sphere_thrashold()) { return cutoutSphereKD(center, radius); } else { return cutoutSphereSerial(center, radius); } } public Atoms cutoutBox(Box box) { return new Atoms(Struct.cutoffAtomsInBox(this.list, box)); } public Atoms withoutHydrogens() { return withoutHydrogenAtoms(this); } public Atoms without(Atoms remove) { List<Atom> res = new ArrayList<>(list.size()); for (Atom a : list) { if (!remove.contains(a)) { res.add(a); } } return new Atoms(res); } /** * delete atoms that are too close together */ public static Atoms consolidate(Atoms atoms, double dist) { Atoms res = new Atoms().buildKdTree(); dist = dist*dist; for (Atom a : atoms) { Atom nearest = res.kdTree.findNearest(a); if (nearest==null || Struct.sqrDist(a, nearest) > dist) { res.add(a); } } return res; } public static Atoms allFromStructure(Structure struc) { List<Atom> list = new ArrayList<>(3000); AtomIterator atomIterator = new AtomIterator(struc); while (atomIterator.hasNext()) { list.add(atomIterator.next()); } return new Atoms(list); } public static Atoms withoutHydrogenAtoms(Atoms atoms) { Atoms res = new Atoms(atoms.getCount()); for (Atom a : atoms) { if (!Struct.isHydrogenAtom(a)) { res.add(a); } } return res; } public static Atoms onlyProteinAtoms(Atoms structAtoms) { List<Atom> res = new ArrayList<>(structAtoms.getCount()); for (Atom a : structAtoms) { if (Struct.isProteinChainGroup(a.getGroup())) { res.add(a); } } return new Atoms(res); } public static Atoms onlyProteinAtoms(Structure struc) { // TODO UNK residues, double models return onlyProteinAtoms(allFromStructure(struc)); } public static Atoms allFromGroup(Group group) { return new Atoms(group.getAtoms()); } public static Atoms allFromGroups(List<? extends Group> groups) { Atoms res = new Atoms(); for (Group g : groups) { res.list.addAll(g.getAtoms()); } return res; } public static Atoms allFromChain(Chain chain) { return allFromGroups(chain.getAtomGroups()); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication04; /** * * @author marsh */ public class Polynomial { Integer degree_; Node head; public Polynomial() { } public int getCoefficient(int power) { Node cur = head; while(cur != null && cur.power_ <= power) { if(cur.power_ == power) { return cur.coeff_; } cur = cur.next_; } return 0; } Node getCoefficientNode(int power) { Node cur = head; while(cur != null && cur.power_ <= power) { if(cur.power_ == power) { return cur; } cur = cur.next_; } return null; } public void setCoefficient(int coef, int power) { Node cur, prev; cur = head; if(getCoeffricentNode(power) == null) { if(cur == null) { head = new Node(coef, power); return; } while(cur != null) { //add item if if(cur.power_ > power) { prev.next_ = new Node(coef, power, cur); return; } prev = cur; cur = cur.next_; } prev.next_ = new Node(coef, power); return; } getCoeffricentNode(power).coeff_ = coef; } @Override public String toString() { String returnMe = ""; Node cur = head; while(cur != null) { returnMe = returnMe + cur.coeff_ +"x^" + cur.power_; cur = cur.next_; } return returnMe; } } class Node { int coeff_; int power_; Node next_; public Node(int coeff, int power) { coeff_ = coeff; power_ = power; } public Node(int coeff, int power, Node next) { coeff_ = coeff; power_ = power; next_ = next; } }
/* * $Log: Base64Pipe.java,v $ * Revision 1.7 2010-09-21 14:54:51 L190409 * lineLength and separator configurable * * Revision 1.6 2010/04/28 09:53:22 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * enabled use of InputStream as input. * replaced Base64 codec by Apache Commons Codec 1.4 * * Revision 1.5 2008/12/16 13:40:52 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added charset attribute * * Revision 1.4 2008/03/20 12:06:56 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated javadoc * * Revision 1.3 2006/04/25 06:56:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added attribute convert2String * * Revision 1.2 2005/10/13 11:44:53 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * switched encode and decode code * * Revision 1.1 2005/10/05 07:38:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * introduction of Base64Pipe * */ package nl.nn.adapterframework.pipes; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.PipeRunException; import nl.nn.adapterframework.core.PipeRunResult; import nl.nn.adapterframework.util.Misc; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64InputStream; import org.apache.commons.lang.StringUtils; public class Base64Pipe extends FixedForwardPipe { private String direction="encode"; private boolean convert2String=true; private int lineLength=76; private String lineSeparator="auto"; private String charset=Misc.DEFAULT_INPUT_STREAM_ENCODING; private byte lineSeparatorArray[]; public void configure() throws ConfigurationException { super.configure(); String dir=getDirection(); if (dir==null) { throw new ConfigurationException(getLogPrefix(null)+"direction must be set"); } if (!dir.equalsIgnoreCase("encode") && !dir.equalsIgnoreCase("decode")) { throw new ConfigurationException(getLogPrefix(null)+"illegal value for direction ["+dir+"], must be 'encode' or 'decode'"); } if (dir.equalsIgnoreCase("encode")) { if (StringUtils.isEmpty(getLineSeparator())) { setLineSeparatorArray(""); } else if (getLineSeparator().equalsIgnoreCase("auto")) { setLineSeparatorArray(System.getProperty ( "line.separator" )); } else if (getLineSeparator().equalsIgnoreCase("dos")) { setLineSeparatorArray("\r\n"); } else if (getLineSeparator().equalsIgnoreCase("unix")) { setLineSeparatorArray("\n"); } else { setLineSeparatorArray(getLineSeparator()); } } } private void setLineSeparatorArray(String separator) { lineSeparatorArray=separator.getBytes(); } public PipeRunResult doPipe(Object invoer, PipeLineSession session) throws PipeRunException { Object result=null; if (invoer!=null) { if ("encode".equalsIgnoreCase(getDirection())) { InputStream binaryInputStream; if (convert2String) { if (StringUtils.isEmpty(getCharset())) { binaryInputStream = new ByteArrayInputStream(invoer.toString().getBytes()); } else { try { binaryInputStream = new ByteArrayInputStream(invoer.toString().getBytes(getCharset())); } catch (UnsupportedEncodingException e) { throw new PipeRunException(this,"cannot encode message using charset ["+getCharset()+"]",e); } } } else if (invoer instanceof InputStream) { binaryInputStream = (InputStream)invoer; } else { binaryInputStream = new ByteArrayInputStream((byte[])invoer); } try { result=Misc.streamToString(new Base64InputStream(binaryInputStream,true,getLineLength(),lineSeparatorArray),null,false); } catch (IOException e) { throw new PipeRunException(this,"cannot encode message from inputstream",e); } } else { String in; if (invoer instanceof InputStream) { try { in=Misc.streamToString((InputStream)invoer,null,false); } catch (IOException e) { throw new PipeRunException(this,"cannot read inputstream",e); } } else { in=invoer.toString(); } try { byte[] data=Base64.decodeBase64(in); if (convert2String) { if (StringUtils.isEmpty(getCharset())) { result=new String(data); } else { result=new String(data,getCharset()); } } else { result=data; } } catch (IOException e) { throw new PipeRunException(this, getLogPrefix(session)+"cannot decode base64, charset ["+getCharset()+"]", e); } } } else { log.debug(getLogPrefix(session)+"has null input, returning null"); } return new PipeRunResult(getForward(), result); } public void setDirection(String string) { direction = string; } public String getDirection() { return direction; } public void setConvert2String(boolean b) { convert2String = b; } public void setCharset(String string) { charset = string; } public String getCharset() { return charset; } public void setLineSeparator(String lineSeparator) { this.lineSeparator = lineSeparator; } public String getLineSeparator() { return lineSeparator; } public void setLineLength(int lineLength) { this.lineLength = lineLength; } public int getLineLength() { return lineLength; } }
package backend.resource; import backend.resource.serialization.SerializableLabel; import javafx.scene.Node; import javafx.scene.control.Tooltip; import org.eclipse.egit.github.core.Label; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; @SuppressWarnings("unused") public class TurboLabel implements Comparable<TurboLabel> { public static final String EXCLUSIVE_DELIMITER = "."; public static final String NONEXCLUSIVE_DELIMITER = "-"; private void ______SERIALIZED_FIELDS______() { } private final String actualName; private final String colour; private void ______TRANSIENT_FIELDS______() { } private final String repoId; private void ______CONSTRUCTORS______() { } public TurboLabel(String repoId, String name) { this.actualName = name; this.colour = "ffffff"; this.repoId = repoId; } public TurboLabel(String repoId, String colour, String name) { this.actualName = name; this.colour = colour; this.repoId = repoId; } public static TurboLabel nonexclusive(String repoId, String group, String name) { return new TurboLabel(repoId, joinWith(group, name, false)); } public static TurboLabel exclusive(String repoId, String group, String name) { return new TurboLabel(repoId, joinWith(group, name, true)); } public TurboLabel(String repoId, Label label) { this.actualName = label.getName(); this.colour = label.getColor(); this.repoId = repoId; } public TurboLabel(String repoId, SerializableLabel label) { this.actualName = label.getActualName(); this.colour = label.getColour(); this.repoId = repoId; } private void ______METHODS______() { } public static Optional<String> getDelimiter(String name) { // Escaping due to constants not being valid regexes Pattern p = Pattern.compile(String.format("^[^\\%s\\%s]+(\\%s|\\%s)", EXCLUSIVE_DELIMITER, NONEXCLUSIVE_DELIMITER, EXCLUSIVE_DELIMITER, NONEXCLUSIVE_DELIMITER)); Matcher m = p.matcher(name); if (m.find()) { return Optional.of(m.group(1)); } else { return Optional.empty(); } } private static String joinWith(String group, String name, boolean exclusive) { return group + (exclusive ? EXCLUSIVE_DELIMITER : NONEXCLUSIVE_DELIMITER) + name; } public boolean isExclusive() { return getDelimiter(actualName).isPresent() && getDelimiter(actualName).get().equals(EXCLUSIVE_DELIMITER); } public Optional<String> getGroup() { if (getDelimiter(actualName).isPresent()) { String delimiter = getDelimiter(actualName).get(); // Escaping due to constants not being valid regexes String[] segments = actualName.split("\\" + delimiter); assert segments.length >= 1; if (segments.length == 1) { if (actualName.endsWith(delimiter)) { // group. return Optional.of(segments[0]); } else { // .name return Optional.empty(); } } else { // group.name assert segments.length == 2; return Optional.of(segments[0]); } } else { // name return Optional.empty(); } } public String getName() { if (getDelimiter(actualName).isPresent()) { String delimiter = getDelimiter(actualName).get(); // Escaping due to constants not being valid regexes String[] segments = actualName.split("\\" + delimiter); assert segments.length >= 1; if (segments.length == 1) { if (actualName.endsWith(delimiter)) { // group. return ""; } else { // .name return segments[0]; } } else { // group.name assert segments.length == 2; return segments[1]; } } else { // name return actualName; } } public String getStyle() { String colour = getColour(); int r = Integer.parseInt(colour.substring(0, 2), 16); int g = Integer.parseInt(colour.substring(2, 4), 16); int b = Integer.parseInt(colour.substring(4, 6), 16); double luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b; boolean bright = luminance > 128; return "-fx-background-color: #" + getColour() + "; -fx-text-fill: " + (bright ? "black;" : "white;"); } public Node getNode() { javafx.scene.control.Label node = new javafx.scene.control.Label(getName()); node.getStyleClass().add("labels"); node.setStyle(getStyle()); if (getGroup().isPresent()) { Tooltip groupTooltip = new Tooltip(getGroup().get()); node.setTooltip(groupTooltip); } return node; } @Override public String toString() { return actualName; } private void ______BOILERPLATE______() { } public String getRepoId() { return repoId; } public String getColour() { return colour; } public String getActualName() { return actualName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TurboLabel that = (TurboLabel) o; return actualName.equals(that.actualName) && colour.equals(that.colour); } @Override public int hashCode() { int result = actualName.hashCode(); result = 31 * result + colour.hashCode(); return result; } @Override public int compareTo(TurboLabel o) { return actualName.compareTo(o.getActualName()); } }
package br.com.dbsoft.crud; import br.com.dbsoft.error.DBSIOException; import br.com.dbsoft.message.DBSMessage; import br.com.dbsoft.message.IDBSMessage; import br.com.dbsoft.message.IDBSMessageBase.MESSAGE_TYPE; import br.com.dbsoft.message.IDBSMessages; public interface IDBSCrud<DataModelClass> { public interface ICrudAction{ CrudAction NONE = CrudAction.NONE; CrudAction READING = CrudAction.READING; CrudAction MERGING = CrudAction.MERGING; CrudAction DELETING = CrudAction.DELETING; public String getName(); public int getCode(); public ICrudAction get(int pCode); } public enum CrudAction implements ICrudAction { NONE ("Not Editing", 0), READING ("Reading", 1), MERGING ("Merging", 2), DELETING ("Deleting", 3); private String wName; private int wCode; private CrudAction(String pName, int pCode) { this.wName = pName; this.wCode = pCode; } @Override public String getName() { return wName; } @Override public int getCode() { return wCode; } @Override public ICrudAction get(int pCode) { switch (pCode) { case 0: return NONE; case 1: return READING; case 2: return MERGING; case 3: return DELETING; default: return NONE; } } } // Mensagens IDBSMessage MsgErroNoPadrao = new DBSMessage(MESSAGE_TYPE.ERROR, "Erro"); public ICrudAction getCrudAction(); /** * Retorna se esta OK. * @return */ public boolean isOk(); public DataModelClass read(DataModelClass pDataModelClass) throws DBSIOException; public Integer merge(DataModelClass pDataModelClass) throws DBSIOException; public Integer delete(DataModelClass pDataModelClass) throws DBSIOException; public IDBSMessages validate(DataModelClass pDataModelClass) throws DBSIOException; public IDBSMessages getMessages(); }
package com.conveyal.gtfs; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.S3Object; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.io.ByteStreams; import com.google.common.io.Files; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.NoSuchElementException; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.function.Function; import java.util.zip.ZipFile; /** * Fast cache for GTFS feeds stored on S3. */ public class GTFSCache { private static final Logger LOG = LoggerFactory.getLogger(GTFSCache.class); public final String bucket; public final String bucketFolder; public final File cacheDir; private static final AmazonS3 s3 = new AmazonS3Client(); private LoadingCache<String, GTFSFeed> cache = CacheBuilder.newBuilder() .maximumSize(10) .build(new CacheLoader<String, GTFSFeed>() { @Override public GTFSFeed load(String s) throws Exception { return retrieveFeed(s); } }); /** If bucket is null, work offline and do not use S3 */ public GTFSCache(String bucket, File cacheDir) { if (bucket == null) LOG.info("No bucket specified; GTFS Cache will run locally"); else LOG.info("Using bucket {} for GTFS Cache", bucket); this.bucket = bucket; this.bucketFolder = null; this.cacheDir = cacheDir; } public GTFSCache(String bucket, String bucketFolder, File cacheDir) { if (bucket == null) LOG.info("No bucket specified; GTFS Cache will run locally"); else LOG.info("Using bucket {} for GTFS Cache", bucket); this.bucket = bucket; this.bucketFolder = bucketFolder != null ? bucketFolder.replaceAll("\\/","") : null; this.cacheDir = cacheDir; } /** * Add a GTFS feed to this cache with the given ID. NB this is not the feed ID, because feed IDs are not * unique when you load multiple versions of the same feed. */ public GTFSFeed put (String id, File feedFile) throws Exception { return put(id, feedFile, null); } /** Add a GTFS feed to this cache where the ID is calculated from the feed itself */ public GTFSFeed put (Function<GTFSFeed, String> idGenerator, File feedFile) throws Exception { return put(null, feedFile, idGenerator); } private GTFSFeed put (String id, File feedFile, Function<GTFSFeed, String> idGenerator) throws Exception { // generate temporary ID to name files String tempId = id != null ? id : UUID.randomUUID().toString(); // read the feed String cleanTempId = cleanId(tempId); File dbFile = new File(cacheDir, cleanTempId + ".db"); File movedFeedFile = new File(cacheDir, cleanTempId + ".zip"); // don't copy if we're loading from a locally-cached feed if (!feedFile.equals(movedFeedFile)) Files.copy(feedFile, movedFeedFile); GTFSFeed feed = new GTFSFeed(dbFile.getAbsolutePath()); feed.loadFromFile(new ZipFile(movedFeedFile)); feed.findPatterns(); if (idGenerator != null) id = idGenerator.apply(feed); String cleanId = cleanId(id); feed.close(); // make sure everything is written to disk if (idGenerator != null) { new File(cacheDir, cleanTempId + ".zip").renameTo(new File(cacheDir, cleanId + ".zip")); new File(cacheDir, cleanTempId + ".db").renameTo(new File(cacheDir, cleanId + ".db")); new File(cacheDir, cleanTempId + ".db.p").renameTo(new File(cacheDir, cleanId + ".db.p")); } // upload feed // TODO best way to do this? Should we zip the files together? if (bucket != null) { LOG.info("Writing feed to s3 cache"); String key = bucketFolder != null ? String.join("/", bucketFolder, cleanId) : cleanId; s3.putObject(bucket, key + ".zip", feedFile); LOG.info("Zip file written."); s3.putObject(bucket, key + ".db", new File(cacheDir, cleanId + ".db")); s3.putObject(bucket, key + ".db.p", new File(cacheDir, cleanId + ".db.p")); LOG.info("db files written."); } // reconnect to feed database feed = new GTFSFeed(new File(cacheDir, cleanId + ".db").getAbsolutePath()); cache.put(id, feed); return feed; } public GTFSFeed get (String id) { try { return cache.get(id); } catch (ExecutionException e) { throw new RuntimeException(e); } } public boolean containsId (String id) { GTFSFeed feed = null; try { feed = cache.get(id); } catch (Exception e) { return false; } return feed != null; } /** retrieve a feed from local cache or S3 */ private GTFSFeed retrieveFeed (String originalId) { // see if we have it cached locally String id = cleanId(originalId); String key = bucketFolder != null ? String.join("/", bucketFolder, id) : id; File dbFile = new File(cacheDir, id + ".db"); if (dbFile.exists()) { LOG.info("Processed GTFS was found cached locally"); return new GTFSFeed(dbFile.getAbsolutePath()); } if (bucket != null) { try { LOG.info("Attempting to download cached GTFS MapDB."); S3Object db = s3.getObject(bucket, key + ".db"); InputStream is = db.getObjectContent(); FileOutputStream fos = new FileOutputStream(dbFile); ByteStreams.copy(is, fos); is.close(); fos.close(); S3Object dbp = s3.getObject(bucket, key + ".db.p"); InputStream isp = dbp.getObjectContent(); FileOutputStream fosp = new FileOutputStream(new File(cacheDir, id + ".db.p")); ByteStreams.copy(isp, fosp); isp.close(); fosp.close(); LOG.info("Returning processed GTFS from S3"); return new GTFSFeed(dbFile.getAbsolutePath()); } catch (AmazonServiceException | IOException e) { LOG.info("Error retrieving MapDB from S3, will load from original GTFS.", e); } } // see if the // if we fell through to here, getting the mapdb was unsuccessful // grab GTFS from S3 if it is not found locally LOG.info("Loading feed from local cache directory..."); File feedFile = new File(cacheDir, id + ".zip"); if (!feedFile.exists() && bucket != null) { LOG.info("Feed not found locally, downloading from S3."); try { S3Object gtfs = s3.getObject(bucket, key + ".zip"); InputStream is = gtfs.getObjectContent(); FileOutputStream fos = new FileOutputStream(feedFile); ByteStreams.copy(is, fos); is.close(); fos.close(); } catch (Exception e) { LOG.warn("Could not download feed at s3://{}/{}.", bucket, key); throw new RuntimeException(e); } } if (feedFile.exists()) { // TODO this will also re-upload the original feed ZIP to S3. try { return put(originalId, feedFile); } catch (Exception e) { throw new RuntimeException(e); } } else { throw new NoSuchElementException(originalId); } } public static String cleanId(String id) { return id.replaceAll("[^A-Za-z0-9]", "-"); } }
package com.ninty.cmd; import com.ninty.classfile.AttributeInfo; import com.ninty.classfile.constantpool.ConstantInfo; import com.ninty.cmd.base.ICmdBase; import com.ninty.cmd.base.Index16Cmd; import com.ninty.cmd.base.Index8Cmd; import com.ninty.cmd.base.NoOperandCmd; import com.ninty.nativee.INativeMethod; import com.ninty.nativee.NaMethodManager; import com.ninty.nativee.lang.NaThrowable; import com.ninty.runtime.*; import com.ninty.runtime.heap.*; import com.ninty.runtime.heap.constantpool.*; import com.ninty.utils.VMUtils; import com.sun.jdi.NativeMethodException; public class CmdReferences { public static void invokeMethod(NiFrame frame, NiMethod method) { frame.getThread().invokeMethod(method); } private static void print(NiFrame frame, String desc) { OperandStack stack = frame.getOperandStack(); switch (desc) { case "(Z)V": System.out.println(stack.popInt() != 0); break; case "(C)V": System.out.println((char) stack.popInt()); break; case "(B)V": System.out.println((byte) stack.popInt()); break; case "(S)V": System.out.println((short) stack.popInt()); break; case "(I)V": System.out.println(stack.popInt()); break; case "(J)V": System.out.println(stack.popLong()); break; case "(F)V": System.out.println(stack.popFloat()); break; case "(D)V": System.out.println(stack.popDouble()); break; case "(Ljava/lang/String;)V": System.out.println(NiString.getString(stack.popRef())); break; default: NiObject ref = stack.popRef(); if (!NiString.isString(ref)) { frame.restorePostion(); NiMethod method = ref.getClz().getToStringMethod(); stack.pushRef(ref); invokeMethod(frame, method); return; } System.out.println(NiString.getString(ref)); } stack.popRef();// pop System.out } private static NiConstantPool getCP(NiFrame frame) { return frame.getMethod().getClz().getCps(); } private static void ldc(NiFrame frame, int index) { OperandStack stack = frame.getOperandStack(); NiClassLoader loader = frame.getMethod().getClz().getLoader(); NiConstantPool cp = getCP(frame); NiConstant constant = cp.get(index); if (constant instanceof NiConstant.NiInteger) { stack.pushInt(((NiConstant.NiInteger) constant).value); } else if (constant instanceof NiConstant.NiFloat) { stack.pushFloat(((NiConstant.NiFloat) constant).value); } else if (constant instanceof NiConstant.NiStr) { stack.pushRef(NiString.newString(loader, ((NiConstant.NiStr) constant).value)); } else if (constant instanceof ClassRef) { ClassRef ref = ((ClassRef) constant); ref.resolve(); NiObject jClass = ref.getClz().getjClass(); stack.pushRef(jClass); } else { throw new UnsupportedOperationException("ldc unknow"); } } public static class NEW extends Index16Cmd { @Override public void exec(NiFrame frame) { NiConstantPool cps = getCP(frame); ClassRef classRef = (ClassRef) cps.get(index); classRef.resolve(); NiClass clz = classRef.getClz(); if (clz.isInterface() || clz.isAbstract()) { throw new InstantiationError(clz.toString()); } if (!clz.isClinit()) { frame.restorePostion(); clz.clinit(frame.getThread()); return; } NiObject ref = clz.newObject(); frame.getOperandStack().pushRef(ref); } } public static class PUTSTATIC extends Index16Cmd { @Override public void exec(NiFrame frame) { NiMethod method = frame.getMethod(); NiClass curClz = method.getClz(); NiConstantPool cps = curClz.getCps(); FieldRef fieldRef = (FieldRef) cps.get(index); fieldRef.resolve(); NiClass clz = fieldRef.getClz(); if (!clz.isClinit()) { frame.restorePostion(); clz.clinit(frame.getThread()); return; } NiField field = fieldRef.getField(); if (!field.isStatic()) { throw new IncompatibleClassChangeError(field.toString()); } if (field.isFinal() && (curClz != clz || !method.getName().equals("<clinit>"))) { throw new IllegalAccessError("access final field failed"); } String desc = field.getDesc(); int slotId = field.getSlotId(); LocalVars slots = clz.getStaticSlots(); OperandStack stack = frame.getOperandStack(); switch (desc.charAt(0)) { case 'Z': case 'B': case 'C': case 'S': case 'I': slots.setInt(slotId, stack.popInt()); break; case 'F': slots.setFloat(slotId, stack.popFloat()); break; case 'J': slots.setLong(slotId, stack.popLong()); break; case 'D': slots.setDouble(slotId, stack.popLong()); break; case 'L': case '[': slots.setRef(slotId, stack.popRef()); break; } } } public static class GETSTATIC extends Index16Cmd { @Override public void exec(NiFrame frame) { NiConstantPool cps = getCP(frame); FieldRef fieldRef = (FieldRef) cps.get(index); fieldRef.resolve(); NiClass clz = fieldRef.getClz(); if (!clz.isClinit()) { frame.restorePostion(); clz.clinit(frame.getThread()); return; } NiField field = fieldRef.getField(); if (!field.isStatic()) { throw new IncompatibleClassChangeError(field.toString()); } String desc = field.getDesc(); int slotId = field.getSlotId(); LocalVars slots = clz.getStaticSlots(); OperandStack stack = frame.getOperandStack(); switch (desc.charAt(0)) { case 'Z': case 'B': case 'C': case 'S': case 'I': stack.pushInt(slots.getInt(slotId)); break; case 'F': stack.pushFloat(slots.getFloat(slotId)); break; case 'J': stack.pushLong(slots.getLong(slotId)); break; case 'D': stack.pushDouble(slots.getDouble(slotId)); break; case 'L': case '[': stack.pushRef(slots.getRef(slotId)); break; } } } public static class PUTFIELD extends Index16Cmd { @Override public void exec(NiFrame frame) { NiMethod method = frame.getMethod(); NiClass curClz = method.getClz(); NiConstantPool cps = curClz.getCps(); FieldRef fieldRef = (FieldRef) cps.get(index); fieldRef.resolve(); NiClass clz = fieldRef.getClz(); NiField field = fieldRef.getField(); if (field.isStatic()) { throw new IncompatibleClassChangeError(field.toString()); } if (field.isFinal() && (curClz != clz || !method.getName().equals("<init>"))) { throw new IllegalAccessError("access final field failed"); } String desc = field.getDesc(); int slotId = field.getSlotId(); OperandStack stack = frame.getOperandStack(); switch (desc.charAt(0)) { case 'Z': case 'B': case 'C': case 'S': case 'I': int ival = stack.popInt(); NiObject iref = stack.popRef(); LocalVars islots = iref.getFields(); islots.setInt(slotId, ival); break; case 'F': float fval = stack.popFloat(); NiObject fref = stack.popRef(); LocalVars fslots = fref.getFields(); fslots.setFloat(slotId, fval); break; case 'J': long lval = stack.popLong(); NiObject lref = stack.popRef(); LocalVars lslots = lref.getFields(); lslots.setLong(slotId, lval); break; case 'D': double dval = stack.popDouble(); NiObject dref = stack.popRef(); LocalVars dslots = dref.getFields(); dslots.setDouble(slotId, dval); break; case 'L': case '[': NiObject rval = stack.popRef(); NiObject rref = stack.popRef(); LocalVars rslots = rref.getFields(); rslots.setRef(slotId, rval); break; } } } public static class GETFIELD extends Index16Cmd { @Override public void exec(NiFrame frame) { NiConstantPool cps = getCP(frame); FieldRef fieldRef = (FieldRef) cps.get(index); fieldRef.resolve(); NiField field = fieldRef.getField(); if (field.isStatic()) { throw new IncompatibleClassChangeError(field.toString()); } OperandStack stack = frame.getOperandStack(); NiObject ref = stack.popRef(); if (ref == null) { throw new NullPointerException("can get ref"); } String desc = field.getDesc(); int slotId = field.getSlotId(); LocalVars slots = ref.getFields(); switch (desc.charAt(0)) { case 'Z': case 'B': case 'C': case 'S': case 'I': stack.pushInt(slots.getInt(slotId)); break; case 'F': stack.pushFloat(slots.getFloat(slotId)); break; case 'J': stack.pushLong(slots.getLong(slotId)); break; case 'D': stack.pushDouble(slots.getDouble(slotId)); break; case 'L': case '[': stack.pushRef(slots.getRef(slotId)); break; } } } public static class INSTANCE_OF extends Index16Cmd { @Override public void exec(NiFrame frame) { OperandStack stack = frame.getOperandStack(); NiObject ref = stack.popRef(); if (ref == null) { stack.pushInt(0); return; } NiConstantPool cps = getCP(frame); ClassRef classRef = (ClassRef) cps.get(index); classRef.resolve(); NiClass clz = classRef.getClz(); if (ref.isInstanceOf(clz)) { stack.pushInt(1); } else { stack.pushInt(0); } } } public static class CHECK_CAST extends Index16Cmd { @Override public void exec(NiFrame frame) { OperandStack stack = frame.getOperandStack(); NiObject ref = stack.popRef(); stack.pushRef(ref); if (ref == null) { return; } NiConstantPool cps = getCP(frame); ClassRef classRef = (ClassRef) cps.get(index); classRef.resolve(); NiClass clz = classRef.getClz(); if (!ref.isInstanceOf(clz)) { throw new ClassCastException(ref.getClz().getClassName() + " can not be cast to " + clz.getClassName()); } } } public static class LDC extends Index8Cmd { @Override public void exec(NiFrame frame) { ldc(frame, index); } } public static class LDC_W extends Index16Cmd { @Override public void exec(NiFrame frame) { ldc(frame, index); } } public static class LDC_2W extends Index16Cmd { @Override public void exec(NiFrame frame) { OperandStack stack = frame.getOperandStack(); NiConstantPool cp = getCP(frame); NiConstant constant = cp.get(index); if (constant instanceof NiConstant.NiLong) { stack.pushLong(((NiConstant.NiLong) constant).value); } else if (constant instanceof NiConstant.NiDouble) { stack.pushDouble(((NiConstant.NiDouble) constant).value); } else { throw new UnsupportedOperationException("ldc classRef"); } } } public static class INVOKE_STATIC extends Index16Cmd { @Override public void exec(NiFrame frame) { NiConstantPool cps = frame.getMethod().getClz().getCps(); MethodRef methodRef = (MethodRef) cps.get(index); methodRef.resolve(); NiClass clz = methodRef.getClz(); if (!clz.isClinit()) { frame.restorePostion(); clz.clinit(frame.getThread()); return; } NiMethod method = methodRef.getMethod(); if (!method.isStatic()) { throw new IncompatibleClassChangeError(method + " is not static"); } invokeMethod(frame, method); } } public static class INVOKE_SPECIAL extends Index16Cmd { @Override public void exec(NiFrame frame) { NiConstantPool cps = frame.getMethod().getClz().getCps(); MethodRef methodRef = (MethodRef) cps.get(index); methodRef.resolve(); NiMethod method = methodRef.getMethod(); NiClass clz = methodRef.getClz(); if (method.getName().equals("<init>") && method.getClz() != clz) { throw new NoSuchMethodError("should call <init> with same class, except:" + method.getClz() + ", while:" + clz); } if (method.isStatic()) { throw new IncompatibleClassChangeError(method + " is static"); } NiObject ref = frame.getOperandStack().getRefFromTop(method.getArgsCount()); if (ref == null) { throw new NullPointerException("this cannot be null"); } NiClass c = ref.getClz(); if (method.isProtected() && c.isSubClass(clz) && !c.isSamePackge(clz) && ref.getClz() != c && !c .isSubClass(ref.getClz())) { throw new IllegalAccessError("only self or subclass can access the protected method"); } NiMethod finalMethod = method; if (method.isSuper() && c.isSubClass(clz) && !method.getName().equals("<init>")) { finalMethod = MethodRef.lookUpMethods(c.getSuperClass(), methodRef.getName(), methodRef.getDesc()); } if (finalMethod == null || finalMethod.isAbstract()) { throw new AbstractMethodError(); } invokeMethod(frame, finalMethod); } } public static class INVOKE_VIRTUAL extends Index16Cmd { @Override public void exec(NiFrame frame) { NiConstantPool cps = frame.getMethod().getClz().getCps(); MethodRef methodRef = (MethodRef) cps.get(index); methodRef.resolve(); NiMethod method = methodRef.getMethod(); NiClass clz = methodRef.getClz(); if (method.isStatic()) { throw new IncompatibleClassChangeError(method + " is static"); } NiObject ref = frame.getOperandStack().getRefFromTop(method.getArgsCount()); if (ref == null) { //hack if (methodRef.getName().equals("println")) { print(frame, methodRef.getDesc()); return; } //hack end throw new NullPointerException("this cannot be null"); } NiClass c = ref.getClz(); if (method.isProtected() && c.isSubClass(clz) && !c.isSamePackge(clz) && ref.getClz() != c && !c .isSubClass(ref.getClz())) { throw new IllegalAccessError("only self or subclass can access the protected method"); } NiMethod finalMethod = MethodRef.lookUpMethods(c, methodRef.getName(), methodRef.getDesc()); ; if (finalMethod == null || finalMethod.isAbstract()) { throw new AbstractMethodError(); } invokeMethod(frame, finalMethod); } } // TODO vtable public static class INVOKE_INTERFACE implements ICmdBase { private int index; @Override public void init(CodeBytes bb) { index = bb.getChar(); bb.get(); //args count bb.get(); //must be 0 } @Override public void exec(NiFrame frame) { NiConstantPool cps = getCP(frame); InterfaceMethodRef methodRef = (InterfaceMethodRef) cps.get(index); methodRef.resolve(); NiMethod method = methodRef.getMethod(); if (method.isStatic() || method.isPrivate()) { throw new IncompatibleClassChangeError(); } NiObject self = frame.getOperandStack().getRefFromTop(method.getArgsCount()); if (self == null) { throw new NullPointerException("this cannot be null"); } if (!self.getClz().isImplements(method.getClz())) { throw new IncompatibleClassChangeError(); } NiMethod finalMethod = MethodRef.lookUpMethods(self.getClz(), methodRef.getName(), methodRef.getDesc()); if (finalMethod == null || finalMethod.isAbstract()) { throw new AbstractMethodError(); } if (!method.isPublic()) { throw new IllegalAccessError(" interface method should be public: " + method); } invokeMethod(frame, finalMethod); } } public static class INVOKE_NATIVE extends NoOperandCmd { @Override public void exec(NiFrame frame) { NiMethod method = frame.getMethod(); INativeMethod nativeMethod = NaMethodManager.findNativeMethod(method); if (nativeMethod == null) { throw new NativeMethodException("cannot found native method: " + method); } nativeMethod.invoke(frame); } } public static class INVOKE_DYNAMIC extends Index16Cmd { private final static String CLZ_METHOD_HANDLE = "java/lang/invoke/MethodHandle"; private final static String CLZ_METHOD_TYPE = "java/lang/invoke.MethodType"; private final static String CLZ_LOOK_UP = "java/lang/invoke/MethodHandles$Lookup"; @Override public void exec(NiFrame frame) { NiConstantPool cps = getCP(frame); NiConstant.NiInvokeDynamic dynamicInfo = (NiConstant.NiInvokeDynamic) cps.get(index); AttributeInfo.BootstrapMethodInfo bootstrapMethodInfo = frame.getMethod().getClz().getBootstrapMethodInfo(dynamicInfo.bmaIndex); NiConstant.NiMethodHandleInfo cp = (NiConstant.NiMethodHandleInfo) cps.get(bootstrapMethodInfo.bmhIndex); NiConstant handle = cps.get(cp.mhIndex); if (handle instanceof MethodRef) { MethodRef ref = (MethodRef) handle; ref.resolve(); NiClassLoader loader = frame.getMethod().getClz().getLoader(); NiMethod method = ref.getMethod(); NiObject caller = getLookUp(frame); NiObject invokedName = NiString.newString(loader, dynamicInfo.name); NiObject invokedType = getMethodType(frame, dynamicInfo.desc); NiObject samMethodType = getMethodType(frame, ((ConstantInfo.CPMethodType) bootstrapMethodInfo.arguments[0]).desc()); NiObject instantiatedMethodType = getMethodType(frame, ((ConstantInfo.CPMethodType) bootstrapMethodInfo.arguments[2]).desc()); ConstantInfo.CPMethodHandleInfo argument = (ConstantInfo.CPMethodHandleInfo) bootstrapMethodInfo.arguments[1]; MethodRef m = (MethodRef) cps.get(argument.getReference()); m.resolve(); NiObject implMethod = getMethodHandle(frame, caller, m.getMethod()); invoke(frame, method, caller, invokedName, invokedType, samMethodType, implMethod, instantiatedMethodType); } } private NiObject getLookUp(NiFrame frame) { NiClassLoader loader = frame.getMethod().getClz().getLoader(); NiClass clzLookUp = loader.loadClass(CLZ_LOOK_UP); NiObject objLookUp = clzLookUp.newObject(); objLookUp.setFieldRef("lookupClass", "Ljava/lang/Class;", frame.getMethod().getClz().getjClass()); objLookUp.setFieldInt("allowedModes", clzLookUp.getStaticInt("ALL_MODES")); return objLookUp; } private NiObject getMethodType(NiFrame frame, String desc) { NiClassLoader loader = frame.getMethod().getClz().getLoader(); int index = desc.indexOf(')'); String paramDesc = desc.substring(1, index); String[] params = VMUtils.toParams(paramDesc); NiObject[] objP = new NiObject[params.length]; for (int i = 0; i < params.length; i++) { objP[i] = loader.loadClass(params[i]).getjClass(); } NiClass clzA = loader.loadClass("[Ljava/lang/Class"); NiObject pClzs = new NiObject(clzA, objP); String ret = desc.substring(index + 1); NiObject rClz = loader.loadClass(VMUtils.toClassname(ret)).getjClass(); NiClassLoader methodType = frame.getMethod().getClz().getLoader(); NiClass clzMethodType = loader.loadClass(CLZ_METHOD_TYPE); NiObject objMethodType = clzMethodType.newObject(); objMethodType.setFieldRef("rtype", "Ljava/lang/Class;", rClz); objMethodType.setFieldRef("ptypes", "[Ljava/lang/Class;", pClzs); return objMethodType; } private NiObject getMethodHandle(NiFrame frame, NiObject lookUp, NiMethod method) { NiClassLoader loader = frame.getMethod().getClz().getLoader(); NiMethod findStatic = lookUp.getClz().getMethod("findStatic", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/MethodHandle;"); Slot ret = NiThread.execMethodDirectly(findStatic, new Slot(lookUp), new Slot(method.getClz().getjClass()), new Slot(NiString.newString(loader, method.getName())), new Slot(getMethodType(frame, method.getDesc()))); return ret.getRef(); } private void invoke(NiFrame frame, NiMethod method, NiObject... params) { NiFrame newFrame = new NiFrame(method); frame.getThread().pushFrame(newFrame); LocalVars slots = newFrame.getLocalVars(); for (int i = 0; i < params.length; i++) { slots.setRef(i, params[i]); } } } public static class ATHROW extends NoOperandCmd { @Override public void exec(NiFrame frame) { NiObject exception = frame.getOperandStack().popRef(); if (exception == null) { throw new NullPointerException("exception is null"); } NiThread thread = frame.getThread(); while (!thread.isEmpty()) { NiFrame topFrame = thread.topFrame(); NiMethod method = topFrame.getMethod(); if (method == null) { NaThrowable.print(exception); return; } int nextPC = method.findExceptionHandler(exception.getClz(), topFrame.getPosition() - 1); if (nextPC > 0) { OperandStack stack = topFrame.getOperandStack(); stack.clear(); stack.pushRef(exception); topFrame.setPosition(nextPC); return; } thread.popFrame(); } if (thread.isEmpty()) { NaThrowable.print(exception); } } } }
package com.sigopt.model; import com.sigopt.net.APIMethodCaller; import com.sigopt.net.PaginatedAPIMethodCaller; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; public class Experiment extends StructObject { public Experiment() { super(); } public Experiment(String id) { super(); this.set("id", id); } public String getId() { return (String) this.get("id"); } public String getType() { return (String) this.get("type"); } public String getName() { return (String) this.get("name"); } public List<Parameter> getParameters() { return Utils.mergeIntoList(new ArrayList<Parameter>(), this.get("parameters"), Parameter.class); } public Metric getMetric() { return Utils.mergeInto(new Metric(), this.get("metric")); } public Progress getProgress() { return Utils.mergeInto(new Progress(), this.get("progress")); } public Metadata getMetadata() { return Utils.mergeInto(new Metadata(), this.get("metadata")); } public String getClient() { return (String) this.get("client"); } public String getState() { return (String) this.get("state"); } public Integer getCreated() { return Utils.asInteger(this.get("created")); } public Integer getObservationBudget() { return Utils.asInteger(this.get("observation_budget")); } public boolean getDevelopment() { return (boolean) this.get("development"); } public static APIMethodCaller<Experiment> fetch() { return new APIMethodCaller<Experiment>("get", "/experiments/:id", Experiment.class); } public static APIMethodCaller<Experiment> fetch(String id) { return Experiment.fetch().addPathComponent("id", id); } public static PaginatedAPIMethodCaller<Experiment> list() { return new PaginatedAPIMethodCaller<Experiment>("get", "/experiments", Experiment.class); } public static APIMethodCaller<Experiment> create() { return new APIMethodCaller<Experiment>("post", "/experiments", Experiment.class); } public static APIMethodCaller<Experiment> create(Experiment e) { return Experiment.create().data(e); } public static APIMethodCaller<Experiment> update() { return new APIMethodCaller<Experiment>("put", "/experiments/:id", Experiment.class); } public static APIMethodCaller<Experiment> update(String id) { return Experiment.update().addPathComponent("id", id); } public static APIMethodCaller<Experiment> update(String id, Experiment e) { return Experiment.update(id).data(e); } public static APIMethodCaller<VoidObject> delete() { return new APIMethodCaller<VoidObject>("delete", "/experiments/:id", VoidObject.class); } public static APIMethodCaller<VoidObject> delete(String id) { return Experiment.delete().addPathComponent("id", id); } public static class Subresource<T extends APIObject> extends BoundObject { String name; Class<T> klass; public Subresource(String prefix, String name, Class<T> klass) { super(prefix); this.name = name; this.klass = klass; } public APIMethodCaller<T> fetch() { return new APIMethodCaller<T>("get", this.prefix() + "/" + this.name + "/:id", klass); } public APIMethodCaller<T> fetch(String id) { return this.fetch().addParam("id", id); } public PaginatedAPIMethodCaller<T> list() { return new PaginatedAPIMethodCaller<T>("get", this.prefix() + "/" + this.name, klass); } public APIMethodCaller<T> create() { return new APIMethodCaller<T>("post", this.prefix() + "/" + this.name, klass); } public APIMethodCaller<T> create(T o) { return this.create().data(o); } public APIMethodCaller<T> update() { return new APIMethodCaller<T>("put", this.prefix() + "/" + this.name + "/:id", klass); } public APIMethodCaller<T> update(String id) { return this.update().addPathComponent("id", id); } public APIMethodCaller<T> update(String id, T o) { return this.update(id).data(o); } public APIMethodCaller<VoidObject> deleteList() { return new APIMethodCaller<VoidObject>("delete", this.prefix() + "/" + this.name, VoidObject.class); } public APIMethodCaller<VoidObject> delete() { return new APIMethodCaller<VoidObject>("delete", this.prefix() + "/" + this.name + "/:id", VoidObject.class); } public APIMethodCaller<VoidObject> delete(String id) { return this.delete().addPathComponent("id", id); } } public Subresource<Observation> observations() { return new Subresource<Observation>("/experiments/" + this.getId(), "observations", Observation.class); } public Subresource<Suggestion> suggestions() { return new Subresource<Suggestion>("/experiments/" + this.getId(), "suggestions", Suggestion.class); } public static class Builder { Experiment e; public Builder() { this.e = new Experiment(); } public Experiment build() { return this.e; } public Builder created(int created) { this.e.set("created", created); return this; } public Builder parameters(List<Parameter> parameters) { this.e.set("parameters", parameters); return this; } public Builder metadata(Map<String, String> metadata) { this.e.set("metadata", metadata); return this; } public Builder metric(Metric metric) { this.e.set("metric", metric); return this; } public Builder progress(Progress progress) { this.e.set("progress", progress); return this; } public Builder client(String client) { this.e.set("client", client); return this; } public Builder id(String id) { this.e.set("id", id); return this; } public Builder name(String name) { this.e.set("name", name); return this; } public Builder state(String state) { this.e.set("state", state); return this; } public Builder type(String type) { this.e.set("type", type); return this; } public Builder observationBudget(int budget) { this.e.set("observation_budget", budget); return this; } public Builder development(boolean development) { this.e.set("development", development); return this; } } }
package com.stratio.specs; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.equalTo; import java.util.List; import com.stratio.specs.BaseGSpec; import com.stratio.specs.CommonG; import cucumber.api.java.en.Then; public class ThenGSpec extends BaseGSpec { public ThenGSpec(CommonG spec) { this.commonspec = spec; } @Then("^an exception '(.*?)' thrown( with class '(.*?)')?") public void assertExceptionNotThrown(String exception, String foo, String clazz) { commonspec.getLogger().info("Verifying thrown exceptions existance"); if ("IS NOT".equals(exception)) { assertThat("Captured exception list is not empty", commonspec.getExceptions(), hasSize(0)); } else { List<Exception> exceptions = commonspec.getExceptions(); assertThat("Unexpected last exception class", exceptions.get(exceptions.size() - 1).getClass().getSimpleName(), equalTo(clazz)); assertThat("Captured exception list is empty", exceptions, not(hasSize(0))); commonspec.getExceptions().clear(); } } }
package com.wepay.net; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.URL; import java.nio.charset.StandardCharsets; import javax.net.ssl.HttpsURLConnection; import org.json.JSONObject; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.wepay.exception.WePayException; import com.wepay.model.data.deserialization.WepayExclusionStrategy; public class WePayResource { public static String apiEndpoint; public static String uiEndpoint; protected final static String STAGE_API_ENDPOINT = "https://stage.wepayapi.com/v2"; protected final static String STAGE_UI_ENDPOINT = "https://stage.wepay.com/v2"; protected final static String PRODUCTION_API_ENDPOINT = "https://wepayapi.com/v2"; protected final static String PRODUCTION_UI_ENDPOINT = "https: public static final Gson gson = new GsonBuilder() .addDeserializationExclusionStrategy(new WepayExclusionStrategy()) .setPrettyPrinting() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); public static void initializeWePayResource(Boolean useStageEnv) { if (useStageEnv) { apiEndpoint = STAGE_API_ENDPOINT; uiEndpoint = STAGE_UI_ENDPOINT; } else { apiEndpoint = PRODUCTION_API_ENDPOINT; uiEndpoint = PRODUCTION_UI_ENDPOINT; } } protected static javax.net.ssl.HttpsURLConnection httpsConnect(String call, String accessToken) throws IOException { URL url = new URL(apiEndpoint + call); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setConnectTimeout(30000); // 30 seconds connection.setReadTimeout(100000); // 100 seconds connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Api-Version", "2016-08-10"); connection.setRequestProperty("User-Agent", "WePay Java SDK v7.1.0"); if (accessToken != null) { connection.setRequestProperty("Authorization", "Bearer " + accessToken); } return connection; } public static String request(String call, JSONObject params, String accessToken) throws WePayException, IOException { HttpsURLConnection connection = httpsConnect(call, accessToken); Writer wr=new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8); wr.write(params.toString()); wr.flush(); wr.close(); boolean error = false; int responseCode = connection.getResponseCode(); InputStream is; if (responseCode >= 200 && responseCode < 300) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); error = true; } BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); } rd.close(); String responseString = response.toString(); if (error) { WePayException ex = WePayResource.gson.fromJson(responseString, WePayException.class); throw ex; } return responseString; } }
package com.yahoo.rdl; import java.util.List; import java.util.Map; import java.util.ArrayList; import java.util.HashMap; /** * A class to assist building Schemas programatically. */ public class SchemaBuilder { Schema schema; public SchemaBuilder(String name) { schema = new Schema().name(name); schema.types = new ArrayList<Type>(); schema.resources = new ArrayList<Resource>(); } public SchemaBuilder namespace(String namespace) { schema.namespace = namespace; return this; } public SchemaBuilder version(int version) { schema.version = version; return this; } public SchemaBuilder comment(String comment) { schema.comment = comment; return this; } public StringTypeBuilder stringType(String tname) { return new StringTypeBuilder(tname); } public NumberTypeBuilder numberType(String tname, String sname) { return new NumberTypeBuilder(tname, sname); } public StructTypeBuilder structType(String tname) { return new StructTypeBuilder(tname, "Struct"); } public StructTypeBuilder structType(String tname, String sname) { return new StructTypeBuilder(tname, sname); } public EnumTypeBuilder enumType(String tname) { return new EnumTypeBuilder(tname); } public UnionTypeBuilder unionType(String tname) { return new UnionTypeBuilder(tname); } public class StructTypeBuilder { StructTypeDef td; StructTypeBuilder(String name, String superName) { td = new StructTypeDef().type(superName).name(name).fields(new ArrayList<StructFieldDef>()); Type t = new Type(td); schema.types.add(t); } public StructTypeBuilder comment(String comment) { td.comment = comment; return this; } public StructTypeBuilder field(String fname, String ftype, boolean optional, String comment) { return field(fname, ftype, optional, comment, null); } public StructTypeBuilder field(String fname, String ftype, boolean optional, String comment, Object _default) { StructFieldDef fd = new StructFieldDef() .name(fname) .type(ftype) .optional(optional) .comment(comment) ._default(_default); td.fields.add(fd); return this; } public StructTypeBuilder arrayField(String fname, String fitems, boolean optional, String comment) { StructFieldDef fd = new StructFieldDef() .name(fname) .type("Array") .items(fitems) .optional(optional) .comment(comment); td.fields.add(fd); return this; } public StructTypeBuilder mapField(String fname, String fkeys, String fitems, boolean optional, String comment) { StructFieldDef fd = new StructFieldDef() .name(fname) .type("Map") .keys(fkeys) .items(fitems) .optional(optional) .comment(comment); td.fields.add(fd); return this; } } public class EnumTypeBuilder { EnumTypeDef td; EnumTypeBuilder(String name) { td = new EnumTypeDef().type("Enum").name(name).elements(new ArrayList<EnumElementDef>()); Type t = new Type(td); schema.types.add(t); } public EnumTypeBuilder comment(String comment) { td.comment = comment; return this; } public EnumTypeBuilder element(String sym) { return element(sym, null); } public EnumTypeBuilder element(String sym, String comment) { EnumElementDef ed = new EnumElementDef().symbol(sym); if (comment != null) { ed.comment(comment); } td.elements.add(ed); return this; } } public class UnionTypeBuilder { UnionTypeDef td; UnionTypeBuilder(String name) { td = new UnionTypeDef().type("Union").name(name).variants(new ArrayList<String>()); Type t = new Type(td); schema.types.add(t); } public UnionTypeBuilder comment(String comment) { td.comment = comment; return this; } public UnionTypeBuilder variant(String variant) { td.variants.add(variant); return this; } } public class StringTypeBuilder { StringTypeDef td; StringTypeBuilder(String name) { td = new StringTypeDef().type("String").name(name); Type t = new Type(td); schema.types.add(t); } public StringTypeBuilder comment(String comment) { td.comment = comment; return this; } public StringTypeBuilder pattern(String pattern) { td.pattern = pattern; return this; } public StringTypeBuilder maxSize(int size) { td.maxSize = size; return this; } //to do: minSize, values, annotations } public class NumberTypeBuilder { NumberTypeDef td; NumberTypeBuilder(String name, String supername) { td = new NumberTypeDef().type(supername).name(name); Type t = new Type(td); schema.types.add(t); } public NumberTypeBuilder comment(String comment) { td.comment = comment; return this; } public NumberTypeBuilder min(int min) { td.min = new Number(min); return this; } public NumberTypeBuilder min(long min) { td.min = new Number(min); return this; } public NumberTypeBuilder min(double min) { td.min = new Number(min); return this; } public NumberTypeBuilder max(int max) { td.max = new Number(max); return this; } public NumberTypeBuilder max(long max) { td.max = new Number(max); return this; } public NumberTypeBuilder max(double max) { td.max = new Number(max); return this; } } public ResourceBuilder resource(String rtype, String rmethod, String rpath) { return new ResourceBuilder(rtype, rmethod, rpath); } public class ResourceBuilder { Resource rez; ResourceBuilder(String rtype, String rmethod, String rpath) { rez = new Resource().type(rtype).method(rmethod).path(rpath); schema.resources.add(rez); } public ResourceBuilder comment(String comment) { rez.comment = comment; return this; } public ResourceBuilder name(String name) { rez.name = name; return this; } private ResourceInput addInput(String iname, String itype, String comment) { ResourceInput in = new ResourceInput() .name(iname) .type(itype); if (comment != null && comment.length() > 0) { in.comment(comment); } if (rez.inputs == null) { rez.inputs = new ArrayList<ResourceInput>(); } rez.inputs.add(in); return in; } public ResourceBuilder input(String iname, String itype, String comment) { addInput(iname, itype, comment); return this; } public ResourceBuilder pathParam(String iname, String itype, String comment) { ResourceInput in = addInput(iname, itype, comment); in.pathParam(true); return this; } public ResourceBuilder queryParam(String iparam, String iname, String itype, Object _default, String comment) { ResourceInput in = addInput(iname, itype, comment); in.queryParam(iparam); if (_default != null) { in._default(_default); } else { in.optional(true); } return this; } public ResourceBuilder headerParam(String iparam, String iname, String itype, Object _default, String comment) { ResourceInput in = addInput(iname, itype, comment); in.header(iparam); in.optional(true); if (_default != null) { in._default(_default); } else { in.optional(true); } return this; } public ResourceBuilder output(String header, String name, String type, String comment) { ResourceOutput out = new ResourceOutput() .header(header) .name(name) .type(type); if (comment != null && comment.length() > 0) { out.comment(comment); } if (rez.outputs == null) { rez.outputs = new ArrayList<ResourceOutput>(); } rez.outputs.add(out); return this; } public ResourceBuilder auth(String action, String resource) { return auth(action, resource, false); } public ResourceBuilder auth(String action, String resource, boolean authenticate) { return auth(action, resource, authenticate, null); } public ResourceBuilder auth(String action, String resource, boolean authenticate, String domain) { ResourceAuth auth = new ResourceAuth() .action(action) .resource(resource) .authenticate(authenticate); if (domain != null && domain.length() > 0) { auth.domain(domain); } rez.auth = auth; return this; } public ResourceBuilder expected(String sym) { rez.expected = sym; return this; } public ResourceBuilder exception(String sym, String type, String comment) { ExceptionDef exc = new ExceptionDef().type(type); if (comment != null && comment.length() > 0) { exc.comment(comment); } if (rez.exceptions == null) { rez.exceptions = new HashMap<String, ExceptionDef>(); } rez.exceptions.put(sym, exc); return this; } public ResourceBuilder async() { rez.async = true; return this; } } public Schema build() { if (schema.types != null && schema.types.size() == 0) { schema.types = null; } if (schema.resources != null && schema.resources.size() == 0) { schema.resources = null; } return schema; } }
package common.base.utils; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.DrawableRes; import android.support.annotation.Nullable; import android.support.annotation.RawRes; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.RequestBuilder; import com.bumptech.glide.load.DataSource; import com.bumptech.glide.load.engine.GlideException; import com.bumptech.glide.load.resource.gif.GifDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.RequestOptions; import com.bumptech.glide.request.target.Target; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class ImageUtil { // public static void loadImage(Context context, String picUrl, int newWidth, int newHeight, Drawable holderDrawable, // Drawable errorDrawable, ImageView targetIv // , Callback callback) { // RequestCreator loadRequest = loadImageRequest(context, picUrl,null,0); // if (newWidth > 0 && newHeight > 0) { // loadRequest.resize(newWidth, newHeight); // loadRequest.centerCrop(); // else{ //// loadRequest.fit(); // if (holderDrawable != null) { // loadRequest.placeholder(holderDrawable); // else{ // loadRequest.noPlaceholder(); // if (errorDrawable != null) { // loadRequest.error(errorDrawable); // loadRequest.noFade(); // loadRequest.into(targetIv, callback); public static void loadImage(Context context, String picUrl, int newWidth, int newHeight, Drawable holderDrawable, Drawable errorDrawable, ImageView targetIv , RequestListener callback) { RequestBuilder requestBuilder = loadImageRequest(context, picUrl); RequestOptions options = new RequestOptions(); if (newWidth > 0 && newHeight > 0) { options.override(newWidth,newHeight).centerCrop(); } else{ // loadRequest.fit(); } if (holderDrawable != null) { options.placeholder(holderDrawable); } else{ // loadRequest.noPlaceholder(); } if (errorDrawable != null) { options.error(errorDrawable); } options.dontAnimate(); if (callback != null) { requestBuilder.listener(callback); } requestBuilder.apply(options) .into(targetIv); } private static void throwCannotException(String reason) { throw new IllegalArgumentException("no " + reason + ",can't loca image pic..."); } // private static RequestCreator loadImageRequest(Context context, String picUrl, File localPicFile,int localPicResId) { // if (Util.isEmpty(picUrl) && null == localPicFile && localPicResId <= 0) { // throwCannotException("pic path "); // Picasso picasso = Picasso.with(context); // if (!Util.isEmpty(picUrl)) { // return picasso.load(picUrl); // if (localPicFile != null) { // return picasso.load(localPicFile); // return picasso.load(localPicResId); // public static RequestCreator loadImageRequest(Context context, String picUrlOrPath) { // if (Util.isEmpty(picUrlOrPath)) { // throwCannotException("picUrl"); // return loadImageRequest(context, picUrlOrPath, null, 0); // public static RequestCreator loadImageRequest(Context context, File localPicFile) { // if (null == localPicFile) { // throwCannotException("pic file"); // return loadImageRequest(context, null, localPicFile, 0); // public static RequestCreator loadImageRequest(Context context, int localPicResId) { // if (localPicResId <= 0) { // throwCannotException("valid local pic res id"); // return loadImageRequest(context, null, null, localPicResId); public static void loadImage(Context context, String picUrl, int newWidth, int newHeight, int holderDrawableResId, int errorDrawableResId, ImageView targetIv , RequestListener callback){ Resources res = context.getResources(); Drawable holderPic = null; if (holderDrawableResId > 0) { holderPic = res.getDrawable(holderDrawableResId); } Drawable errorDrawable = null; if (errorDrawableResId > 0) { errorDrawable = res.getDrawable(errorDrawableResId); } loadImage(context, picUrl, newWidth, newHeight,holderPic, errorDrawable, targetIv, callback); } public static void loadImage(Context context,String picUrl,int holderDrawableResId, int errorDrawableResId, ImageView targetIv , RequestListener callback){ loadImage(context,picUrl,0,0,holderDrawableResId,errorDrawableResId,targetIv,callback); } public static void loadImage(Context context, String picUrl, int holderDrawableResId, int errorDrawableResId, ImageView targetIv) { loadImage(context,picUrl,holderDrawableResId,errorDrawableResId,targetIv,null); } public static void loadImage(Context context, String picUrl, ImageView targetIv, RequestListener callback) { loadImage(context, picUrl, 0, 0, targetIv, callback); } public static void loadImage(Context context, String picUrl, ImageView targetIv) { loadImage(context, picUrl, targetIv,null); } public static void loadResizeImage(Context context, String picUrl, int resizeW, int resizeH, ImageView targetIv) { loadImage(context, picUrl, resizeW, resizeH, null, null, targetIv, null); } public static void loadImage(Context context, Object model) { Glide.with(context).load(model); } public static RequestBuilder<Drawable> loadImageRequest(Context context, Object model) { return Glide.with(context).load(model); } public static RequestBuilder<Bitmap> loadBitmapeRequest(Context context, Object model) { return Glide.with(context).asBitmap().load(model); } public static void loadBitmap(Context context, Object model, Target target) { Glide.with(context).asBitmap().load(model).into(target); } public static void loadGif(Context context, int gifDrawableResId, ImageView ivTarget, int needPlayTime) { loadGifModel(context, gifDrawableResId,0, ivTarget, needPlayTime); } public static void loadGifModel(Context context, Object mayBeGifModel, @RawRes @DrawableRes int defHolderPicRes, ImageView ivTarget, final int needPlayTime) { if (mayBeGifModel == null) { return; } RequestBuilder<GifDrawable> gifDrawableBuilder = Glide.with(context).asGif() ; if (defHolderPicRes != 0) { gifDrawableBuilder.placeholder(defHolderPicRes) .error(defHolderPicRes); } RequestListener<GifDrawable> loadGifDrawableListener = null; if (needPlayTime >= 1) { loadGifDrawableListener = new RequestListener<GifDrawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) { return false; } @Override public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) { resource.setLoopCount(needPlayTime); return false; } }; gifDrawableBuilder.listener(loadGifDrawableListener); } if (mayBeGifModel instanceof Integer) {//:load(Bitmap xx);load(byte[]xxx);loadDrawable(Drawable xx); Integer gifResId = (Integer) mayBeGifModel; if (gifResId != 0) { gifDrawableBuilder.load(gifResId); } else { return; } } else{ gifDrawableBuilder.load(mayBeGifModel); } gifDrawableBuilder.into(ivTarget); } public static ColorDrawable createDefHolderColorDrawable(int theColor) { if (theColor <= 0) { theColor = Color.parseColor("#555555"); } return new ColorDrawable(theColor); } //and so on public static final int BLUR_RADIUS = 50; @Nullable public static Bitmap blur(Bitmap sentBitmap) { try { return blur(sentBitmap, BLUR_RADIUS); } catch (Exception e) { e.printStackTrace(); } return null; } private static Bitmap blur(Bitmap sentBitmap, int radius) { Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true); if (radius < 1) { return null; } int w = bitmap.getWidth(); int h = bitmap.getHeight(); int[] pix = new int[w * h]; bitmap.getPixels(pix, 0, w, 0, 0, w, h); int wm = w - 1; int hm = h - 1; int wh = w * h; int div = radius + radius + 1; int r[] = new int[wh]; int g[] = new int[wh]; int b[] = new int[wh]; int rsum, gsum, bsum, x, y, i, p, yp, yi, yw; int vmin[] = new int[Math.max(w, h)]; int divsum = (div + 1) >> 1; divsum *= divsum; int dv[] = new int[256 * divsum]; for (i = 0; i < 256 * divsum; i++) { dv[i] = (i / divsum); } yw = yi = 0; int[][] stack = new int[div][3]; int stackpointer; int stackstart; int[] sir; int rbs; int r1 = radius + 1; int routsum, goutsum, boutsum; int rinsum, ginsum, binsum; for (y = 0; y < h; y++) { rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0; for (i = -radius; i <= radius; i++) { p = pix[yi + Math.min(wm, Math.max(i, 0))]; sir = stack[i + radius]; sir[0] = (p & 0xff0000) >> 16; sir[1] = (p & 0x00ff00) >> 8; sir[2] = (p & 0x0000ff); rbs = r1 - Math.abs(i); rsum += sir[0] * rbs; gsum += sir[1] * rbs; bsum += sir[2] * rbs; if (i > 0) { rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; } else { routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; } } stackpointer = radius; for (x = 0; x < w; x++) { r[yi] = dv[rsum]; g[yi] = dv[gsum]; b[yi] = dv[bsum]; rsum -= routsum; gsum -= goutsum; bsum -= boutsum; stackstart = stackpointer - radius + div; sir = stack[stackstart % div]; routsum -= sir[0]; goutsum -= sir[1]; boutsum -= sir[2]; if (y == 0) { vmin[x] = Math.min(x + radius + 1, wm); } p = pix[yw + vmin[x]]; sir[0] = (p & 0xff0000) >> 16; sir[1] = (p & 0x00ff00) >> 8; sir[2] = (p & 0x0000ff); rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; rsum += rinsum; gsum += ginsum; bsum += binsum; stackpointer = (stackpointer + 1) % div; sir = stack[(stackpointer) % div]; routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; rinsum -= sir[0]; ginsum -= sir[1]; binsum -= sir[2]; yi++; } yw += w; } for (x = 0; x < w; x++) { rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0; yp = -radius * w; for (i = -radius; i <= radius; i++) { yi = Math.max(0, yp) + x; sir = stack[i + radius]; sir[0] = r[yi]; sir[1] = g[yi]; sir[2] = b[yi]; rbs = r1 - Math.abs(i); rsum += r[yi] * rbs; gsum += g[yi] * rbs; bsum += b[yi] * rbs; if (i > 0) { rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; } else { routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; } if (i < hm) { yp += w; } } yi = x; stackpointer = radius; for (y = 0; y < h; y++) { // Preserve alpha channel: ( 0xff000000 & pix[yi] ) pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum]; rsum -= routsum; gsum -= goutsum; bsum -= boutsum; stackstart = stackpointer - radius + div; sir = stack[stackstart % div]; routsum -= sir[0]; goutsum -= sir[1]; boutsum -= sir[2]; if (x == 0) { vmin[y] = Math.min(y + r1, hm) * w; } p = x + vmin[y]; sir[0] = r[p]; sir[1] = g[p]; sir[2] = b[p]; rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; rsum += rinsum; gsum += ginsum; bsum += binsum; stackpointer = (stackpointer + 1) % div; sir = stack[stackpointer]; routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; rinsum -= sir[0]; ginsum -= sir[1]; binsum -= sir[2]; yi += w; } } bitmap.setPixels(pix, 0, w, 0, 0, w, h); return bitmap; } public static Bitmap resizeImage(Bitmap source, int w, int h) { int width = source.getWidth(); int height = source.getHeight(); float scaleWidth = ((float) w) / width; float scaleHeight = ((float) h) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); return Bitmap.createBitmap(source, 0, 0, width, height, matrix, true); } public static Bitmap createCircleImage(Bitmap source) { int length = Math.min(source.getWidth(), source.getHeight()); Paint paint = new Paint(); paint.setAntiAlias(true); Bitmap target = Bitmap.createBitmap(length, length, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(target); canvas.drawCircle(length / 2, length / 2, length / 2, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(source, 0, 0, paint); return target; } // /** // * Glide // * // * @param context Context // * @param fileUrl // * @param targetLocalFilePath // * @return file // */ // private static File download(Context context, String fileUrl,String targetLocalFilePath) { // if (fileUrl == null || "".equals(fileUrl.trim())) { // return null; // File targetFile = null; // try { // targetFile = Glide.with(context).download(fileUrl).submit().get(); // } catch (Exception e) { // e.printStackTrace(); // if (targetLocalFilePath != null && !"".equals(targetLocalFilePath.trim())) {// // boolean isValidFile = targetFile != null && targetFile.length() > 1; // if (isValidFile) { // String downloadFileAbsPath = targetFile.getAbsolutePath(); // if (!targetLocalFilePath.equals(downloadFileAbsPath)) {// // File targetLocalFile = new File(targetLocalFilePath); // boolean needCopyToTargetPath = true; // boolean copySuc = copyFile(targetFile, targetLocalFile); // if (copySuc) { // targetFile.delete(); // targetFile = targetLocalFile; // return targetFile; public static boolean copyFile(File srcFile, File targetFile) { if (srcFile == null || srcFile.length() < 1 || targetFile == null) { return false; } FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(targetFile, true); byte[] readBuf = new byte[1024]; int hasReadLen = -1; while ((hasReadLen = fis.read(readBuf)) != -1) { byte[] readDatas = new byte[hasReadLen]; System.arraycopy(readBuf, 0, readDatas, 0, hasReadLen); fos.write(readDatas); } fos.flush(); return true; } catch (Exception e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; } public static File downloadAndCopyToTarget(Context context, String fileUrl, String targetDirPath, String targetFileName, boolean deleteSrcFile) { File downloadResultFile = download(context, fileUrl); if (downloadResultFile == null) { return null; } boolean isTargetDirNull = isTextEmpty(targetDirPath); boolean isTargetFileNameNull = isTextEmpty(targetFileName); if (!isTargetDirNull) { boolean isDownloadFileValid = downloadResultFile.length() > 1; if (isDownloadFileValid) { String downloadedFileName = downloadResultFile.getName(); CommonLog.e("info", "-->downloadAndCopyToTarget() downloadedFileName = " + downloadedFileName); String targetWholeFilePath = appendSeparator(targetDirPath); File targetFile = null; if (isTargetFileNameNull) { targetWholeFilePath += downloadedFileName; targetFile = new File(targetWholeFilePath); if (targetFile.exists() && targetFile.length() > 1) { CommonLog.e("info", "-->downloadAndCopyToTarget() not need copy file..."); return targetFile; } } else{ targetWholeFilePath += targetFileName; } targetFile = new File(targetWholeFilePath); boolean isCopySuc = copyFile(downloadResultFile, targetFile); if (isCopySuc) { if (deleteSrcFile) { downloadResultFile.delete(); } downloadResultFile = targetFile; } } } return downloadResultFile; } public static File download(Context context, String fileUrl) { if (fileUrl == null || "".equals(fileUrl.trim())) { return null; } File targetFile = null; try { targetFile = Glide.with(context).download(fileUrl).submit().get(); } catch (Exception e) { e.printStackTrace(); } return targetFile; } private static boolean isTextEmpty(String text) { if (text == null || text.trim().length() == 0) { return true; } return false; } private static String appendSeparator(String text) { if (!isTextEmpty(text)) { if (!text.endsWith("/")) { return text + "/"; } } return text; } }
package cronapi.database; import java.lang.reflect.Method; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Vector; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.Type; import org.eclipse.persistence.annotations.Multitenant; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.descriptors.DescriptorQueryManager; import org.eclipse.persistence.internal.jpa.EJBQueryImpl; import org.eclipse.persistence.internal.jpa.EntityManagerImpl; import org.eclipse.persistence.internal.jpa.metamodel.EntityTypeImpl; import org.eclipse.persistence.internal.sessions.AbstractSession; import org.eclipse.persistence.queries.DatabaseQuery; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.security.core.GrantedAuthority; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializable; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.google.gson.JsonObject; import cronapi.*; import cronapi.cloud.CloudFactory; import cronapi.cloud.CloudManager; import cronapi.i18n.Messages; import cronapi.rest.security.CronappSecurity; /** * Class database manipulation, responsible for querying, inserting, * updating and deleting database data procedurally, allowing paged * navigation and setting page size. * * @author robson.ataide * @version 1.0 * @since 2017-04-26 * */ public class DataSource implements JsonSerializable { private String entity; private String simpleEntity; private Class domainClass; private String filter; private Var[] params; private int pageSize; private Page page; private int index; private int current; private Pageable pageRequest; private Object insertedElement = null; private EntityManager customEntityManager; private DataSourceFilter dsFilter; private boolean multiTenant = true; /** * Init a datasource with a page size equals 100 * * @param entity * - full name of entitiy class like String */ public DataSource(String entity) { this(entity, 100); } public DataSource(JsonObject query) { this(query.get("entityFullName").getAsString(), 100); QueryManager.checkMultiTenant(query, this); } /** * Init a datasource with a page size equals 100, and custom entity manager * * @param entity * - full name of entitiy class like String * @param entityManager * - custom entity manager */ public DataSource(String entity, EntityManager entityManager) { this(entity, 100); this.customEntityManager = entityManager; } /** * Init a datasource setting a page size * * @param entity * - full name of entitiy class like String * @param pageSize * - page size of a Pageable object retrieved from repository */ public DataSource(String entity, int pageSize) { CronappDescriptorQueryManager.enableMultitenant(); this.entity = entity; this.simpleEntity = entity.substring(entity.lastIndexOf(".") + 1); this.pageSize = pageSize; this.pageRequest = new PageRequest(0, pageSize); // initialize dependencies and necessaries objects this.instantiateRepository(); } private EntityManager getEntityManager(Class domainClass) { EntityManager em; if(customEntityManager != null) em = customEntityManager; else em = TransactionManager.getEntityManager(domainClass); enableTenantToogle(em); return em; } public Class getDomainClass() { return domainClass; } public String getSimpleEntity() { return simpleEntity; } public String getEntity() { return entity; } /** * Retrieve repository from entity * * @throws RuntimeException * when repository not fount, entity passed not found or cast repository */ private void instantiateRepository() { try { domainClass = Class.forName(this.entity); } catch(ClassNotFoundException cnfex) { throw new RuntimeException(cnfex); } } private List<String> parseParams(String SQL) { final String delims = " \n\r\t.(){},+:=!"; final String quots = "\'"; String token = ""; boolean isQuoted = false; List<String> tokens = new LinkedList<>(); for(int i = 0; i < SQL.length(); i++) { if(quots.indexOf(SQL.charAt(i)) != -1) { isQuoted = token.length() == 0; } if(delims.indexOf(SQL.charAt(i)) == -1 || isQuoted) { token += SQL.charAt(i); } else { if(token.length() > 0) { if(token.startsWith(":")) tokens.add(token.substring(1)); token = ""; isQuoted = false; } if(SQL.charAt(i) == ':') { token = ":"; } } } if(token.length() > 0) { if(token.startsWith(":")) tokens.add(token.substring(1)); } return tokens; } private void enableTenantToogle(EntityManager em) { try { for(EntityType type : em.getMetamodel().getEntities()) { DescriptorQueryManager old = ((EntityTypeImpl)type).getDescriptor().getQueryManager(); ClassDescriptor desc = ((EntityTypeImpl)type).getDescriptor(); if (desc.getMultitenantPolicy() != null && !(desc.getMultitenantPolicy() instanceof CronappMultitenantPolicy)) { desc.setMultitenantPolicy(new CronappMultitenantPolicy(desc.getMultitenantPolicy())); } if(CronappDescriptorQueryManager.needProxy(old)) { desc.setQueryManager(CronappDescriptorQueryManager.build(old)); } } } catch(Exception e) { throw new RuntimeException(e); } } private void startMultitenant(EntityManager em) { if (!multiTenant) { CronappDescriptorQueryManager.disableMultitenant(); } } private void endMultitetant() { if (!multiTenant) { CronappDescriptorQueryManager.enableMultitenant(); } } /** * Retrieve objects from database using repository when filter is null or empty, * if filter not null or is not empty, this method uses entityManager and create a * jpql instruction. * * @return a array of Object */ public Object[] fetch() { String jpql = this.filter; Var[] params = this.params; if(jpql == null) { jpql = "select e from " + simpleEntity + " e"; } boolean containsNoTenant = jpql.contains("/*notenant*/"); jpql = jpql.replace("/*notenant*/", ""); if (containsNoTenant) { multiTenant = false; } if(dsFilter != null) { dsFilter.applyTo(domainClass, jpql, params); params = dsFilter.getAppliedParams(); jpql = dsFilter.getAppliedJpql(); } try { EntityManager em = getEntityManager(domainClass); startMultitenant(em); AbstractSession session = (AbstractSession)((EntityManagerImpl) em.getDelegate()).getActiveSession(); DatabaseQuery dbQuery = EJBQueryImpl.buildEJBQLDatabaseQuery("customQuery", jpql, session, (Enum)null, (Map)null, session.getDatasourcePlatform().getConversionManager().getLoader()); TypedQuery<?> query = new EJBQueryImpl(dbQuery, (EntityManagerImpl) em.getDelegate()); int i = 0; List<String> parsedParams = parseParams(jpql); for(String param : parsedParams) { Var p = null; if(i <= params.length - 1) { p = params[i]; } if(p != null) { if(p.getId() != null) { query.setParameter(p.getId(), p.getObject(query.getParameter(p.getId()).getParameterType())); } else { query.setParameter(param, p.getObject(query.getParameter(parsedParams.get(i)).getParameterType())); } } else { query.setParameter(param, null); } i++; } if (this.pageRequest != null) { query.setFirstResult(this.pageRequest.getPageNumber() * this.pageRequest.getPageSize()); query.setMaxResults(this.pageRequest.getPageSize()); } List<?> resultsInPage = query.getResultList(); this.page = new PageImpl(resultsInPage, this.pageRequest, 0); } catch(Exception ex) { throw new RuntimeException(ex); } finally { enableMultiTenant(); } // has data, moves cursor to first position if(this.page.getNumberOfElements() > 0) this.current = 0; return this.page.getContent().toArray(); } public EntityMetadata getMetadata() { return new EntityMetadata(domainClass); } /** * Create a new instance of entity and add a * results and set current (index) for his position */ public void insert() { try { this.insertedElement = this.domainClass.newInstance(); } catch(Exception ex) { throw new RuntimeException(ex); } } public Object toObject(Map<?, ?> values) { try { Object insertedElement = this.domainClass.newInstance(); for(Object key : values.keySet()) { updateField(insertedElement, key.toString(), values.get(key)); } return insertedElement; } catch(Exception ex) { throw new RuntimeException(ex); } } public void insert(Object value) { try { if(value instanceof Map) { this.insertedElement = this.domainClass.newInstance(); Map<?, ?> values = (Map<?, ?>)value; for(Object key : values.keySet()) { try { updateField(key.toString(), values.get(key)); } catch(Exception e) { } } } else { this.insertedElement = value; } } catch(Exception ex) { throw new RuntimeException(ex); } } public Object save() { return save(true); } private void processCloudFields(Object toSaveParam) { Object toSave; if (toSaveParam != null) toSave = toSaveParam; else if(this.insertedElement != null) toSave = this.insertedElement; else toSave = this.getObject(); List<String> fieldsAnnotationCloud = Utils.getFieldsWithAnnotationCloud(toSave, "dropbox"); List<String> fieldsIds = Utils.getFieldsWithAnnotationId(toSave); if (fieldsAnnotationCloud.size() > 0) { String dropAppAccessToken = Utils.getAnnotationCloud(toSave, fieldsAnnotationCloud.get(0)).value(); CloudManager cloudManager = CloudManager.newInstance().byID(fieldsIds.toArray(new String[0])).toFields(fieldsAnnotationCloud.toArray(new String[0])); CloudFactory factory = cloudManager.byEntity(toSave).build(); factory.dropbox(dropAppAccessToken).upload(); factory.getFiles().forEach(f-> { updateField(toSave, f.getFieldReference(), f.getFileDirectUrl()); }); } } /** * Saves the object in the current index or a new object when has insertedElement */ public Object save(boolean returnCursorAfterInsert) { try { processCloudFields(null); Object toSave; Object saved; EntityManager em = getEntityManager(domainClass); try { startMultitenant(em); if (!em.getTransaction().isActive()) { em.getTransaction().begin(); } if (this.insertedElement != null) { toSave = this.insertedElement; if (returnCursorAfterInsert) this.insertedElement = null; em.persist(toSave); } else toSave = this.getObject(); saved = em.merge(toSave); if (toSave.getClass().getAnnotation(Multitenant.class) != null) { em.flush(); if (multiTenant) { em.refresh(toSave); } } } finally { endMultitetant(); } return saved; } catch(Exception e) { throw new RuntimeException(e); } } public void delete(Var[] primaryKeys) { insert(); int i = 0; Var[] params = new Var[primaryKeys.length]; EntityManager em = getEntityManager(domainClass); EntityType type = em.getMetamodel().entity(domainClass); String jpql = " DELETE FROM " + entity.substring(entity.lastIndexOf(".") + 1) + " WHERE "; List<TypeKey> keys = getKeys(type); for(TypeKey key : keys) { jpql += "" + key.name + " = :p" + i; params[i] = Var.valueOf("p" + i, primaryKeys[i].getObject(key.field.getType().getJavaType())); i++; } execute(jpql, params); } /** * Removes the object in the current index */ public void delete() { EntityManager em = getEntityManager(domainClass); try { Object toRemove = this.getObject(); startMultitenant(em); if(!em.getTransaction().isActive()) { em.getTransaction().begin(); } // returns managed instance toRemove = em.merge(toRemove); em.remove(toRemove); if (!multiTenant) { em.flush(); } } catch(Exception e) { throw new RuntimeException(e); } finally { endMultitetant(); } } /** * Update a field from object in the current index * * @param fieldName * - attributte name in entity * @param fieldValue * - value that replaced or inserted in field name passed */ public void updateField(String fieldName, Object fieldValue) { updateField(getObject(), fieldName, fieldValue); } private void updateField(Object obj, String fieldName, Object fieldValue) { try { boolean update = true; if(RestClient.getRestClient().isFilteredEnabled()) { update = SecurityBeanFilter.includeProperty(obj.getClass(), fieldName, null); } if(update) { Method setMethod = Utils.findMethod(obj, "set" + fieldName); if(setMethod != null) { if(fieldValue instanceof Var) { fieldValue = ((Var)fieldValue).getObject(setMethod.getParameterTypes()[0]); } else { Var tVar = Var.valueOf(fieldValue); fieldValue = tVar.getObject(setMethod.getParameterTypes()[0]); } setMethod.invoke(obj, fieldValue); } else { throw new RuntimeException("Field " + fieldName + " not found"); } } } catch(Exception ex) { throw new RuntimeException(ex); } } /** * Update fields from object in the current index * * @param fields * - bidimensional array like fields * sample: { {"name", "Paul"}, {"age", "21"} } * * @thows RuntimeException if a field is not accessible through a set method */ public void updateFields(Var ... fields) { for(Var field : fields) { updateField(field.getId(), field.getObject()); } } public void filter(Var data, Var[] extraParams) { EntityManager em = getEntityManager(domainClass); EntityType type = em.getMetamodel().entity(domainClass); int i = 0; String jpql = " select e FROM " + entity.substring(entity.lastIndexOf(".") + 1) + " e WHERE "; Vector<Var> params = new Vector<>(); for(Object obj : type.getAttributes()) { SingularAttribute field = (SingularAttribute)obj; if(field.isId()) { if(i > 0) { jpql += " AND "; } jpql += "e." + field.getName() + " = :p" + i; params.add(Var.valueOf("p" + i, data.getField(field.getName()).getObject(field.getType().getJavaType()))); i++; } } if(extraParams != null) { for(Var p : extraParams) { jpql += "e." + p.getId() + " = :p" + i; params.add(Var.valueOf("p" + i, p.getObject())); i++; } } Var[] arr = params.toArray(new Var[params.size()]); filter(jpql, arr); } public void update(Var data) { try { List<String> fieldsByteHeaderSignature = cronapi.Utils.getFieldsWithAnnotationByteHeaderSignature(domainClass); LinkedList<String> fields = data.keySet(); for(String key : fields) { if (!fieldsByteHeaderSignature.contains(key) || isFieldByteWithoutHeader(key, data.getField(key))) { if(!key.equalsIgnoreCase(Class.class.getSimpleName())) { try { this.updateField(key, data.getField(key)); } catch (Exception e) { //NoCommand } } } } } catch(Exception e) { throw new RuntimeException(e); } } private boolean isFieldByteWithoutHeader(String fieldName, Object fieldValue) { boolean result = false; if(fieldValue instanceof Var) { if (((Var)fieldValue).getObject() == null) return true; else if (cronapi.util.StorageService.isTempFileJson(((Var)fieldValue).getObject().toString())) return true; } Method setMethod = Utils.findMethod(getObject(), "set" + fieldName); if (setMethod!=null) { if(fieldValue instanceof Var) { fieldValue = ((Var)fieldValue).getObject(setMethod.getParameterTypes()[0]); } else { Var tVar = Var.valueOf(fieldValue); fieldValue = tVar.getObject(setMethod.getParameterTypes()[0]); } Object header = cronapi.util.StorageService.getFileBytesMetadata((byte[])fieldValue); result = (header == null); } return result; } /** * Return object in current index * * @return Object from database in current position */ public Object getObject() { if(this.insertedElement != null) return this.insertedElement; if(this.current < 0 || this.current > this.page.getContent().size() - 1) return null; return this.page.getContent().get(this.current); } /** * Return field passed from object in current index * * @return Object value of field passed * @thows RuntimeException if a field is not accessible through a set method */ public Object getObject(String fieldName) { try { Method getMethod = Utils.findMethod(getObject(), "get" + fieldName); if(getMethod != null) return getMethod.invoke(getObject()); return null; } catch(Exception ex) { throw new RuntimeException(ex); } } /** * Moves the index for next position, in pageable case, * looking for next page and so on */ public void next() { if(this.page.getNumberOfElements() > (this.current + 1)) this.current++; else { if(this.page.hasNext()) { this.pageRequest = this.page.nextPageable(); this.fetch(); this.current = 0; } else { this.current = -1; } } } /** * Moves the index for next position, in pageable case, * looking for next page and so on */ public void nextOnPage() { this.current++; } /** * Verify if can moves the index for next position, * in pageable case, looking for next page and so on * * @return boolean true if has next, false else */ public boolean hasNext() { if(this.page.getNumberOfElements() > (this.current + 1)) return true; else { if(this.page.hasNext()) { return true; } else { return false; } } } public boolean hasData() { return getObject() != null; } /** * Moves the index for previous position, in pageable case, * looking for next page and so on * * @return boolean true if has previous, false else */ public boolean previous() { if(this.current - 1 >= 0) { this.current } else { if(this.page.hasPrevious()) { this.pageRequest = this.page.previousPageable(); this.fetch(); this.current = this.page.getNumberOfElements() - 1; } else { return false; } } return true; } public void setCurrent(int current) { this.current = current; } public int getCurrent() { return this.current; } /** * Gets a Pageable object retrieved from repository * * @return pageable from repository, returns null when fetched by filter */ public Page getPage() { return this.page; } /** * Create a new page request with size passed * * @param pageSize * size of page request */ public void setPageSize(int pageSize) { this.pageSize = pageSize; this.pageRequest = new PageRequest(0, pageSize); this.current = -1; } /** * Fetch objects from database by a filter * * @param filter * jpql instruction like a namedQuery * @param params * parameters used in jpql instruction */ public void filter(String filter, Var ... params) { this.filter = filter; this.params = params; this.pageRequest = new PageRequest(0, pageSize); this.current = -1; this.fetch(); } public void setDataSourceFilter(DataSourceFilter dsFilter) { this.dsFilter = dsFilter; } public void filter(String filter, PageRequest pageRequest, Var ... params) { if(filter == null) { if(params.length > 0) { EntityManager em = getEntityManager(domainClass); EntityType type = em.getMetamodel().entity(domainClass); int i = 0; String jpql = "Select e from " + simpleEntity + " e where ("; for(Object obj : type.getAttributes()) { SingularAttribute field = (SingularAttribute)obj; if(field.isId()) { if(i > 0) { jpql += " and "; } jpql += "e." + field.getName() + " = :p" + i; params[i].setId("p" + i); } } jpql += ")"; filter = jpql; } else { filter = "Select e from " + simpleEntity + " e "; } } this.params = params; this.filter = filter; this.pageRequest = pageRequest; this.current = -1; this.fetch(); } private Class forName(String name) { try { return Class.forName(name); } catch(ClassNotFoundException e) { return null; } } private Object newInstance(String name) { try { return Class.forName(name).newInstance(); } catch(Exception e) { return null; } } private static class TypeKey { String name; SingularAttribute field; } private void addKeys(EntityManager em, EntityType type, String parent, List<TypeKey> keys) { for(Object obj : type.getAttributes()) { SingularAttribute field = (SingularAttribute)obj; if(field.isId()) { if(field.getType().getPersistenceType() == Type.PersistenceType.BASIC) { TypeKey key = new TypeKey(); key.name = parent == null ? field.getName() : parent + "." + field.getName(); key.field = field; keys.add(key); } else { EntityType subType = (EntityType)field.getType(); addKeys(em, subType, (parent == null ? field.getName() : parent + "." + field.getName()), keys); } } } } private List<TypeKey> getKeys(EntityType type) { EntityManager em = getEntityManager(domainClass); List<TypeKey> keys = new LinkedList<>(); addKeys(em, type, null, keys); return keys; } public void deleteRelation(String refId, Var[] primaryKeys, Var[] relationKeys) { EntityMetadata metadata = getMetadata(); RelationMetadata relationMetadata = metadata.getRelations().get(refId); EntityManager em = getEntityManager(domainClass); int i = 0; String jpql = null; Var[] params = null; if(relationMetadata.getAssossiationName() != null) { params = new Var[relationKeys.length + primaryKeys.length]; jpql = " DELETE FROM " + relationMetadata.gettAssossiationSimpleName() + " WHERE "; EntityType type = em.getMetamodel().entity(domainClass); List<TypeKey> keys = getKeys(type); for(TypeKey key : keys) { if(i > 0) { jpql += " AND "; } jpql += relationMetadata.getAssociationAttribute().getName() + "." + key.name + " = :p" + i; params[i] = Var.valueOf("p" + i, primaryKeys[i].getObject(key.field.getType().getJavaType())); i++; } int v = 0; type = em.getMetamodel().entity(forName(relationMetadata.getAssossiationName())); keys = getKeys(type); for(TypeKey key : keys) { if(i > 0) { jpql += " AND "; } jpql += relationMetadata.getAttribute().getName() + "." + key.name + " = :p" + i; params[i] = Var.valueOf("p" + i, relationKeys[v].getObject(key.field.getType().getJavaType())); i++; v++; } } else { params = new Var[relationKeys.length]; jpql = " DELETE FROM " + relationMetadata.getSimpleName() + " WHERE "; EntityType type = em.getMetamodel().entity(forName(relationMetadata.getName())); List<TypeKey> keys = getKeys(type); for(TypeKey key : keys) { if(i > 0) { jpql += " AND "; } jpql += "" + key.name + " = :p" + i; params[i] = Var.valueOf("p" + i, relationKeys[i].getObject(key.field.getType().getJavaType())); i++; } } execute(jpql, params); } public Object insertRelation(String refId, Map<?, ?> data, Var ... primaryKeys) { EntityMetadata metadata = getMetadata(); RelationMetadata relationMetadata = metadata.getRelations().get(refId); EntityManager em = getEntityManager(domainClass); Object result = null; try { startMultitenant(em); filter(null, new PageRequest(0, 100), primaryKeys); Object insertion = null; if (relationMetadata.getAssossiationName() != null) { insertion = this.newInstance(relationMetadata.getAssossiationName()); updateField(insertion, relationMetadata.getAttribute().getName(), Var.valueOf(data).getObject(forName(relationMetadata.getName()))); updateField(insertion, relationMetadata.getAssociationAttribute().getName(), getObject()); result = getObject(); } else { insertion = Var.valueOf(data).getObject(forName(relationMetadata.getName())); updateField(insertion, relationMetadata.getAttribute().getName(), getObject()); result = insertion; } processCloudFields(insertion); if (!em.getTransaction().isActive()) { em.getTransaction().begin(); } em.persist(insertion); if (!multiTenant) { em.flush(); } } finally { endMultitetant(); } return result; } public void filterByRelation(String refId, PageRequest pageRequest, Var ... primaryKeys) { EntityMetadata metadata = getMetadata(); RelationMetadata relationMetadata = metadata.getRelations().get(refId); EntityManager em = getEntityManager(domainClass); EntityType type = null; String name = null; String selectAttr = ""; String filterAttr = relationMetadata.getAttribute().getName(); type = em.getMetamodel().entity(domainClass); if(relationMetadata.getAssossiationName() != null) { name = relationMetadata.gettAssossiationSimpleName(); selectAttr = "." + relationMetadata.getAttribute().getName(); filterAttr = relationMetadata.getAssociationAttribute().getName(); try { domainClass = Class.forName(relationMetadata.getAttribute().getJavaType().getName()); } catch(ClassNotFoundException e) { } } else { name = relationMetadata.getSimpleName(); try { domainClass = Class.forName(name); } catch(ClassNotFoundException e) { } } int i = 0; String jpql = "Select e" + selectAttr + " from " + name + " e where "; for(Object obj : type.getAttributes()) { SingularAttribute field = (SingularAttribute)obj; if(field.isId()) { if(i > 0) { jpql += " and "; } jpql += "e." + filterAttr + "." + field.getName() + " = :p" + i; primaryKeys[i].setId("p" + i); } } filter(jpql, pageRequest, primaryKeys); } /** * Clean Datasource and to free up allocated memory */ public void clear() { this.pageRequest = new PageRequest(0, 100); this.current = -1; this.page = null; } private Object createAndSetFieldsDomain(List<String> parsedParams, TypedQuery<?> strQuery, Var ... params) { try { Object instanceForUpdate = this.domainClass.newInstance(); int i = 0; for(String param : parsedParams) { Var p = null; if(i <= params.length - 1) { p = params[i]; } if(p != null) { if(p.getId() != null) { Utils.updateField(instanceForUpdate, p.getId(), p.getObject(strQuery.getParameter(p.getId()).getParameterType())); } else { Utils.updateField(instanceForUpdate, param, p.getObject(strQuery.getParameter(parsedParams.get(i)).getParameterType())); } } else { Utils.updateField(instanceForUpdate, param, null); } i++; } return instanceForUpdate; } catch (Exception e) { throw new RuntimeException(e); } } /** * Execute Query * * @param query * - JPQL instruction for filter objects to remove * @param params * - Bidimentional array with params name and params value */ public void execute(String query, Var ... params) { EntityManager em = getEntityManager(domainClass); try { startMultitenant(em); try { TypedQuery<?> strQuery = em.createQuery(query, domainClass); int i = 0; List<String> parsedParams = parseParams(query); if (!query.trim().startsWith("DELETE")) { Object instanceForUpdate = createAndSetFieldsDomain(parsedParams, strQuery, params); processCloudFields(instanceForUpdate); for(String param : parsedParams) { Var p = null; if(i <= params.length - 1) { p = params[i]; } if(p != null) { if(p.getId() != null) { //strQuery.setParameter(p.getId(), p.getObject(strQuery.getParameter(p.getId()).getParameterType())); strQuery.setParameter(p.getId(), Utils.getFieldValue(instanceForUpdate, p.getId())); } else { // strQuery.setParameter(param, p.getObject(strQuery.getParameter(parsedParams.get(i)).getParameterType())); strQuery.setParameter(param, Utils.getFieldValue(instanceForUpdate, parsedParams.get(i))); } } else { strQuery.setParameter(param, null); } i++; } } else { for(String param : parsedParams) { Var p = null; if(i <= params.length - 1) { p = params[i]; } if(p != null) { if(p.getId() != null) { strQuery.setParameter(p.getId(), p.getObject(strQuery.getParameter(p.getId()).getParameterType())); } else { strQuery.setParameter(param, p.getObject(strQuery.getParameter(parsedParams.get(i)).getParameterType())); } } else { strQuery.setParameter(param, null); } i++; } } try { if (!em.getTransaction().isActive()) { em.getTransaction().begin(); } strQuery.executeUpdate(); } catch (Exception e) { throw new RuntimeException(e); } } catch (Exception ex) { throw new RuntimeException(ex); } } finally { endMultitetant(); } } public Var getTotalElements() { return new Var(this.page.getTotalElements()); } @Override public String toString() { if(this.page != null) { return this.page.getContent().toString(); } else { return "[]"; } } @Override public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeObject(this.page.getContent()); } @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { gen.writeObject(this.page.getContent()); } public void checkRESTSecurity(String method) throws Exception { checkRESTSecurity(domainClass, method); } public void checkRESTSecurity(String relationId, String method) throws Exception { EntityMetadata metadata = getMetadata(); RelationMetadata relationMetadata = metadata.getRelations().get(relationId); checkRESTSecurity(Class.forName(relationMetadata.getName()), method); } public String getRelationEntity(String relationId) throws Exception { EntityMetadata metadata = getMetadata(); RelationMetadata relationMetadata = metadata.getRelations().get(relationId); return relationMetadata.getName(); } private void checkRESTSecurity(Class clazz, String method) throws Exception { Annotation security = clazz.getAnnotation(CronappSecurity.class); boolean authorized = false; if(security instanceof CronappSecurity) { CronappSecurity cronappSecurity = (CronappSecurity)security; Method methodPermission = cronappSecurity.getClass().getMethod(method.toLowerCase()); if(methodPermission != null) { String value = (String)methodPermission.invoke(cronappSecurity); if(value == null || value.trim().isEmpty()) { value = "authenticated"; } String[] authorities = value.trim().split(";"); for(String role : authorities) { if(role.equalsIgnoreCase("authenticated")) { authorized = RestClient.getRestClient().getUser() != null; if(authorized) break; } if(role.equalsIgnoreCase("permitAll") || role.equalsIgnoreCase("public")) { authorized = true; break; } for(GrantedAuthority authority : RestClient.getRestClient().getAuthorities()) { if(role.equalsIgnoreCase(authority.getAuthority())) { authorized = true; break; } } if(authorized) break; } } } if(!authorized) { throw new RuntimeException(Messages.getString("notAllowed")); } } public void disableMultiTenant() { this.multiTenant = false; } public void enableMultiTenant() { this.multiTenant = true; } }
package com.sometrik.framework; import java.util.Date; import com.sometrik.framework.NativeCommand.Selector; import android.graphics.Bitmap; import android.text.InputFilter; import android.view.MotionEvent; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; public class FWEditText extends EditText implements NativeCommandHandler { private FrameWork frame; ViewStyleManager normalStyle, activeStyle, currentStyle; public FWEditText(FrameWork frameWork) { super(frameWork); this.frame = frameWork; final float scale = getContext().getResources().getDisplayMetrics().density; this.normalStyle = currentStyle = new ViewStyleManager(frame.bitmapCache, scale, true); this.activeStyle = new ViewStyleManager(frame.bitmapCache, scale, false); final FWEditText editText = this; setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { System.out.println("editText on touch"); if (event.getAction() == MotionEvent.ACTION_DOWN) { editText.currentStyle = editText.activeStyle; editText.currentStyle.apply(editText); } else if (event.getAction() == MotionEvent.ACTION_UP) { editText.currentStyle = editText.normalStyle; editText.currentStyle.apply(editText); } return false; } }); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); setLayoutParams(params); this.clearFocus(); this.setFocusable(true); } @Override public boolean performClick() { System.out.println("FWEditText onClick"); frame.setSoftKeyboardShow(this, true); return super.performClick(); } @Override public void addChild(View view) { System.out.println("FWEditText couldn't handle command"); } @Override public void addOption(int optionId, String text) { System.out.println("FWEditText couldn't handle command"); } @Override public void setValue(String v) { setText(v); setSelection(getText().length()); } @Override public void setValue(int v) { // if (v > 0) { // this.requestFocus(); // frame.setSoftKeyboardShow(this, true); // } else { // frame.setSoftKeyboardShow(this, false); } @Override public void setStyle(Selector selector, String key, String value) { if (key.equals("max-length")) { InputFilter[] filters = new InputFilter[1]; filters[0] = new InputFilter.LengthFilter(Integer.parseInt(value)); //Filter to 10 characters setFilters(filters); return; } if (selector == Selector.NORMAL) { normalStyle.setStyle(key, value); } else if (selector == Selector.ACTIVE) { activeStyle.setStyle(key, value); } } @Override public void applyStyles() { currentStyle.apply(this); } @Override public void setError(boolean hasError, String errorText) { setError(hasError ? errorText : null); } @Override public int getElementId() { return getId(); } @Override public void onScreenOrientationChange(boolean isLandscape) { // TODO Auto-generated method stub } @Override public void addData(String text, int row, int column, int sheet) { System.out.println("FWEditText couldn't handle command"); } @Override public void setViewVisibility(boolean visibility) { if (visibility){ this.setVisibility(VISIBLE); } else { this.setVisibility(GONE); } } @Override public void clear() { this.setText(""); this.clearFocus(); } @Override public void flush() { // TODO Auto-generated method stub } @Override public void addColumn(String text, int columnType) { // TODO Auto-generated method stub } @Override public void reshape(int value, int size) { // TODO Auto-generated method stub } @Override public void setBitmap(Bitmap bitmap) { } @Override public void reshape(int size) { // TODO Auto-generated method stub } @Override public void deinitialize() { // TODO Auto-generated method stub } @Override public void addImageUrl(String url, int width, int height) { // TODO Auto-generated method stub } }
package com.mapswithme.maps; import java.util.Locale; import android.app.ListActivity; import android.content.Context; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.mapswithme.maps.location.LocationService; public class SearchActivity extends ListActivity implements LocationService.Listener { private static String TAG = "SearchActivity"; private static class SearchAdapter extends BaseAdapter { private SearchActivity m_context; private LayoutInflater m_inflater; int m_count = 0; int m_resultID = 0; public SearchAdapter(SearchActivity context) { m_context = context; m_inflater = (LayoutInflater) m_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getItemViewType(int position) { return 0; } @Override public int getViewTypeCount() { return 1; } @Override public int getCount() { return m_count; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } private static class ViewHolder { public TextView m_name = null; public TextView m_country = null; public TextView m_distance = null; public TextView m_amenity = null; public ArrowImage m_flag = null; void initFromView(View v) { m_name = (TextView) v.findViewById(R.id.name); m_country = (TextView) v.findViewById(R.id.country); m_distance = (TextView) v.findViewById(R.id.distance); m_amenity = (TextView) v.findViewById(R.id.amenity); m_flag = (ArrowImage) v.findViewById(R.id.country_flag); } } /// Created from native code. public static class SearchResult { public String m_name; public String m_country; public String m_amenity; public String m_flag; public String m_distance; public double m_azimut; /// 0 - suggestion result /// 1 - feature result public int m_type; public SearchResult(String suggestion) { m_name = suggestion; m_type = 0; } public SearchResult(String name, String country, String amenity, String flag, String distance, double azimut) { m_name = name; m_country = country; m_amenity = amenity; m_flag = flag; m_distance = distance; m_azimut = azimut; m_type = 1; } } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); switch (getItemViewType(position)) { case 0: convertView = m_inflater.inflate(R.layout.search_item, null); holder.initFromView(convertView); break; } convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } //Log.d(TAG, "Getting result for result ID = " + m_resultID); final SearchResult r = m_context.getResult(position, m_resultID); if (r != null) { holder.m_name.setText(r.m_name); holder.m_country.setText(r.m_country); holder.m_amenity.setText(r.m_amenity); holder.m_distance.setText(r.m_distance); if (r.m_type == 1) { holder.m_flag.setVisibility(View.VISIBLE); if (r.m_flag != null && r.m_flag.length() > 0 && r.m_azimut < 0.0) holder.m_flag.setFlag(m_context.getResources(), r.m_flag); else holder.m_flag.setAzimut(r.m_azimut); // force invalidate arrow image holder.m_flag.invalidate(); } else holder.m_flag.setVisibility(View.INVISIBLE); } return convertView; } /// Update list data. public void updateData(int count, int resultID) { m_count = count; m_resultID = resultID; notifyDataSetChanged(); } public void updateDistance() { notifyDataSetChanged(); } /// Show tapped country or get suggestion. public String showCountry(int position) { final SearchResult r = m_context.getResult(position, m_resultID); if (r != null) { if (r.m_type == 1) { // show country and close activity SearchActivity.nativeShowItem(position); return null; } else { // advise suggestion return r.m_name; } } // return an empty string as a suggestion return ""; } } private EditText getSearchBox() { return (EditText) findViewById(R.id.search_string); } private LinearLayout getSearchToolbar() { return (LinearLayout) findViewById(R.id.search_toolbar); } private String getSearchString() { final String s = getSearchBox().getText().toString(); Log.d(TAG, "Search string = " + s); return s; } private LocationService m_location; private ProgressBar m_progress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); nativeInitSearch(); m_location = ((MWMApplication) getApplication()).getLocationService(); setContentView(R.layout.search_list_view); m_progress = (ProgressBar) findViewById(R.id.search_progress); EditText v = getSearchBox(); v.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { runSearch(); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) { } }); setListAdapter(new SearchAdapter(this)); } @Override protected void onDestroy() { super.onDestroy(); nativeFinishSearch(); } @Override protected void onResume() { super.onResume(); // Reset current mode flag - start first search. m_mode = 0; m_north = -1.0; m_location.startUpdate(this); // do the search immediately after resume runSearch(); } @Override protected void onPause() { super.onPause(); m_location.stopUpdate(this); } private SearchAdapter getSA() { return (SearchAdapter) getListView().getAdapter(); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); final String suggestion = getSA().showCountry(position); if (suggestion == null) { // close activity finish(); } else { // set suggestion string and run search (this call invokes runSearch) runSearch(suggestion); } } /// Current position. private double m_lat; private double m_lon; private double m_north = -1.0; /// It's should be equal to search::SearchParams::ModeT /// Possible values:\n /// m_mode % 2 == 0 - first search query;\n /// m_mode >= 2 - position exists;\n int m_mode = 0; @Override public void onLocationUpdated(long time, double lat, double lon, float accuracy) { if (m_mode < 2) m_mode += 2; m_lat = lat; m_lon = lon; runSearch(); } @Override public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy) { final int orientation = getWindowManager().getDefaultDisplay().getOrientation(); final double correction = LocationService.getAngleCorrection(orientation); final double north = LocationService.correctAngle(trueNorth, correction); // if difference is more than 1 degree if (m_north == -1 || Math.abs(m_north - north) > 0.02) { m_north = north; //Log.d(TAG, "Compass updated, north = " + m_north); getSA().updateDistance(); } } @Override public void onLocationStatusChanged(int status) { } private int m_queryID = 0; /// Make 5-step increment to leave space for middle queries. /// This constant should be equal with native SearchAdapter::QUERY_STEP; private final static int QUERY_STEP = 5; private boolean isCurrentResult(int id) { return (id >= m_queryID && id < m_queryID + QUERY_STEP); } public void updateData(final int count, final int resultID) { runOnUiThread(new Runnable() { @Override public void run() { Log.d(TAG, "Show " + count + " results for id = " + resultID); // if this results for the last query - hide progress if (isCurrentResult(resultID)) m_progress.setVisibility(View.GONE); // update list view content getSA().updateData(count, resultID); // scroll list view to the top setSelection(0); } }); } /// @name Amenity buttons listeners public void onSearchFood(View v) { runSearch("food "); } public void onSearchMoney(View v) { runSearch("money "); } public void onSearchFuel(View v) { runSearch("fuel "); } public void onSearchShop(View v) { runSearch("shop "); } public void onSearchTransport(View v) { runSearch("transport "); } public void onSearchTourism(View v) { runSearch("tourism "); } private void runSearch(String s) { EditText box = getSearchBox(); // this call invokes runSearch box.setText(s); // put cursor to the end of string box.setSelection(s.length()); } private void runSearch() { // TODO Need to get input language final String lang = Locale.getDefault().getLanguage(); Log.d(TAG, "Current language = " + lang); final String s = getSearchString(); final int id = m_queryID + QUERY_STEP; if (nativeRunSearch(s, lang, m_lat, m_lon, m_mode, id)) { // store current query m_queryID = id; //Log.d(TAG, "Current search query id =" + m_queryID); // mark that it's not the first query already if (m_mode % 2 == 0) ++m_mode; // set toolbar visible only for empty search string LinearLayout bar = getSearchToolbar(); bar.setVisibility(s.length() == 0 ? View.VISIBLE : View.GONE); // show search progress m_progress.setVisibility(View.VISIBLE); } } public SearchAdapter.SearchResult getResult(int position, int queryID) { return nativeGetResult(position, queryID, m_lat, m_lon, m_mode, m_north); } private native void nativeInitSearch(); private native void nativeFinishSearch(); private static native SearchAdapter.SearchResult nativeGetResult(int position, int queryID, double lat, double lon, int mode, double north); private native boolean nativeRunSearch(String s, String lang, double lat, double lon, int mode, int queryID); private static native void nativeShowItem(int position); }
package com.apollo.managers.graphics; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetDescriptor; import com.badlogic.gdx.assets.AssetLoaderParameters; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.assets.loaders.FileHandleResolver; import com.badlogic.gdx.assets.loaders.SynchronousAssetLoader; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.Json.Serializer; import com.badlogic.gdx.utils.JsonValue; import com.badlogic.gdx.utils.OrderedMap; /** * @author egyware * */ public class SpriteLoader extends SynchronousAssetLoader<Sprite, SpriteLoader.AnimationParameter> { public static final int DEFAULT_DURATION = 200; //100 ms private Json json; private SpriteSerializer serializer; public SpriteLoader(FileHandleResolver resolver) { super(resolver); json = new Json(); serializer = new SpriteSerializer(); json.setSerializer(Sprite.class,serializer); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Array<AssetDescriptor> getDependencies(String fileName, FileHandle file, AnimationParameter parameter) { Array<AssetDescriptor> deps = new Array<AssetDescriptor>(); if (parameter == null) { deps.add(new AssetDescriptor(file .pathWithoutExtension() + ".atlas", TextureAtlas.class)); } else { deps.add(new AssetDescriptor(parameter.textureAtlasPath, TextureAtlas.class)); } return deps; } @Override public Sprite load(AssetManager assetManager, String fileName, FileHandle file, AnimationParameter parameter) { String textureAtlasPath; if (parameter == null) { textureAtlasPath = file.pathWithoutExtension() + ".atlas"; } else { textureAtlasPath = parameter.textureAtlasPath; } //con esto no puede ser asincronico serializer.setAtlas(assetManager.get(textureAtlasPath, TextureAtlas.class)); Sprite sprite = json.fromJson(Sprite.class, Gdx.files.internal(fileName)); return sprite; } private final class SpriteSerializer implements Serializer<Sprite> { private TextureAtlas atlas; private SpriteSerializer() { } public void setAtlas(TextureAtlas textureAtlas) { atlas = textureAtlas; } @SuppressWarnings("rawtypes") @Override public void write(Json json, Sprite object, Class knownType) { // TODO Auto-generated method stub } @SuppressWarnings({ "rawtypes"}) @Override public Sprite read(Json json, JsonValue jsonData, Class type) { Sprite sprite = new Sprite(); // talvez no sea la mejor manera de leer estos datos, pero por // lo menos es simple json.readField(sprite, "width", jsonData); json.readField(sprite, "height", jsonData); json.readField(sprite, "origin", jsonData); json.readField(sprite, "first", jsonData); JsonValue animations = jsonData.get("animations"); for (JsonValue animation : animations) { JsonValue sequence = animation.get("sequence"); String name = animation.getString("name"); String region = (animation.hasChild("region"))?animation.getString("region"):name; AtlasRegion array[] = null; int duration = DEFAULT_DURATION; if(sequence.hasChild("delay")) { duration = (int) sequence.getInt("delay"); } Array<AtlasRegion> regions = atlas.findRegions(region); if(sequence.hasChild("data")) { JsonValue framesArray = sequence.get("data"); array = new AtlasRegion[framesArray.size]; for (int i = 0; i < framesArray.size; i++) { array[i] = regions.get(framesArray.getInt(i)); } } if (array == null) { array = new AtlasRegion[regions.size]; for (int i = 0; i < regions.size; i++) { array[i] = regions.get(i); } } // ya ahora estn listos los datos :D sprite.addAnimation(name, new Animation(duration * 0.001f, array)); } return sprite; } } static public class AnimationParameter extends AssetLoaderParameters<Sprite> { public String textureAtlasPath; public AnimationParameter(String _textureAtlasPath) { textureAtlasPath = _textureAtlasPath; } } }
package graphql; import graphql.execution.ExecutionPath; import graphql.execution.ExecutionStepInfo; import graphql.execution.UnresolvedTypeException; import graphql.language.SourceLocation; import java.util.List; import static graphql.Assert.assertNotNull; import static graphql.schema.GraphQLTypeUtil.simplePrint; import static java.lang.String.format; @PublicApi public class UnresolvedTypeError implements GraphQLError { private final String message; private final List<Object> path; private final UnresolvedTypeException exception; public UnresolvedTypeError(ExecutionPath path, ExecutionStepInfo info, UnresolvedTypeException exception) { this.path = assertNotNull(path).toList(); this.exception = assertNotNull(exception); this.message = mkMessage(path, exception, assertNotNull(info)); } private String mkMessage(ExecutionPath path, UnresolvedTypeException exception, ExecutionStepInfo info) { return format("Can't resolve '%s'. Abstract type '%s' must resolve to an Object type at runtime for field '%s.%s'. %s", path, exception.getInterfaceOrUnionType().getName(), simplePrint(info.getParent().getUnwrappedNonNullType()), info.getFieldDefinition().getName(), exception.getMessage()); } public UnresolvedTypeException getException() { return exception; } @Override public String getMessage() { return message; } @Override public List<SourceLocation> getLocations() { return null; } @Override public ErrorType getErrorType() { return ErrorType.DataFetchingException; } @Override public List<Object> getPath() { return path; } @Override public String toString() { return "UnresolvedTypeError{" + "path=" + path + ", exception=" + exception + '}'; } @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @Override public boolean equals(Object o) { return GraphqlErrorHelper.equals(this, o); } @Override public int hashCode() { return GraphqlErrorHelper.hashCode(this); } }
package group7.anemone.UI; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import processing.core.PApplet; public class Utilities { public static double distanceBetweenPoints(double ax, double ay, double bx, double by){ return Math.sqrt(Math.pow((float) (bx - ax), 2) + Math.pow((float) (by - ay), 2)); } public static double angleBetweenPoints(double ax, double ay, double bx, double by){ double angle = 0; if(bx - ax == 0){ if(by > ay) angle = -90; else angle = 90; }else angle = Math.atan((by - ay) / (bx - ax)) * 180.0 / Math.PI; if(bx > ax) { if (by < ay) angle = 360 + angle; }else{ if (by >= ay) angle = 180 + angle; else angle += 180; } return angle; } public static void line(PApplet canvas, int x1, int y1, int len, double angle){ canvas.pushMatrix(); canvas.translate(x1, y1); canvas.rotate((float) ((angle - 90) * Math.PI / 180)); canvas.line(0, 0, 0, len); canvas.popMatrix(); } public static void pointAtAngle(PApplet canvas, double x, double y, double dist, double angle){ canvas.pushMatrix(); canvas.translate((int) x, (int) y); canvas.rotate((float) ((angle - 90) * Math.PI / 180)); canvas.point(0, (int) dist); canvas.popMatrix(); } public static boolean isPointInBox(int x, int y, int rx, int ry, int w, int h){ return (x >= rx && x <= rx + w && y >= ry && y <= ry + h); } //assumes that the lines do intersect public static Point2D.Double findIntersection(Line2D.Double line1, Line2D.Double line2){ Point2D.Double intersection = new Point2D.Double(); //get gradients and y intercepts double m1 = (line1.y2-line1.y1)/(line1.x2-line1.x1); double c1 = line1.y1 - m1 * line1.x1; double m2 = (line2.y2-line2.y1)/(line2.x2-line2.x1); double c2 = line2.y1 - m2 * line2.x1; boolean m2Invalid = (m2 == Double.POSITIVE_INFINITY || m2 == Double.NEGATIVE_INFINITY || Double.isNaN(m2)); boolean c2Invalid = (c2 == Double.POSITIVE_INFINITY || c2 == Double.NEGATIVE_INFINITY || Double.isNaN(c2)); boolean c2NaN = c2 == Double.NaN; //if the lines aren't parallel if(m1 != m2){ //get x value of intersection double intersectX = -(c1-c2)/(m1-m2); if(m2Invalid && c2Invalid) intersectX = line2.x1; //check it lies within both segments boolean withinLine1 = Math.min(line1.x1,line1.x2) < intersectX && intersectX < Math.max(line1.x1, line1.x2); boolean withinLine2 = Math.min(line2.x1,line2.x2) < intersectX && intersectX < Math.max(line2.x1, line2.x2); if((m2Invalid && c2Invalid)) withinLine2 = true; if(withinLine1 && withinLine2) { //calculate y value of intersection double intersectY = m1*intersectX + c1; intersection = new Point2D.Double(intersectX, intersectY); } } return intersection; } public static Line2D.Double generateLine(Point2D.Double point, double length, double angle){ double endX = length * Math.cos(angle*(Math.PI/180)) + point.x; double endY = length * Math.sin(angle*(Math.PI/180)) + point.y; return new Line2D.Double(point,new Point2D.Double(endX,endY)); } }
package hudson.remoting; import java.io.CharArrayWriter; import java.io.IOException; import java.io.InterruptedIOException; import java.io.Writer; import java.util.logging.Level; import java.util.logging.Logger; /** * {@link Writer} that sends bits to an exported * {@link Writer} on a remote machine. */ final class ProxyWriter extends Writer { private Channel channel; private int oid; private PipeWindow window; /** * If bytes are written to this stream before it's connected * to a remote object, bytes will be stored in this buffer. */ private CharArrayWriter tmp; /** * Set to true if the stream is closed. */ private boolean closed; /** * Creates unconnected {@link ProxyWriter}. * The returned stream accepts data right away, and * when it's {@link #connect(Channel,int) connected} later, * the data will be sent at once to the remote stream. */ public ProxyWriter() { } /** * Creates an already connected {@link ProxyWriter}. * * @param oid * The object id of the exported {@link Writer}. */ public ProxyWriter(Channel channel, int oid) throws IOException { connect(channel,oid); } /** * Connects this stream to the specified remote object. */ synchronized void connect(Channel channel, int oid) throws IOException { if(this.channel!=null) throw new IllegalStateException("Cannot connect twice"); if(oid==0) throw new IllegalArgumentException("oid=0"); this.channel = channel; this.oid = oid; window = channel.getPipeWindow(oid); // if we already have bytes to write, do so now. if(tmp!=null) { char[] b = tmp.toCharArray(); tmp = null; _write(b, 0, b.length); } if(closed) // already marked closed? close(); } public void write(int c) throws IOException { write(new char[]{(char)c},0,1); } public void write(char[] cbuf, int off, int len) throws IOException { if (closed) throw new IOException("stream is already closed"); _write(cbuf, off, len); } /** * {@link #write(char[])} without the close check. */ private synchronized void _write(char[] cbuf, int off, int len) throws IOException { if(channel==null) { if(tmp==null) tmp = new CharArrayWriter(); tmp.write(cbuf); } else { final int max = window.max(); while (len>0) { int sendable; try { /* To avoid fragmentation of the pipe window, at least demand that 10% of the pipe window be reclaimed. Imagine a large latency network where we are always low on the window size, and we are continuously sending data of irregular size. In such a circumstance, a fragmentation will happen. We start sending out a small Chunk at a time (say 4 bytes), and when its Ack comes back, it gets immediately consumed by another out-bound Chunk of 4 bytes. Clearly, it's better to wait a bit until we have a sizable pipe window, then send out a bigger Chunk, since Chunks have static overheads. This code does just that. (Except when what we are trying to send as a whole is smaller than the current available window size, in which case there's no point in waiting.) */ sendable = Math.min(window.get(Math.min(max/10,len)),len); /* Imagine if we have a lot of data to send and the pipe window is fully available. If we create one Chunk that fully uses the window size, we need to wait for the whole Chunk to get to the other side, then the Ack to come back to this side, before we can send a next Chunk. While the Ack is traveling back to us, we have to sit idle. This fails to utilize available bandwidth. A better strategy is to create a smaller Chunk, say half the window size. This allows the other side to send back the ack while we are sending the second Chunk. In a network with a non-trivial latency, this allows Chunk and Ack to overlap, and that improves the utilization. It's not clear what the best size of the chunk to send (there's a certain overhead in our Command structure, around 100-200 bytes), so I'm just starting with 2. Further analysis would be needed to determine the best value. */ sendable = Math.min(sendable, max /2); } catch (InterruptedException e) { throw (IOException)new InterruptedIOException().initCause(e); } channel.send(new Chunk(channel.newIoId(),oid,cbuf,off,sendable)); window.decrease(sendable); off+=sendable; len-=sendable; } } } public void flush() throws IOException { if(channel!=null && channel.remoteCapability.supportsProxyWriter2_35()) channel.send(new Flush(channel.newIoId(),oid)); } public synchronized void close() throws IOException { error(null); } public synchronized void error(Throwable e) throws IOException { if (!closed) { closed = true; // error = e; } if(channel!=null) doClose(e); } private void doClose(Throwable error) throws IOException { channel.send(new EOF(channel.newIoId(),oid/*,error*/)); channel = null; oid = -1; } protected void finalize() throws Throwable { super.finalize(); // if we haven't done so, release the exported object on the remote side. // if the object is auto-unexported, the export entry could have already been removed. if(channel!=null) { if (channel.remoteCapability.supportsProxyWriter2_35()) channel.send(new Unexport(channel.newIoId(),oid)); else channel.send(new EOF(channel.newIoId(),oid)); channel = null; oid = -1; } } /** * {@link Command} for sending bytes. */ private static final class Chunk extends Command { private final int ioId; private final int oid; private final char[] buf; public Chunk(int ioId, int oid, char[] buf, int start, int len) { // to improve the performance when a channel is used purely as a pipe, // don't record the stack trace. On FilePath.writeToTar case, the stack trace and the OOS header // takes up about 1.5K. super(false); this.ioId = ioId; this.oid = oid; if (start==0 && len==buf.length) this.buf = buf; else { this.buf = new char[len]; System.arraycopy(buf,start,this.buf,0,len); } } protected void execute(final Channel channel) { final Writer os = (Writer) channel.getExportedObject(oid); channel.pipeWriter.submit(ioId, new Runnable() { public void run() { try { os.write(buf); } catch (IOException e) { try { if (channel.remoteCapability.supportsProxyWriter2_35()) channel.send(new NotifyDeadWriter(channel, e, oid)); } catch (ChannelClosedException x) { // the other direction can be already closed if the connection // shut down is initiated from this side. In that case, remain silent. } catch (IOException x) { // ignore errors LOGGER.log(Level.WARNING, "Failed to notify the sender that the write end is dead", x); LOGGER.log(Level.WARNING, "... the failed write was:", e); } } finally { if (channel.remoteCapability.supportsProxyWriter2_35()) { try { channel.send(new Ack(oid, buf.length)); } catch (ChannelClosedException x) { // the other direction can be already closed if the connection // shut down is initiated from this side. In that case, remain silent. } catch (IOException e) { // ignore errors LOGGER.log(Level.WARNING, "Failed to ack the stream", e); } } } } }); } public String toString() { return "Pipe.Chunk("+oid+","+buf.length+")"; } private static final long serialVersionUID = 1L; } /** * {@link Command} for flushing. * @since 2.35 */ private static final class Flush extends Command { private final int oid; private final int ioId; public Flush(int ioId, int oid) { super(false); this.ioId = ioId; this.oid = oid; } protected void execute(Channel channel) { final Writer os = (Writer) channel.getExportedObject(oid); channel.pipeWriter.submit(ioId, new Runnable() { public void run() { try { os.flush(); } catch (IOException e) { // ignore errors } } }); } public String toString() { return "Pipe.Flush("+oid+")"; } private static final long serialVersionUID = 1L; } /** * {@link Command} for releasing an export table. * * <p> * Unlike {@link EOF}, this just unexports but not closes the stream. * @since 2.35 */ private static class Unexport extends Command { private final int oid; private final int ioId; public Unexport(int ioId, int oid) { this.ioId = ioId; this.oid = oid; } protected void execute(final Channel channel) { channel.pipeWriter.submit(ioId,new Runnable() { public void run() { channel.unexport(oid); } }); } public String toString() { return "Pipe.Unexport("+oid+")"; } private static final long serialVersionUID = 1L; } /** * {@link Command} for sending EOF. */ private static final class EOF extends Command { private final int oid; private final int ioId; public EOF(int ioId,int oid) { this.ioId = ioId; this.oid = oid; } protected void execute(final Channel channel) { final Writer os = (Writer) channel.getExportedObject(oid); channel.pipeWriter.submit(ioId, new Runnable() { public void run() { channel.unexport(oid); try { os.close(); } catch (IOException e) { // ignore errors } } }); } public String toString() { return "Pipe.EOF("+oid+")"; } private static final long serialVersionUID = 1L; } /** * {@link Command} to notify the sender that it can send some more data. * @since 2.35 */ private static class Ack extends Command { /** * The oid of the {@link Writer} on the receiver side of the data. */ private final int oid; /** * The number of bytes that were freed up. */ private final int size; private Ack(int oid, int size) { super(false); // performance optimization this.oid = oid; this.size = size; } protected void execute(Channel channel) { PipeWindow w = channel.getPipeWindow(oid); w.increase(size); } public String toString() { return "Pipe.Ack("+oid+','+size+")"; } private static final long serialVersionUID = 1L; } /** * {@link Command} to notify the sender that the receiver is dead. * @since 2.35 */ private static final class NotifyDeadWriter extends Command { private final int oid; private NotifyDeadWriter(Channel channel,Throwable cause, int oid) { super(channel,cause); this.oid = oid; } @Override protected void execute(Channel channel) { PipeWindow w = channel.getPipeWindow(oid); w.dead(createdAt.getCause()); } public String toString() { return "Pipe.Dead("+oid+")"; } private static final long serialVersionUID = 1L; } private static final Logger LOGGER = Logger.getLogger(ProxyWriter.class.getName()); }
package infovis.routing; import infovis.data.BusDataBuilder; import infovis.data.BusEdge; import infovis.data.BusStation; import infovis.data.BusStationManager; import infovis.data.BusTime; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.PriorityQueue; /** * Algorithm for finding shortest routes from a given bus station. * * @author Leo Woerteler */ public final class RouteFinder implements RoutingAlgorithm { /** Comparator for comparing {@link Route}s by travel time. */ private static final Comparator<Route> CMP = new Comparator<Route>() { @Override public int compare(final Route o1, final Route o2) { return o1.travelTime - o2.travelTime; } }; @Override public Collection<RoutingResult> findRoutes(final BusStation station, final BitSet dests, final BusTime start, final int wait, final int maxDuration) throws InterruptedException { final Map<BusStation, List<BusEdge>> map = findRoutesFrom(station, dests, start, wait, maxDuration); final List<RoutingResult> res = new ArrayList<RoutingResult>(map.size()); for(final Entry<BusStation, List<BusEdge>> e : map.entrySet()) { final List<BusEdge> list = e.getValue(); final BusStation to = e.getKey(); if(list.isEmpty()) { res.add(new RoutingResult(station)); } else { res.add(new RoutingResult(station, to, start.minutesTo(list.get(list.size() - 1).getEnd()), list, start)); } } return res; } /** * Finds shortest routes to all reachable stations from the given start * station at the given start time. * * @param station start position * @param dests set of IDs of stations that should be reached, * <code>null</code> means all stations of the start station's * {@link BusStationManager} * @param start start time * @param wait waiting time when changing lines * @param maxDuration maximum allowed duration of a route * @return map from station to shortest route * @throws InterruptedException if the current thread was interrupted during * the computation */ public static Map<BusStation, List<BusEdge>> findRoutesFrom(final BusStation station, final BitSet dests, final BusTime start, final int wait, final int maxDuration) throws InterruptedException { // set of stations yet to be found final BitSet notFound = dests == null ? new BitSet() : (BitSet) dests.clone(); if(dests == null) { for(final BusStation s : station.getManager().getStations()) { notFound.set(s.getId()); } } notFound.set(station.getId(), false); final Map<BusStation, Route> bestRoutes = new HashMap<BusStation, Route>(); final PriorityQueue<Route> queue = new PriorityQueue<Route>(16, CMP); for(final BusEdge e : station.getEdges(start)) { final Route route = new Route(start, e); if(route.travelTime <= maxDuration) { queue.add(route); } } for(Route current; !notFound.isEmpty() && (current = queue.poll()) != null;) { if(Thread.interrupted()) throw new InterruptedException(); final BusEdge last = current.last; final BusStation dest = last.getTo(); final Route best = bestRoutes.get(dest); if(best == null) { bestRoutes.put(dest, current); notFound.set(dest.getId(), false); } final BusTime arrival = last.getEnd(); for(final BusEdge e : dest.getEdges(arrival)) { if(current.timePlus(e) > maxDuration || current.contains(e.getTo())) { // violates general invariants continue; } final boolean sameTour = last.sameTour(e); if(!sameTour && arrival.minutesTo(e.getStart()) < wait) { // bus is missed continue; } if(best != null && !(sameTour && best.last.getEnd().minutesTo(last.getEnd()) < wait)) { // one could just change the bus from the optimal previous route continue; } queue.add(current.extendedBy(e)); } } final Map<BusStation, List<BusEdge>> res = new HashMap<BusStation, List<BusEdge>>(); res.put(station, Collections.EMPTY_LIST); for(final Entry<BusStation, Route> e : bestRoutes.entrySet()) { res.put(e.getKey(), e.getValue().asList()); } return res; } /** * Finds a single shortest route from the start station to the destination. * * @param station start station * @param dest destination * @param start start time * @param wait waiting time when changing bus lines * @param maxDuration maximum allowed travel time * @return shortest route if found, <code>null</code> otherwise * @throws InterruptedException if the current thread was interrupted */ public static List<BusEdge> findRoute(final BusStation station, final BusStation dest, final BusTime start, final int wait, final int maxDuration) throws InterruptedException { final BitSet set = new BitSet(); set.set(dest.getId()); return findRoutesFrom(station, set, start, wait, maxDuration).get(dest); } @Override public String toString() { return "Exact route finder"; } /** * Inner class for routes. * * @author Leo Woerteler */ private static final class Route { /** Route up to this point, possibly {@code null}. */ final Route before; /** Last edge in the route. */ final BusEdge last; /** Overall travel time in minutes. */ final int travelTime; /** Stations in this route. */ private final BitSet stations; /** * Creates a new route with given waiting time and first edge. * * @param start start time of the route * @param first first edge */ Route(final BusTime start, final BusEdge first) { before = null; last = first; travelTime = start.minutesTo(first.getStart()) + first.travelMinutes(); stations = new BitSet(); stations.set(first.getFrom().getId()); stations.set(first.getTo().getId()); } /** * Creates a new route with given previous route and last edge. * * @param before previously taken route * @param last last edge */ private Route(final Route before, final BusEdge last) { this.before = before; this.last = last; travelTime = before.timePlus(last); stations = (BitSet) before.stations.clone(); stations.set(last.getTo().getId()); } /** * Creates a new route by extending this one by the given edge. * * @param next edge to be added * @return new route */ public Route extendedBy(final BusEdge next) { assert loopFree(next); // loop detection return new Route(this, next); } /** * Tests whether a route with the given next edge would have no loops. This * is a general invariant and the method should only be called for debugging * purposes. * * @param next The possible next route. * @return Whether the resulting route has no loops. */ private boolean loopFree(final BusEdge next) { for(Route r = this; r != null; r = r.before) { if(r.last.equals(next)) return false; } return true; } /** * Checks if this route contains the given bus station. * * @param s bus station * @return <code>true</code> if the station is contained, <code>false</code> * otherwise */ public boolean contains(final BusStation s) { return stations.get(s.getId()); } /** * Calculates the overall travel time of this route as extended by the given * edge. * * @param next next edge * @return time in minutes */ public int timePlus(final BusEdge next) { return travelTime + last.getEnd().minutesTo(next.getStart()) + next.travelMinutes(); } /** * Creates a list containing all edges of this route. * * @return list containing all edges */ public List<BusEdge> asList() { final List<BusEdge> list = before == null ? new ArrayList<BusEdge>() : before.asList(); list.add(last); return list; } @Override public String toString() { return last.toString(); } } /** * A little performance test. * * @param args No-args * @throws Exception No-exceptions */ public static void main(final String[] args) throws Exception { final BusStationManager man = BusDataBuilder.load("src/main/resources"); final BitSet set = new BitSet(); for(final BusStation a : man.getStations()) { set.set(a.getId()); } final boolean performance = true, store = false; if(performance) { final int numTests = 5; double avgFullTime = 0; double c = 0; for(int i = 0; i < numTests; ++i) { int count = 0; final long time = System.currentTimeMillis(); for(final BusStation a : man.getStations()) { RouteFinder.findRoutesFrom(a, set, new BusTime(12, 0), 5, man.getMaxTimeHours() * BusTime.MINUTES_PER_HOUR); ++count; } final double fullTime = System.currentTimeMillis() - time; avgFullTime += fullTime; c = count; } final double fullTime = avgFullTime / numTests; final PrintWriter out = new PrintWriter(new OutputStreamWriter( new FileOutputStream( new File("performance.txt"), true), "UTF-8")); out.println(fullTime / 1000 + "s " + fullTime / c + "ms per line"); out.close(); System.out.println(fullTime / 1000 + "s"); System.out.println(fullTime / c + "ms per line"); } else if(store) { final List<BusStation> stations = new ArrayList<BusStation>(man.getStations()); Collections.sort(stations); final DataOutputStream dos = new DataOutputStream(new BufferedOutputStream( new FileOutputStream("res.txt"))); for(final BusStation a : stations) { dos.writeByte(a.getId()); final Map<BusStation, List<BusEdge>> routes = RouteFinder.findRoutesFrom(a, set, new BusTime(12, 0), 5, man.getMaxTimeHours() * BusTime.MINUTES_PER_HOUR); for(final BusStation to : stations) { dos.writeByte(to.getId()); final List<BusEdge> route = routes.get(to); final int time = route == null ? -1 : route.isEmpty() ? 0 : new BusTime(12, 0).minutesTo(route.get(route.size() - 1).getEnd()); dos.writeInt(time); } dos.writeByte(-2); } dos.close(); } else { final DataInputStream in = new DataInputStream(new BufferedInputStream( new FileInputStream("res.txt"))); for(int station; (station = in.read()) != -1;) { final BusStation a = man.getForId(station); final Map<BusStation, List<BusEdge>> routes = RouteFinder.findRoutesFrom(a, set, new BusTime(12, 0), 5, man.getMaxTimeHours() * BusTime.MINUTES_PER_HOUR); for(int toId; (toId = in.read()) < 128;) { final BusStation to = man.getForId(toId); final int duration = in.readInt(); final List<BusEdge> route = routes.get(to); if(duration == -1) { if(route != null) { System.out.println("Didn't expect route from " + a + " to " + to + ": " + route); } } else if(duration == 0) { if(route == null || station == toId && !route.isEmpty()) { System.out.println("Route from and to " + a + " should be empty: " + route); } } else if(route == null || new BusTime(12, 0).minutesTo(route.get(route.size() - 1).getEnd()) != duration) { System.out.println("Expected " + duration + "min from " + a + " to " + to + ": " + route); } } } } } }
package invtweaks.forge; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.relauncher.Side; import invtweaks.*; import invtweaks.api.IItemTreeListener; import invtweaks.api.SortingMethod; import invtweaks.api.container.ContainerSection; import invtweaks.network.packets.ITPacketClick; import invtweaks.network.packets.ITPacketSortComplete; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.multiplayer.PlayerControllerMP; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import org.lwjgl.input.Keyboard; public class ClientProxy extends CommonProxy { public static final KeyBinding KEYBINDING_SORT = new KeyBinding("invtweaks.key.sort", Keyboard.KEY_R, "invtweaks.key.category"); private InvTweaks instance; private ForgeClientTick clientTick; public boolean serverSupportEnabled = false; public boolean serverSupportDetected = false; @Override public void preInit(FMLPreInitializationEvent e) { super.preInit(e); InvTweaks.log = e.getModLog(); } @Override public void init(FMLInitializationEvent e) { super.init(e); Minecraft mc = FMLClientHandler.instance().getClient(); // Instantiate mod core instance = new InvTweaks(mc); clientTick = new ForgeClientTick(instance); FMLCommonHandler.instance().bus().register(clientTick); MinecraftForge.EVENT_BUS.register(this); ClientRegistry.registerKeyBinding(KEYBINDING_SORT); } @SubscribeEvent public void notifyPickup(PlayerEvent.ItemPickupEvent e) { instance.setItemPickupPending(true); } @SubscribeEvent public void onItemTooltip(ItemTooltipEvent e) { if(e.showAdvancedItemTooltips) { String first_line = e.toolTip.get(0); first_line += " [" + Item.itemRegistry.getNameForObject(e.itemStack.getItem()) + "]"; e.toolTip.set(0, first_line); } } @Override public void setServerAssistEnabled(boolean enabled) { serverSupportEnabled = serverSupportDetected && enabled; //InvTweaks.log.info("Server has support: " + serverSupportDetected + " support enabled: " + serverSupportEnabled); } @Override public void setServerHasInvTweaks(boolean hasInvTweaks) { serverSupportDetected = hasInvTweaks; serverSupportEnabled = hasInvTweaks && !InvTweaks.getConfigManager().getConfig() .getProperty(InvTweaksConfig.PROP_ENABLE_SERVER_ITEMSWAP) .equals(InvTweaksConfig.VALUE_FALSE); //InvTweaks.log.info("Server has support: " + hasInvTweaks + " support enabled: " + serverSupportEnabled); } @Override public void slotClick(PlayerControllerMP playerController, int windowId, int slot, int data, int action, EntityPlayer player) { //int modiferKeys = (shiftHold) ? 1 : 0 /* XXX Placeholder */; if(serverSupportEnabled) { player.openContainer.slotClick(slot, data, action, player); invtweaksChannel.get(Side.CLIENT).writeOutbound(new ITPacketClick(slot, data, action)); } else { playerController.windowClick(windowId, slot, data, action, player); } } @Override public void sortComplete() { if(serverSupportEnabled) { invtweaksChannel.get(Side.CLIENT).writeOutbound(new ITPacketSortComplete()); } } @Override public void addOnLoadListener(IItemTreeListener listener) { InvTweaksItemTreeLoader.addOnLoadListener(listener); } @Override public boolean removeOnLoadListener(IItemTreeListener listener) { return InvTweaksItemTreeLoader.removeOnLoadListener(listener); } @Override public void setSortKeyEnabled(boolean enabled) { instance.setSortKeyEnabled(enabled); } @Override public void setTextboxMode(boolean enabled) { instance.setTextboxMode(enabled); } @Override public int compareItems(ItemStack i, ItemStack j) { return instance.compareItems(i, j); } @Override public void sort(ContainerSection section, SortingMethod method) { // TODO: This seems like something useful enough to be a util method somewhere. Minecraft mc = FMLClientHandler.instance().getClient(); Container currentContainer = mc.thePlayer.inventoryContainer; if(mc.currentScreen instanceof GuiContainer) { currentContainer = ((GuiContainer) mc.currentScreen).inventorySlots; } try { new InvTweaksHandlerSorting(mc, instance.getConfigManager().getConfig(), section, method, InvTweaksObfuscation.getSpecialChestRowSize(currentContainer)).sort(); } catch(Exception e) { InvTweaks.logInGameErrorStatic("invtweaks.sort.chest.error", e); e.printStackTrace(); } } }
package jkanvas.animation; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; /** * A list of circular shaped points with filling and border color. * * @author Joschi <josua.krause@gmail.com> * @param <T> The point shape type. */ public abstract class PointList<T extends Shape> extends GenericPaintList<T> { /** The index for the x coordinate. */ protected static final int X_COORD = 0; /** The index for the y coordinate. */ protected static final int Y_COORD = 1; /** The index for the size. */ protected static final int SIZE = 2; /** The index for the filling color. */ protected static final int COLOR_FILL = 0; /** The index for the border color. */ protected static final int COLOR_BORDER = 1; /** The default filling color. */ private Color defaultColor; /** The default border color. */ private Color defaultBorder; /** * Creates a point list with initial size. * * @param initialSize The initial size. * @param defaultColor The default filling color. * @param defaultBorder The default border color. */ public PointList(final int initialSize, final Color defaultColor, final Color defaultBorder) { super(3, 2, initialSize); this.defaultColor = defaultColor; this.defaultBorder = defaultBorder; } /** * Setter. * * @param defaultColor Sets the default filling color. <code>null</code> * indicates a invisible fill. */ public void setDefaultColor(final Color defaultColor) { this.defaultColor = defaultColor; } /** * Getter. * * @return The default filling color or <code>null</code> if the filling is * not visible. */ public Color getDefaultColor() { return defaultColor; } /** * Setter. * * @param defaultBorder Sets the default border color. <code>null</code> * indicates a invisible border. */ public void setDefaultBorder(final Color defaultBorder) { this.defaultBorder = defaultBorder; } /** * Getter. * * @return The default border color or <code>null</code> if the border is not * visible. */ public Color getDefaultBorder() { return defaultBorder; } /** * Adds a point. * * @param x The initial x coordinate. * @param y The initial y coordinate. * @param size The initial size. * @return The index of the point. */ public int addPoint(final double x, final double y, final double size) { final int index = addIndex(); final int pos = getPosition(index); set(X_COORD, pos, x); set(Y_COORD, pos, y); set(SIZE, pos, size); final int cpos = getColorPosition(index); setColor(COLOR_FILL, cpos, null); setColor(COLOR_BORDER, cpos, null); return index; } /** * Sets the position of the given point. * * @param index The index of the point. * @param x The x coordinate. * @param y The y coordinate. * @param size The size. */ public void setPoint(final int index, final double x, final double y, final double size) { ensureActive(index); final int pos = getPosition(index); set(X_COORD, pos, x); set(Y_COORD, pos, y); set(SIZE, pos, size); } /** * Getter. * * @param index The index of the point. * @return The x coordinate. */ public double getX(final int index) { ensureActive(index); final int pos = getPosition(index); return get(X_COORD, pos); } /** * Getter. * * @param index The index of the point. * @return The y coordinate. */ public double getY(final int index) { ensureActive(index); final int pos = getPosition(index); return get(Y_COORD, pos); } /** * Getter. * * @param p The shape the position will be stored. * @param index The index of the point. */ public void getPosition(final Point2D p, final int index) { ensureActive(index); final int pos = getPosition(index); p.setLocation(get(X_COORD, pos), get(Y_COORD, pos)); } /** * Setter. * * @param index The index. * @param x The x coordinate. * @param y The y coordinate. */ public void setPosition(final int index, final double x, final double y) { ensureActive(index); final int pos = getPosition(index); set(X_COORD, pos, x); set(Y_COORD, pos, y); } /** * Getter. * * @param index The index. * @return The size. */ public double getRadius(final int index) { ensureActive(index); final int pos = getPosition(index); return get(SIZE, pos); } /** * Setter. * * @param index The index. * @param radius The size. */ public void setRadius(final int index, final double radius) { ensureActive(index); final int pos = getPosition(index); set(SIZE, pos, radius); } /** * Setter. * * @param index The index. * @param color The filling color or <code>null</code> if the default should * be used. */ public void setColor(final int index, final Color color) { ensureActive(index); final int cpos = getColorPosition(index); setColor(COLOR_FILL, cpos, color); } /** * Getter. * * @param index The index. * @return The filling color or <code>null</code> if the default color should * be used. */ public Color getColor(final int index) { ensureActive(index); final int cpos = getColorPosition(index); return getColor(COLOR_FILL, cpos); } /** * Setter. * * @param index The index. * @param color The border color or <code>null</code> if the default should be * used. */ public void setBorder(final int index, final Color color) { ensureActive(index); final int cpos = getColorPosition(index); setColor(COLOR_BORDER, cpos, color); } /** * Getter. * * @param index The index. * @return The border color or <code>null</code> if the default should be * used. */ public Color getBorder(final int index) { ensureActive(index); final int cpos = getColorPosition(index); return getColor(COLOR_BORDER, cpos); } /** * Sets the given shape for the point. * * @param shape The shape. * @param index The index. * @param x The x coordinate. * @param y The y coordinate. * @param s The size. */ protected abstract void setShape(T shape, int index, double x, double y, double s); @Override protected void paint(final Graphics2D gfx, final T shape, final int index, final int pos, final int cpos, final Composite defaultComposite) { final double x = get(X_COORD, pos); final double y = get(Y_COORD, pos); final double s = get(SIZE, pos); if(Double.isNaN(x) || Double.isNaN(y) || Double.isNaN(s)) return; setShape(shape, index, x, y, s); final Color fill = getColor(COLOR_FILL, cpos); if(fill != null || defaultColor != null) { gfx.setColor(fill != null ? fill : defaultColor); gfx.fill(shape); } final Color border = getColor(COLOR_BORDER, cpos); if(border != null || defaultBorder != null) { gfx.setColor(border != null ? border : defaultBorder); gfx.draw(shape); } } @Override protected boolean contains( final Point2D point, final T shape, final int index, final int pos) { final double x = get(X_COORD, pos); final double y = get(Y_COORD, pos); final double s = get(SIZE, pos); if(Double.isNaN(x) || Double.isNaN(y) || Double.isNaN(s)) return false; setShape(shape, index, x, y, s); return shape.contains(point); } public Rectangle2D getBoundingBoxFor(final int index) { final int pos = getPosition(index); final double x = get(X_COORD, pos); final double y = get(Y_COORD, pos); final double s = get(SIZE, pos); final T obj = createDrawObject(); setShape(obj, index, x, y, s); return obj.getBounds2D(); } }
package mcjty.lostcities; import mcjty.lostcities.commands.CommandDebug; import mcjty.lostcities.commands.CommandExportBuilding; import mcjty.lostcities.dimensions.world.lost.BuildingInfo; import mcjty.lostcities.dimensions.world.lost.Highway; import mcjty.lostcities.proxy.CommonProxy; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.*; @Mod(modid = LostCities.MODID, name="The Lost Cities", dependencies = "required-after:compatlayer@[" + LostCities.COMPATLAYER_VER + ",);" + "after:Forge@[" + LostCities.MIN_FORGE10_VER + ",);" + "after:forge@[" + LostCities.MIN_FORGE11_VER + ",)", version = LostCities.VERSION, acceptableRemoteVersions = "*", acceptedMinecraftVersions = "[1.10,1.12)") public class LostCities { public static final String MODID = "lostcities"; public static final String VERSION = "0.0.7beta"; public static final String MIN_FORGE10_VER = "12.18.1.2082"; public static final String MIN_FORGE11_VER = "13.19.0.2176"; public static final String COMPATLAYER_VER = "0.1.6"; @SidedProxy(clientSide="mcjty.lostcities.proxy.ClientProxy", serverSide="mcjty.lostcities.proxy.ServerProxy") public static CommonProxy proxy; @Mod.Instance("lostcities") public static LostCities instance; public static boolean chisel = false; public static boolean biomesoplenty = false; public static boolean atg = false; /** * Run before anything else. Read your config, create blocks, items, etc, and * register them with the GameRegistry. */ @Mod.EventHandler public void preInit(FMLPreInitializationEvent e) { chisel = Loader.isModLoaded("chisel"); biomesoplenty = Loader.isModLoaded("biomesoplenty") || Loader.isModLoaded("BiomesOPlenty"); // atg = Loader.isModLoaded("atg"); // @todo this.proxy.preInit(e); } /** * Do your mod setup. Build whatever data structures you care about. Register recipes. */ @Mod.EventHandler public void init(FMLInitializationEvent e) { this.proxy.init(e); } @Mod.EventHandler public void serverLoad(FMLServerStartingEvent event) { event.registerServerCommand(new CommandDebug()); event.registerServerCommand(new CommandExportBuilding()); BuildingInfo.cleanCache(); Highway.cleanCache(); } @Mod.EventHandler public void serverStopped(FMLServerStoppedEvent event) { BuildingInfo.cleanCache(); Highway.cleanCache(); } /** * Handle interaction with other mods, complete your setup based on this. */ @Mod.EventHandler public void postInit(FMLPostInitializationEvent e) { this.proxy.postInit(e); } }
package org.apdplat.word.util; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * * @author */ public class Utils { private static final Pattern PATTERN = Pattern.compile("^[\\u4e00-\\u9fa5]{2,}$"); /** * * @param word * @return */ public static boolean isChineseCharAndLengthAtLeastTwo(String word){ if(PATTERN.matcher(word).find()){ return true; } return false; } /** * MAPVALUE * @param <K> key * @param <V> value * @param map map * @return MAPVALUE */ public static <K, V extends Number> List<Map.Entry<K, V>> getSortedMapByValue(Map<K, V> map) { List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<K,V>>() { @Override public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { if(o1.getValue() instanceof Integer){ return o2.getValue().intValue() - o1.getValue().intValue(); } if(o1.getValue() instanceof Long){ return (int)(o2.getValue().longValue() - o1.getValue().longValue()); } if(o1.getValue() instanceof Float){ float f1 = o1.getValue().floatValue(); float f2 = o2.getValue().floatValue(); if(f1 < f2){ return 1; } if(f1 == f2){ return 0; } return -1; } if(o1.getValue() instanceof Double){ double f1 = o1.getValue().doubleValue(); double f2 = o2.getValue().doubleValue(); if(f1 < f2){ return 1; } if(f1 == f2){ return 0; } return -1; } return 0; } }); return list; } }
package org.cactoos.iterator; import java.util.Iterator; /** * Creates an iterator returning an interval(slice) of the original iterator * by means of providing starting index, number of elements to retrieve from * the starting index and a decorated original iterator. * * <p>There is no thread-safety guarantee.</p> * @param <T> The type of the iterator. * @since 1.0.0 * @todo #1190:30min This class to be refactored by extending IteratorEnvelope, * which will provide extra functionality to subclasses and is planned to be * added to Cactoos shortly. */ public final class Sliced<T> implements Iterator<T> { /** * Decorated iterator. */ private final Iterator<T> iterator; /** * Constructor. * @param start Starting index * @param count Maximum number of elements for resulted iterator * @param iterator Decorated iterator */ public Sliced(final int start, final int count, final Iterator<T> iterator) { this.iterator = new HeadOf<>( count, new Skipped<>( start, iterator ) ); } @Override public boolean hasNext() { return this.iterator.hasNext(); } @Override public T next() { return this.iterator.next(); } }
package com.indeed.proctor.consumer; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.indeed.proctor.common.ProctorResult; import com.indeed.proctor.common.model.ConsumableTestDefinition; import com.indeed.proctor.common.model.Payload; import com.indeed.proctor.common.model.TestBucket; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public abstract class AbstractGroups { private final ProctorResult proctorResult; private final LinkedHashMap<String, TestBucket> buckets; protected AbstractGroups(final ProctorResult proctorResult) { this.proctorResult = proctorResult; this.buckets = Maps.newLinkedHashMap(); for (final Entry<String, TestBucket> entry : proctorResult.getBuckets().entrySet()) { final TestBucket testBucket = entry.getValue(); this.buckets.put(entry.getKey(), testBucket); } } public Map<String, Integer> getTestVersions() { return proctorResult.getTestVersions(); } /** * @deprecated Use {@link #isBucketActive(String, int, int)} instead */ protected boolean isBucketActive(final String testName, final int value) { final TestBucket testBucket = buckets.get(testName); return ((testBucket != null) && (value == testBucket.getValue())); } protected boolean isBucketActive(final String testName, final int value, final int defaultValue) { final TestBucket testBucket = buckets.get(testName); if (null == testBucket) { return value == defaultValue; } else { return value == testBucket.getValue(); } } protected int getValue(final String testName, final int defaultValue) { final TestBucket testBucket = buckets.get(testName); if (testBucket == null) { return defaultValue; } return testBucket.getValue(); } public Map<String, Integer> getTestVersions(final Set<String> tests) { final Map<String, Integer> selectedTestVersions = Maps.newLinkedHashMap(); final Map<String, ConsumableTestDefinition> testDefinitions = proctorResult.getTestDefinitions(); for (final String testName : tests) { final ConsumableTestDefinition testDefinition = testDefinitions.get(testName); if (testDefinition != null) { selectedTestVersions.put(testName, testDefinition.getVersion()); } } return selectedTestVersions; } /** * Return the Payload attached to the current active bucket for |test|. * Always returns a payload so the client doesn't crash on a malformed * test definition. * * @deprecated Use {@link #getPayload(String, Bucket)} instead */ @Nonnull protected Payload getPayload(final String testName) { // Get the current bucket. final TestBucket testBucket = buckets.get(testName); // Lookup Payloads for this test if (testBucket != null) { final Payload payload = testBucket.getPayload(); if (null != payload) { return payload; } } return Payload.EMPTY_PAYLOAD; } @Nonnull protected Payload getPayload(final String testName, @Nonnull final Bucket<?> fallbackBucket) { // Get the current bucket. final TestBucket testBucket = buckets.get(testName); // Lookup Payloads for this test final Payload payload; if (testBucket != null) { payload = testBucket.getPayload(); } else { final TestBucket fallbackTestBucket = Preconditions.checkNotNull( getTestBucketForBucket(testName, fallbackBucket), "Invalid fallback bucket '%s' for test '%s'", fallbackBucket.getName(), testName); payload = fallbackTestBucket.getPayload(); } return Objects.firstNonNull(payload, Payload.EMPTY_PAYLOAD); } /** * Return the TestBucket, as defined in the current test matrix, for the test called testName with bucket value targetBucket.getValue(). * * Can return null if it can't find any such bucket. * * This does a linear search over the list of defined buckets. There shouldn't be too many buckets in any test, * so this should be fast enough. */ protected @Nullable TestBucket getTestBucketForBucket(final String testName, Bucket<?> targetBucket) { final @Nullable Map<String, ConsumableTestDefinition> testDefinitions = proctorResult.getTestDefinitions(); if (testDefinitions != null) { final @Nullable ConsumableTestDefinition testDefinition = testDefinitions.get(testName); if (testDefinition != null) { final @Nullable List<TestBucket> buckets = testDefinition.getBuckets(); if (buckets != null) { for (final TestBucket testBucket : buckets) { if (targetBucket.getValue() == testBucket.getValue()) { return testBucket; } } } } } return null; } public String toLongString() { if (proctorResult.getBuckets().isEmpty()) { return ""; } final StringBuilder sb = new StringBuilder(); for (final Entry<String, TestBucket> entry : proctorResult.getBuckets().entrySet()) { final String testName = entry.getKey(); final TestBucket testBucket = entry.getValue(); sb.append(testName).append('-').append(testBucket.getName()).append(','); } return sb.deleteCharAt(sb.length() - 1) .toString(); } /** * To be called when logging ONLY */ @Override public String toString() { if (isEmpty()) { return ""; } final StringBuilder sb = buildTestGroupString(); if (sb.length() == 0) { return ""; } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } public StringBuilder buildTestGroupString() { final StringBuilder sb = new StringBuilder(); appendTestGroups(sb); return sb; } public void appendTestGroups(final StringBuilder sb) { appendTestGroups(sb, ','); } /** * Return a value indicating if the groups are empty * and should be represented by an empty-string * {@link #toString()} * @return */ protected boolean isEmpty() { return proctorResult.getBuckets().isEmpty(); } /** * Appends each group to the StringBuilder using the separator to delimit * group names. the separator should be appended for each group added * to the string builder * * {@link #toString()} * {@link #buildTestGroupString()} or {@link #appendTestGroups(StringBuilder)} * @param sb */ public void appendTestGroups(final StringBuilder sb, char separator) { for (final Entry<String, TestBucket> entry : proctorResult.getBuckets().entrySet()) { final String testName = entry.getKey(); final TestBucket testBucket = entry.getValue(); if (testBucket.getValue() < 0) { continue; } sb.append(testName).append(testBucket.getValue()).append(separator); } } /** * Generates a Map that be serialized to JSON and used with * indeed.proctor.groups.init and * indeed.proctor.groups.inGroup(tstName, bucketValue) * * When we create a generated JavaScript representation of indeed.proctor.AbstractGroups, * this config can be updated for use in it's constructor. * * @return */ public Map<String, Integer> getJavaScriptConfig() { // For now this is a simple mapping from {testName to bucketValue} final Map<String, Integer> groups = Maps.newHashMapWithExpectedSize(proctorResult.getBuckets().size()); for (final Entry<String, TestBucket> entry : proctorResult.getBuckets().entrySet()) { final String testName = entry.getKey(); final TestBucket testBucket = entry.getValue(); // mirrors appendTestGroups method by skipping *inactive* tests if (testBucket.getValue() < 0) { continue; } groups.put(testName, testBucket.getValue()); } return groups; } public ProctorResult getProctorResult() { return proctorResult; } }
package org.ihtsdo.json; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import com.google.gson.Gson; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.Arrays; import org.ihtsdo.json.model.Concept; import org.ihtsdo.json.model.ConceptAncestor; import org.ihtsdo.json.model.ConceptDescriptor; import org.ihtsdo.json.model.Description; import org.ihtsdo.json.model.LangMembership; import org.ihtsdo.json.model.LightDescription; import org.ihtsdo.json.model.LightLangMembership; import org.ihtsdo.json.model.LightRefsetMembership; import org.ihtsdo.json.model.LightRelationship; import org.ihtsdo.json.model.RefsetMembership; import org.ihtsdo.json.model.Relationship; import org.ihtsdo.json.model.TextIndexDescription; /** * * @author Alejandro Rodriguez */ public class Transformer { private String MODIFIER = "Existential restriction"; private String sep = System.getProperty("line.separator"); private Map<Long, ConceptDescriptor> concepts; private Map<Long, List<LightDescription>> descriptions; private Map<Long, List<LightRelationship>> relationships; private Map<Long, List<LightRefsetMembership>> simpleMembers; private Map<Long, List<LightRefsetMembership>> simpleMapMembers; private Map<Long, List<LightLangMembership>> languageMembers; private Map<String, String> langCodes; private String defaultLangCode = "en"; public String fsnType = "900000000000003001"; public String synType = "900000000000013009"; private Long inferred = 900000000000011006l; private Long stated = 900000000000010007l; private Long isaSCTId=116680003l; private String defaultTermType = fsnType; private HashMap<Long, List<LightDescription>> tdefMembers; private HashMap<Long, List<LightRefsetMembership>> attrMembers; private HashMap<Long, List<LightRefsetMembership>> assocMembers; private ArrayList<Long> listA; private Map<String, String> charConv; public Transformer() { concepts = new HashMap<Long, ConceptDescriptor>(); descriptions = new HashMap<Long, List<LightDescription>>(); relationships = new HashMap<Long, List<LightRelationship>>(); simpleMembers = new HashMap<Long, List<LightRefsetMembership>>(); assocMembers = new HashMap<Long, List<LightRefsetMembership>>(); attrMembers = new HashMap<Long, List<LightRefsetMembership>>(); tdefMembers = new HashMap<Long, List<LightDescription>>(); simpleMapMembers = new HashMap<Long, List<LightRefsetMembership>>(); languageMembers = new HashMap<Long, List<LightLangMembership>>(); langCodes = new HashMap<String, String>(); langCodes.put("en", "english"); langCodes.put("es", "spanish"); langCodes.put("da", "danish"); langCodes.put("sv", "swedish"); langCodes.put("fr", "french"); langCodes.put("nl", "dutch"); } public static void main(String[] args) throws Exception { Transformer tr = new Transformer(); tr.setDefaultLangCode("da"); tr.setDefaultTermType(tr.synType); tr.loadConceptsFile(new File("/Users/termmed/Downloads/SnomedCT_Release_INT_20130731/RF2Release/Snapshot/Terminology/sct2_Concept_Snapshot_INT_20130731.txt")); tr.loadConceptsFile(new File("/Users/termmed/Downloads/1-1/SnomedCT_Release_DK1000005_20131018/RF2Release/Snapshot/Terminology/sct2_Concept_Snapshot_DK1000005_20131018.txt")); tr.loadDescriptionsFile(new File("/Users/termmed/Downloads/SnomedCT_Release_INT_20130731/RF2Release/Snapshot/Terminology/sct2_Description_Snapshot-en_INT_20130731.txt")); tr.loadDescriptionsFile(new File("/Users/termmed/Downloads/1-1/SnomedCT_Release_DK1000005_20131018/RF2Release/Snapshot/Terminology/sct2_Description_Snapshot_DK1000005_20131018.txt")); tr.loadTextDefinitionFile(new File("/Users/termmed/Downloads/SnomedCT_Release_INT_20130731/RF2Release/Snapshot/Terminology/Terminology/sct2_TextDefinition_Snapshot-en_INT_20130731.txt")); tr.loadRelationshipsFile(new File("/Users/termmed/Downloads/SnomedCT_Release_INT_20130731/RF2Release/Snapshot/Terminology/sct2_StatedRelationship_Snapshot_INT_20130731.txt")); tr.loadRelationshipsFile(new File("/Users/termmed/Downloads/1-1/SnomedCT_Release_DK1000005_20131018/RF2Release/Snapshot/Terminology/sct2_StatedRelationship_Snapshot_DK1000005_20131018.txt")); tr.loadRelationshipsFile(new File("/Users/termmed/Downloads/SnomedCT_Release_INT_20130731/RF2Release/Snapshot/Terminology/sct2_Relationship_Snapshot_INT_20130731.txt")); tr.loadRelationshipsFile(new File("/Users/termmed/Downloads/1-1/SnomedCT_Release_DK1000005_20131018/RF2Release/Snapshot/Terminology/sct2_Relationship_Snapshot_DK1000005_20131018.txt")); tr.loadSimpleRefsetFile(new File("/Users/termmed/Downloads/SnomedCT_Release_INT_20130731/RF2Release/Snapshot/Refset/Content/der2_Refset_SimpleSnapshot_INT_20130731.txt")); tr.loadSimpleMapRefsetFile(new File("/Users/termmed/Downloads/SnomedCT_Release_INT_20130731/RF2Release/Snapshot/Refset/Map/der2_sRefset_SimpleMapSnapshot_INT_20130731.txt")); tr.loadLanguageRefsetFile(new File("/Users/termmed/Downloads/SnomedCT_Release_INT_20130731/RF2Release/Snapshot/Terminology/der2_cRefset_LanguageSnapshot-en_INT_20130731.txt")); tr.loadLanguageRefsetFile(new File("/Users/termmed/Downloads/1-1/SnomedCT_Release_DK1000005_20131018/RF2Release/Snapshot/Refset/Language/der2_cRefset_LanguageSnapshot-da_DK1000005_20131018.txt")); tr.loadLanguageRefsetFile(new File("/Users/termmed/Downloads/1-1/SnomedCT_Release_DK1000005_20131018/RF2Release/Snapshot/Refset/Language/der2_cRefset_LanguageSnapshot-en_DK1000005_20131018.txt")); tr.loadAssociationFile(new File("/Users/termmed/Downloads/SnomedCT_Release_INT_20130731/RF2Release/Snapshot/Refset/Content/der2_cRefset_AssociationReferenceSnapshot_INT_20130731.txt")); tr.loadAttributeFile(new File("/Users/termmed/Downloads/SnomedCT_Release_INT_20130731/RF2Release/Snapshot/Refset/Content/der2_cRefset_AttributeValueSnapshot_INT_20130731.txt")); tr.createConceptsJsonFile("target/concepts.json"); tr.createTextIndexFile("target/text-index.json"); // tr.setDefaultLangCode("en"); // tr.setDefaultTermType(tr.synType); // tr.loadConceptsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Terminology/sct2_Concept_Snapshot_INT_20140131.txt")); // tr.loadDescriptionsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Terminology/sct2_Description_Snapshot-en_INT_20140131.txt")); // tr.loadTextDefinitionFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Terminology/sct2_TextDefinition_Snapshot-en_INT_20140131.txt")); // tr.loadRelationshipsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Terminology/sct2_StatedRelationship_Snapshot_INT_20140131.txt")); // tr.loadRelationshipsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Terminology/sct2_Relationship_Snapshot_INT_20140131.txt")); // tr.loadSimpleRefsetFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Refset/Content/der2_Refset_SimpleSnapshot_INT_20140131.txt")); // tr.loadAssociationFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Refset/Content/der2_cRefset_AssociationReferenceSnapshot_INT_20140131.txt")); // tr.loadAttributeFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Refset/Content/der2_cRefset_AttributeValueSnapshot_INT_20140131.txt")); // tr.loadSimpleMapRefsetFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Refset/Map/der2_sRefset_SimpleMapSnapshot_INT_20140131.txt")); // tr.loadLanguageRefsetFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Refset/Language/der2_cRefset_LanguageSnapshot-en_INT_20140131.txt")); // tr.createConceptsJsonFile("target/concepts.json"); // tr.createTClosures(); } public void createTClosures() throws IOException { loadConceptsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Terminology/sct2_Concept_Snapshot_INT_20140131.txt")); loadRelationshipsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Terminology//sct2_Relationship_Snapshot_INT_20140131.txt")); createTClosure("target/inferred_tc.txt",inferred); relationships = new HashMap<Long, List<LightRelationship>>(); loadRelationshipsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Terminology/sct2_StatedRelationship_Snapshot_INT_20140131.txt")); createTClosure("target/stated_tc.txt",stated); } public void loadConceptsFile(File conceptsFile) throws FileNotFoundException, IOException { System.out.println("Starting Concepts: " + conceptsFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(conceptsFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); ConceptDescriptor loopConcept = new ConceptDescriptor(); Long conceptId = Long.parseLong(columns[0]); loopConcept.setConceptId(conceptId); loopConcept.setActive(columns[2].equals("1")); loopConcept.setEffectiveTime(columns[1]); loopConcept.setModule(Long.parseLong(columns[3])); loopConcept.setDefinitionStatus(columns[4].equals("900000000000074008") ? "Primitive" : "Fully defined"); concepts.put(conceptId, loopConcept); line = br.readLine(); count++; if (count % 100000 == 0) { System.out.print("."); } } System.out.println("."); System.out.println("Concepts loaded = " + concepts.size()); } finally { br.close(); } } public void loadDescriptionsFile(File descriptionsFile) throws FileNotFoundException, IOException { System.out.println("Starting Descriptions: " + descriptionsFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(descriptionsFile), "UTF8")); int descriptionsCount = 0; try { String line = br.readLine(); line = br.readLine(); // Skip header boolean act; ConceptDescriptor cdesc; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); LightDescription loopDescription = new LightDescription(); loopDescription.setDescriptionId(Long.parseLong(columns[0])); act = columns[2].equals("1"); loopDescription.setActive(act); loopDescription.setEffectiveTime(columns[1]); Long sourceId = Long.parseLong(columns[4]); loopDescription.setConceptId(sourceId); loopDescription.setType(Long.parseLong(columns[6])); loopDescription.setTerm(columns[7]); loopDescription.setIcs(Long.parseLong(columns[8])); loopDescription.setModule(Long.parseLong(columns[3])); loopDescription.setLang(columns[5]); List<LightDescription> list = descriptions.get(sourceId); if (list == null) { list = new ArrayList<LightDescription>(); } list.add(loopDescription); descriptions.put(sourceId, list); if (act && columns[6].equals("900000000000003001") && columns[5].equals("en")) { cdesc = concepts.get(sourceId); if (cdesc != null && (cdesc.getDefaultTerm() == null || cdesc.getDefaultTerm().isEmpty())) { cdesc.setDefaultTerm(columns[7]); } } else if (act && columns[6].equals(defaultTermType) && columns[5].equals(defaultLangCode)) { cdesc = concepts.get(sourceId); if (cdesc != null) { cdesc.setDefaultTerm(columns[7]); } } line = br.readLine(); descriptionsCount++; if (descriptionsCount % 100000 == 0) { System.out.print("."); } } System.out.println("."); System.out.println("Descriptions loaded = " + descriptions.size()); } finally { br.close(); } } public void loadTextDefinitionFile(File textDefinitionFile) throws FileNotFoundException, IOException { System.out.println("Starting Text Definitions: " + textDefinitionFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(textDefinitionFile), "UTF8")); int descriptionsCount = 0; try { String line = br.readLine(); line = br.readLine(); // Skip header boolean act; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); LightDescription loopDescription = new LightDescription(); loopDescription.setDescriptionId(Long.parseLong(columns[0])); act = columns[2].equals("1"); loopDescription.setActive(act); loopDescription.setEffectiveTime(columns[1]); Long sourceId = Long.parseLong(columns[4]); loopDescription.setConceptId(sourceId); loopDescription.setType(Long.parseLong(columns[6])); loopDescription.setTerm(columns[7]); loopDescription.setIcs(Long.parseLong(columns[8])); loopDescription.setModule(Long.parseLong(columns[3])); loopDescription.setLang(columns[5]); List<LightDescription> list = tdefMembers.get(sourceId); if (list == null) { list = new ArrayList<LightDescription>(); } list.add(loopDescription); tdefMembers.put(sourceId, list); line = br.readLine(); descriptionsCount++; if (descriptionsCount % 100000 == 0) { System.out.print("."); } } System.out.println("."); System.out.println("Text Definitions loaded = " + tdefMembers.size()); } finally { br.close(); } } public void loadRelationshipsFile(File relationshipsFile) throws FileNotFoundException, IOException { System.out.println("Starting Relationships: " + relationshipsFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(relationshipsFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); LightRelationship loopRelationship = new LightRelationship(); loopRelationship.setActive(columns[2].equals("1")); loopRelationship.setEffectiveTime(columns[1]); loopRelationship.setModule(Long.parseLong(columns[3])); loopRelationship.setTarget(Long.parseLong(columns[5])); loopRelationship.setType(Long.parseLong(columns[7])); loopRelationship.setModifier(Long.parseLong(columns[9])); loopRelationship.setGroupId(Integer.parseInt(columns[6])); Long sourceId = Long.parseLong(columns[4]); loopRelationship.setSourceId(sourceId); loopRelationship.setCharType(Long.parseLong(columns[8])); List<LightRelationship> relList = relationships.get(sourceId); if (relList == null) { relList = new ArrayList<LightRelationship>(); } relList.add(loopRelationship); relationships.put(sourceId, relList); line = br.readLine(); count++; if (count % 100000 == 0) { System.out.print("."); } } System.out.println("."); System.out.println("Relationships loaded = " + relationships.size()); } finally { br.close(); } } public void loadSimpleRefsetFile(File simpleRefsetFile) throws FileNotFoundException, IOException { System.out.println("Starting Simple Refset Members: " + simpleRefsetFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(simpleRefsetFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); if (columns[2].equals("1")) { LightRefsetMembership loopMember = new LightRefsetMembership(); loopMember.setType(LightRefsetMembership.RefsetMembershipType.SIMPLE_REFSET.name()); loopMember.setUuid(UUID.fromString(columns[0])); loopMember.setActive(columns[2].equals("1")); loopMember.setEffectiveTime(columns[1]); loopMember.setModule(Long.parseLong(columns[3])); Long sourceId = Long.parseLong(columns[5]); loopMember.setReferencedComponentId(sourceId); loopMember.setRefset(Long.parseLong(columns[4])); List<LightRefsetMembership> list = simpleMembers.get(sourceId); if (list == null) { list = new ArrayList<LightRefsetMembership>(); } list.add(loopMember); simpleMembers.put(Long.parseLong(columns[5]), list); count++; if (count % 100000 == 0) { System.out.print("."); } } line = br.readLine(); } System.out.println("."); System.out.println("SimpleRefsetMember loaded = " + simpleMembers.size()); } finally { br.close(); } } public void loadAssociationFile(File associationsFile) throws FileNotFoundException, IOException { System.out.println("Starting Association Refset Members: " + associationsFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(associationsFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); if (columns[2].equals("1")) { LightRefsetMembership loopMember = new LightRefsetMembership(); loopMember.setType(LightRefsetMembership.RefsetMembershipType.ASSOCIATION.name()); loopMember.setUuid(UUID.fromString(columns[0])); loopMember.setActive(columns[2].equals("1")); loopMember.setEffectiveTime(columns[1]); loopMember.setModule(Long.parseLong(columns[3])); Long sourceId = Long.parseLong(columns[5]); loopMember.setReferencedComponentId(sourceId); loopMember.setRefset(Long.parseLong(columns[4])); loopMember.setCidValue(Long.parseLong(columns[6])); List<LightRefsetMembership> list = assocMembers.get(sourceId); if (list == null) { list = new ArrayList<LightRefsetMembership>(); } list.add(loopMember); assocMembers.put(Long.parseLong(columns[5]), list); count++; if (count % 100000 == 0) { System.out.print("."); } } line = br.readLine(); } System.out.println("."); System.out.println("AssociationMember loaded = " + assocMembers.size()); } finally { br.close(); } } public void loadAttributeFile(File attributeFile) throws FileNotFoundException, IOException { System.out.println("Starting Attribute Refset Members: " + attributeFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(attributeFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); if (columns[2].equals("1")) { LightRefsetMembership loopMember = new LightRefsetMembership(); loopMember.setType(LightRefsetMembership.RefsetMembershipType.ATTRIBUTE_VALUE.name()); loopMember.setUuid(UUID.fromString(columns[0])); loopMember.setActive(columns[2].equals("1")); loopMember.setEffectiveTime(columns[1]); loopMember.setModule(Long.parseLong(columns[3])); Long sourceId = Long.parseLong(columns[5]); loopMember.setReferencedComponentId(sourceId); loopMember.setRefset(Long.parseLong(columns[4])); loopMember.setCidValue(Long.parseLong(columns[6])); List<LightRefsetMembership> list = attrMembers.get(sourceId); if (list == null) { list = new ArrayList<LightRefsetMembership>(); } list.add(loopMember); attrMembers.put(Long.parseLong(columns[5]), list); count++; if (count % 100000 == 0) { System.out.print("."); } } line = br.readLine(); } System.out.println("."); System.out.println("AttributeMember loaded = " + attrMembers.size()); } finally { br.close(); } } public void loadSimpleMapRefsetFile(File simpleMapRefsetFile) throws FileNotFoundException, IOException { System.out.println("Starting SimpleMap Refset Members: " + simpleMapRefsetFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(simpleMapRefsetFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); if (columns[2].equals("1")) { LightRefsetMembership loopMember = new LightRefsetMembership(); loopMember.setType(LightRefsetMembership.RefsetMembershipType.SIMPLEMAP.name()); loopMember.setUuid(UUID.fromString(columns[0])); loopMember.setActive(columns[2].equals("1")); loopMember.setEffectiveTime(columns[1]); loopMember.setModule(Long.parseLong(columns[3])); Long sourceId = Long.parseLong(columns[5]); loopMember.setReferencedComponentId(sourceId); loopMember.setRefset(Long.parseLong(columns[4])); loopMember.setOtherValue(columns[6]); List<LightRefsetMembership> list = simpleMapMembers.get(sourceId); if (list == null) { list = new ArrayList<LightRefsetMembership>(); } list.add(loopMember); simpleMapMembers.put(sourceId, list); count++; if (count % 100000 == 0) { System.out.print("."); } } line = br.readLine(); } System.out.println("."); System.out.println("SimpleMap RefsetMember loaded = " + simpleMapMembers.size()); } finally { br.close(); } } public void loadLanguageRefsetFile(File languageRefsetFile) throws FileNotFoundException, IOException { System.out.println("Starting Language Refset Members: " + languageRefsetFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(languageRefsetFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); if (columns[2].equals("1")) { LightLangMembership loopMember = new LightLangMembership(); loopMember.setUuid(UUID.fromString(columns[0])); loopMember.setActive(columns[2].equals("1")); loopMember.setEffectiveTime(columns[1]); loopMember.setModule(Long.parseLong(columns[3])); Long sourceId = Long.parseLong(columns[5]); loopMember.setDescriptionId(sourceId); loopMember.setRefset(Long.parseLong(columns[4])); loopMember.setAcceptability(Long.parseLong(columns[6])); List<LightLangMembership> list = languageMembers.get(sourceId); if (list == null) { list = new ArrayList<LightLangMembership>(); } list.add(loopMember); languageMembers.put(sourceId, list); count++; if (count % 100000 == 0) { System.out.print("."); } } line = br.readLine(); } System.out.println("."); System.out.println("LanguageMembers loaded = " + languageMembers.size()); } finally { br.close(); } } public void createConceptsJsonFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException, IOException { System.out.println("Starting creation of " + fileName); FileOutputStream fos = new FileOutputStream(fileName); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw = new BufferedWriter(osw); Gson gson = new Gson(); List<LightDescription> listLD = new ArrayList<LightDescription>(); List<Description> listD = new ArrayList<Description>(); List<LightLangMembership> listLLM = new ArrayList<LightLangMembership>(); List<LangMembership> listLM = new ArrayList<LangMembership>(); List<LightRelationship> listLR = new ArrayList<LightRelationship>(); List<Relationship> listR = new ArrayList<Relationship>(); List<LightRefsetMembership> listLRM = new ArrayList<LightRefsetMembership>(); List<RefsetMembership> listRM = new ArrayList<RefsetMembership>(); // int count = 0; for (Long cptId : concepts.keySet()) { // count++; //if (count > 10) break; Concept cpt = new Concept(); ConceptDescriptor cptdesc = concepts.get(cptId); cpt.setConceptId(cptId); cpt.setActive(cptdesc.getActive()); cpt.setDefaultTerm(cptdesc.getDefaultTerm()); cpt.setEffectiveTime(cptdesc.getEffectiveTime()); cpt.setModule(cptdesc.getModule()); cpt.setDefinitionStatus(cptdesc.getDefinitionStatus()); listLD = descriptions.get(cptId); listD = new ArrayList<Description>(); if (listLD != null) { Long descId; for (LightDescription ldesc : listLD) { Description d = new Description(); d.setActive(ldesc.getActive()); d.setConceptId(ldesc.getConceptId()); descId = ldesc.getDescriptionId(); d.setDescriptionId(descId); d.setEffectiveTime(ldesc.getEffectiveTime()); d.setIcs(concepts.get(ldesc.getIcs())); d.setTerm(ldesc.getTerm()); d.setLength(ldesc.getTerm().length()); d.setModule(ldesc.getModule()); d.setType(concepts.get(ldesc.getType())); d.setLang(ldesc.getLang()); listLLM = languageMembers.get(descId); listLM = new ArrayList<LangMembership>(); if (listLLM != null) { for (LightLangMembership llm : listLLM) { LangMembership lm = new LangMembership(); lm.setActive(llm.getActive()); lm.setDescriptionId(descId); lm.setEffectiveTime(llm.getEffectiveTime()); lm.setModule(llm.getModule()); lm.setAcceptability(concepts.get(llm.getAcceptability())); lm.setRefset(concepts.get(llm.getRefset())); lm.setUuid(llm.getUuid()); listLM.add(lm); } if (listLM.isEmpty()) { d.setLangMemberships(null); } else { d.setLangMemberships(listLM); } } listLRM = attrMembers.get(descId); listRM = new ArrayList<RefsetMembership>(); if (listLRM != null) { for (LightRefsetMembership lrm : listLRM) { RefsetMembership rm = new RefsetMembership(); rm.setEffectiveTime(lrm.getEffectiveTime()); rm.setActive(lrm.getActive()); rm.setModule(lrm.getModule()); rm.setUuid(lrm.getUuid()); rm.setReferencedComponentId(descId); rm.setRefset(concepts.get(lrm.getRefset())); rm.setType(lrm.getType()); rm.setCidValue(concepts.get(lrm.getCidValue())); listRM.add(rm); } if (listRM.isEmpty()){ d.setRefsetMemberships(null); }else{ d.setRefsetMemberships(listRM); } }else{ d.setRefsetMemberships(null); } listD.add(d); } } listLD = tdefMembers.get(cptId); if (listLD != null) { Long descId; for (LightDescription ldesc : listLD) { Description d = new Description(); d.setActive(ldesc.getActive()); d.setConceptId(ldesc.getConceptId()); descId = ldesc.getDescriptionId(); d.setDescriptionId(descId); d.setEffectiveTime(ldesc.getEffectiveTime()); d.setIcs(concepts.get(ldesc.getIcs())); d.setTerm(ldesc.getTerm()); d.setLength(ldesc.getTerm().length()); d.setModule(ldesc.getModule()); d.setType(concepts.get(ldesc.getType())); d.setLang(ldesc.getLang()); listLLM = languageMembers.get(descId); listLM = new ArrayList<LangMembership>(); if (listLLM != null) { for (LightLangMembership llm : listLLM) { LangMembership lm = new LangMembership(); lm.setActive(llm.getActive()); lm.setDescriptionId(descId); lm.setEffectiveTime(llm.getEffectiveTime()); lm.setModule(llm.getModule()); lm.setAcceptability(concepts.get(llm.getAcceptability())); lm.setRefset(concepts.get(llm.getRefset())); lm.setUuid(llm.getUuid()); listLM.add(lm); } if (listLM.isEmpty()) { d.setLangMemberships(null); } else { d.setLangMemberships(listLM); } } listD.add(d); } } if (listD!=null && !listD.isEmpty()){ cpt.setDescriptions(listD); } else { cpt.setDescriptions(null); } listLR = relationships.get(cptId); listR = new ArrayList<Relationship>(); if (listLR != null) { for (LightRelationship lrel : listLR) { if (lrel.getCharType().equals(900000000000010007L)) { Relationship d = new Relationship(); d.setEffectiveTime(lrel.getEffectiveTime()); d.setActive(lrel.getActive()); d.setModule(lrel.getModule()); d.setGroupId(lrel.getGroupId()); d.setModifier(MODIFIER); d.setSourceId(cptId); d.setTarget(concepts.get(lrel.getTarget())); d.setType(concepts.get(lrel.getType())); d.setCharType(concepts.get(lrel.getCharType())); listR.add(d); } } if (listR.isEmpty()) { cpt.setStatedRelationships(null); } else { cpt.setStatedRelationships(listR); } } else { cpt.setStatedRelationships(null); } listLR = relationships.get(cptId); listR = new ArrayList<Relationship>(); if (listLR != null) { for (LightRelationship lrel : listLR) { if (lrel.getCharType().equals(900000000000011006L)) { Relationship d = new Relationship(); d.setEffectiveTime(lrel.getEffectiveTime()); d.setActive(lrel.getActive()); d.setModule(lrel.getModule()); d.setGroupId(lrel.getGroupId()); d.setModifier(MODIFIER); d.setSourceId(cptId); d.setTarget(concepts.get(lrel.getTarget())); d.setType(concepts.get(lrel.getType())); d.setCharType(concepts.get(lrel.getCharType())); listR.add(d); } } if (listR.isEmpty()) { cpt.setRelationships(null); } else { cpt.setRelationships(listR); } } else { cpt.setRelationships(null); } listLRM = simpleMembers.get(cptId); listRM = new ArrayList<RefsetMembership>(); if (listLRM != null) { for (LightRefsetMembership lrm : listLRM) { RefsetMembership d = new RefsetMembership(); d.setEffectiveTime(lrm.getEffectiveTime()); d.setActive(lrm.getActive()); d.setModule(lrm.getModule()); d.setUuid(lrm.getUuid()); d.setReferencedComponentId(cptId); d.setRefset(concepts.get(lrm.getRefset())); d.setType(lrm.getType()); listRM.add(d); } } listLRM = simpleMapMembers.get(cptId); if (listLRM != null) { for (LightRefsetMembership lrm : listLRM) { RefsetMembership d = new RefsetMembership(); d.setEffectiveTime(lrm.getEffectiveTime()); d.setActive(lrm.getActive()); d.setModule(lrm.getModule()); d.setUuid(lrm.getUuid()); d.setReferencedComponentId(cptId); d.setRefset(concepts.get(lrm.getRefset())); d.setType(lrm.getType()); d.setOtherValue(lrm.getOtherValue()); listRM.add(d); } } listLRM = assocMembers.get(cptId); if (listLRM != null) { for (LightRefsetMembership lrm : listLRM) { RefsetMembership d = new RefsetMembership(); d.setEffectiveTime(lrm.getEffectiveTime()); d.setActive(lrm.getActive()); d.setModule(lrm.getModule()); d.setUuid(lrm.getUuid()); d.setReferencedComponentId(cptId); d.setRefset(concepts.get(lrm.getRefset())); d.setType(lrm.getType()); d.setCidValue(concepts.get(lrm.getCidValue())); listRM.add(d); } } listLRM = attrMembers.get(cptId); if (listLRM != null) { for (LightRefsetMembership lrm : listLRM) { RefsetMembership d = new RefsetMembership(); d.setEffectiveTime(lrm.getEffectiveTime()); d.setActive(lrm.getActive()); d.setModule(lrm.getModule()); d.setUuid(lrm.getUuid()); d.setReferencedComponentId(cptId); d.setRefset(concepts.get(lrm.getRefset())); d.setType(lrm.getType()); d.setCidValue(concepts.get(lrm.getCidValue())); listRM.add(d); } } if (listRM.isEmpty()) { cpt.setMemberships(null); } else { cpt.setMemberships(listRM); } bw.append(gson.toJson(cpt).toString()); bw.append(sep); } bw.close(); System.out.println(fileName + " Done"); } public String getDefaultLangCode() { return defaultLangCode; } public void setDefaultLangCode(String defaultLangCode) { this.defaultLangCode = defaultLangCode; } private void createTClosure(String fileName,Long charType) throws IOException { System.out.println("Starting creation of " + fileName); FileOutputStream fos = new FileOutputStream(fileName); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw = new BufferedWriter(osw); Gson gson = new Gson(); // int count = 0; for (Long cptId : concepts.keySet()) { listA = new ArrayList<Long>(); getAncestors(cptId,charType); if (!listA.isEmpty()){ ConceptAncestor ca=new ConceptAncestor(); ca.setConceptId(cptId); ca.setAncestor(listA); bw.append(gson.toJson(ca).toString()); bw.append(sep); } } bw.close(); System.out.println(fileName + " Done"); } private void getAncestors(Long cptId,Long charType) { List<LightRelationship> listLR = new ArrayList<LightRelationship>(); listLR = relationships.get(cptId); if (listLR != null) { for (LightRelationship lrel : listLR) { if (lrel.getCharType().equals(charType) && lrel.getType().equals(isaSCTId) && lrel.getActive()) { Long tgt=lrel.getTarget(); if (!listA.contains(tgt)){ listA.add(tgt); getAncestors(tgt,charType); } } } } return ; } public void createTextIndexFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException, IOException { getCharConvTable(); System.out.println("Starting creation of " + fileName); FileOutputStream fos = new FileOutputStream(fileName); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw = new BufferedWriter(osw); Gson gson = new Gson(); // int count = 0; for (long conceptId : descriptions.keySet()) { // count++; //if (count > 10) break; for (LightDescription ldesc : descriptions.get(conceptId)) { TextIndexDescription d = new TextIndexDescription(); d.setActive(ldesc.getActive()); d.setTerm(ldesc.getTerm()); d.setLength(ldesc.getTerm().length()); d.setTypeId(ldesc.getType()); d.setConceptId(ldesc.getConceptId()); d.setDescriptionId(ldesc.getDescriptionId()); // using long lang names for Mongo 2.4.x text indexes d.setLang(langCodes.get(ldesc.getLang())); ConceptDescriptor concept = concepts.get(ldesc.getConceptId()); d.setConceptActive(concept.getActive()); d.setFsn(concept.getDefaultTerm()); if (d.getFsn() == null) { System.out.println("FSN Issue..." + d.getConceptId()); d.setFsn(d.getTerm()); } d.setSemanticTag(""); if (d.getFsn().endsWith(")")) { d.setSemanticTag(d.getFsn().substring(d.getFsn().lastIndexOf("(") + 1, d.getFsn().length() - 1)); } String cleanTerm = d.getTerm().replace("(", "").replace(")", "").trim().toLowerCase(); String convertedTerm=convertTerm(cleanTerm); String[] tokens = convertedTerm.toLowerCase().split("\\s+"); d.setWords(Arrays.asList(tokens)); bw.append(gson.toJson(d).toString()); bw.append(sep); } } bw.close(); System.out.println(fileName + " Done"); } private String convertTerm(String cleanTerm) { for (String code:charConv.keySet()){ String test="\\u" + code; String repl=charConv.get(code); cleanTerm=cleanTerm.replaceAll(test, repl); } return cleanTerm; } private void getCharConvTable() throws IOException { String charconvtable="src/main/resources/org/ihtsdo/util/char_conversion_table.txt"; BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(charconvtable), "UTF8")); br.readLine(); String line=null; charConv=new HashMap<String,String>(); while ((line=br.readLine())!=null){ String[] spl=line.split("\t",-1); String[]codes=spl[2].split(" "); for (String code:codes){ charConv.put(code,spl[0]); } } } public String getDefaultTermType() { return defaultTermType; } public void setDefaultTermType(String defaultTermType) { this.defaultTermType = defaultTermType; } }
package com.charlesmadere.hummingbird.models; import android.os.Parcel; import android.os.Parcelable; import com.charlesmadere.hummingbird.misc.ParcelableUtils; 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.annotations.SerializedName; public class MediaStory extends AbsStory implements Parcelable { @SerializedName("media") private AbsMedia mMedia; public AbsMedia getMedia() { return mMedia; } @Override public Type getType() { return Type.MEDIA_STORY; } @Override public void hydrate(final Feed feed) { super.hydrate(feed); mMedia.hydrate(feed); } @Override public String toString() { return getType().toString() + ':' + mMedia.toString(); } @Override protected void readFromParcel(final Parcel source) { super.readFromParcel(source); mMedia = ParcelableUtils.readMediaStoryAbsMediaFromParcel(source); } @Override public void writeToParcel(final Parcel dest, final int flags) { super.writeToParcel(dest, flags); ParcelableUtils.writeMediaStoryAbsMediaToParcel(mMedia, dest, flags); } public static final Creator<MediaStory> CREATOR = new Creator<MediaStory>() { @Override public MediaStory createFromParcel(final Parcel source) { final MediaStory ms = new MediaStory(); ms.readFromParcel(source); return ms; } @Override public MediaStory[] newArray(final int size) { return new MediaStory[size]; } }; public static abstract class AbsMedia implements Parcelable { @SerializedName("id") private String mId; public String getId() { return mId; } public abstract Type getType(); public abstract void hydrate(final Feed feed); @Override public int describeContents() { return 0; } protected void readFromParcel(final Parcel source) { mId = source.readString(); } @Override public void writeToParcel(final Parcel dest, final int flags) { dest.writeString(mId); } public enum Type implements Parcelable { @SerializedName("anime") ANIME, @SerializedName("manga") MANGA; public static Type from(final String type) { switch (type) { case "anime": return ANIME; case "manga": return MANGA; default: throw new IllegalArgumentException("encountered unknown " + Type.class.getName() + ": \"" + type + '"'); } } @Override public int describeContents() { return 0; } @Override public void writeToParcel(final Parcel dest, final int flags) { dest.writeInt(ordinal()); } public static final Creator<Type> CREATOR = new Creator<Type>() { @Override public Type createFromParcel(final Parcel source) { final int ordinal = source.readInt(); return values()[ordinal]; } @Override public Type[] newArray(final int size) { return new Type[size]; } }; } public static final JsonDeserializer<AbsMedia> JSON_DESERIALIZER = new JsonDeserializer<AbsMedia>() { @Override public AbsMedia deserialize(final JsonElement json, final java.lang.reflect.Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { final JsonObject jsonObject = json.getAsJsonObject(); final Type type = Type.from(jsonObject.get("type").getAsString()); final AbsMedia media; switch (type) { case ANIME: media = context.deserialize(json, AnimeMedia.class); break; case MANGA: media = context.deserialize(json, MangaMedia.class); break; default: throw new RuntimeException("encountered unknown " + Type.class.getName() + ": \"" + type + '"'); } return media; } }; } public static class AnimeMedia extends AbsMedia implements Parcelable { private AbsAnime mAnime; public AbsAnime getAnime() { return mAnime; } @Override public Type getType() { return Type.ANIME; } @Override public void hydrate(final Feed feed) { final String mediaId = getId(); for (final AbsAnime anime : feed.getAnime()) { if (mediaId.equalsIgnoreCase(anime.getId())) { mAnime = anime; break; } } } @Override public String toString() { return getType().toString() + ':' + mAnime.getTitle(); } @Override protected void readFromParcel(final Parcel source) { super.readFromParcel(source); mAnime = ParcelableUtils.readAbsAnimeFromParcel(source); } @Override public void writeToParcel(final Parcel dest, final int flags) { super.writeToParcel(dest, flags); ParcelableUtils.writeAbsAnimeToParcel(mAnime, dest, flags); } public static final Creator<AnimeMedia> CREATOR = new Creator<AnimeMedia>() { @Override public AnimeMedia createFromParcel(final Parcel source) { final AnimeMedia am = new AnimeMedia(); am.readFromParcel(source); return am; } @Override public AnimeMedia[] newArray(final int size) { return new AnimeMedia[size]; } }; } public static class MangaMedia extends AbsMedia implements Parcelable { @Override public Type getType() { return Type.MANGA; } @Override public void hydrate(final Feed feed) { } @Override public String toString() { return getType().toString(); } public static final Creator<MangaMedia> CREATOR = new Creator<MangaMedia>() { @Override public MangaMedia createFromParcel(final Parcel source) { final MangaMedia mm = new MangaMedia(); mm.readFromParcel(source); return mm; } @Override public MangaMedia[] newArray(final int size) { return new MangaMedia[size]; } }; } }